download all files

This commit is contained in:
Roman Pyrih
2025-06-24 14:14:35 +02:00
parent ebed09c00b
commit 4c71b5d9c2
72007 changed files with 10407727 additions and 40029 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
# About Newsletter Pro
--------
This module for PrestaShop allows you to create and send your own newsletters with different products from your store using many customizable templates.
## Tutorials
--------
- English : https://www.youtube.com/watch?v=NAbw7HhJfSo
- Français: https://www.youtube.com/watch?v=f6HMi4-k3EA
- Español: https://www.youtube.com/watch?v=dUddLn4QAJA
## More Info
--------
More information regards the installation of the module you can find in the file "readme_en.pdf"

View File

@@ -0,0 +1 @@
Deny from all

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,42 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
namespace PQNP;
use Tools;
class Path
{
public static function join()
{
$args = func_get_args();
$count = count($args);
$output = [];
foreach ($args as $key => $value) {
if ($key < $count - 1) {
$len = Tools::strlen($value);
$output[$key] = Tools::substr($value, $len - 1, $len) !== DIRECTORY_SEPARATOR ? $value . DIRECTORY_SEPARATOR : $value;
} else {
$output[$key] = $value;
}
}
return join('', $output);
}
}

View File

@@ -0,0 +1,96 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
abstract class NewsletterProApi
{
/**
* @var NewsletterProOutput
*/
protected $output;
/**
* @var NewsletterProRequest
*/
protected $request;
/**
* @var NewsletterProTranslate
*/
private $translate;
abstract public function call();
/**
* new NewsletterProApiCss(false, 'text/css');
* new NewsletterProApiMailchimp(true);
* new NewsletterProApiNewsletter(NewsletterProToken::getPublicToken(), 'text/html');.
*
* @param bool|string $token
* @param string $contentType
*
* @return void
*/
public function __construct($token = true, $contentType = 'text/plain')
{
$this->output = new NewsletterProOutput();
$this->request = new NewsletterProRequest();
$this->translate = new NewsletterProTranslate($this);
if (is_bool($token)) {
if ($token && !NewsletterProToken::isValidToken($this->request->get('token', ''))) {
exit('Invalid token');
}
} elseif (is_string($token)) {
if (!NewsletterProToken::validateToken($this->request->get('token', ''), $token)) {
exit('Invalid token');
}
}
if (isset($contentType)) {
header('Content-Type: '.$contentType);
}
}
public function l($string)
{
return $this->translate->l($string);
}
public static function getLink($action, $params = [], $token = false, $urldecode = false, $ssl = null, $idLang = null, $idShop = null, $relativeProtocol = false)
{
$ownParams = [];
if (is_bool($token)) {
if ($token) {
$ownParams['token'] = NewsletterProToken::getToken();
}
} elseif (is_string($token)) {
$ownParams['token'] = $token;
}
$ownParams['action'] = $action;
$link = Context::getContext()->link->getModuleLink(NewsletterProTools::module()->name, 'api', array_merge($ownParams, $params), $ssl, $idLang, $idShop, $relativeProtocol);
if ($urldecode) {
return urldecode($link);
}
return $link;
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiBounce extends NewsletterProApi
{
public function call()
{
$email = trim($this->request->get('email'));
if (!$email) {
exit($this->l('The email address field is empty.'));
}
$module = NewsletterProTools::module();
$bouceAction = $this->request->get('bounceAction');
$bouceActionActions = ['delete', 'unsubscribe'];
if (!in_array($bouceAction, $bouceActionActions)) {
exit($this->l(sprintf('The bounceAction should be [%s].', join(', ', $bouceActionActions))));
}
$bouceAction = (('delete' != $bouceAction && 'unsubscribe' != $bouceAction) ? 'delete' : $bouceAction);
$bouceMethod = 'delete' == $bouceAction ? (int) ('-1') : 0;
$actionMsg = (-1 == $bouceMethod ? $this->l('removed') : $this->l('unsubscribed'));
if (NewsletterProBounce::execute($email, [], $bouceMethod)) {
exit($this->l(sprintf('The bounced email %s has been %s from the database.', $email, $actionMsg)));
} else {
exit($this->l(sprintf('The bounced email %s has not been %s from the database. Maybe the email does not exists into database.', $email, $actionMsg)));
}
return $this->output->render();
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiCss extends NewsletterProApi
{
public function call()
{
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/css');
@ob_clean();
@ob_end_clean();
$context = Context::getContext();
if ($this->request->has('getSubscriptionCSS')) {
$idTemplate = $this->request->get('idTemplate');
if ($this->request->has('idShop')) {
$id_shop = (int) $this->request->get('idShop');
$shop = Shop::getShop($id_shop);
if ($shop) {
$context->shop = new Shop((int) $shop['id_shop']);
}
}
$template = new NewsletterProSubscriptionTpl((int) $idTemplate);
if (Validate::isLoadedObject($template)) {
exit((string) $template->css_style);
}
} elseif ($this->request->has('getNewsletterTemplateCSS') && $this->request->has('name')) {
$templateName = $this->request->get('name');
$idLang = (int) $this->request->get('id_lang');
try {
$template = NewsletterProTemplate::newFile($templateName)->load($idLang);
exit($template->css());
} catch (Exception $e) {
pqnp_log()->write($e->__toString(), NewsletterProLog::ERROR_FILE);
}
}
return $this->output->render();
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiMailchimp extends NewsletterProApi
{
public function call()
{
try {
$process = NewsletterProMailChimpWebhooks::newInstance()->process();
exit($process);
} catch (Exception $e) {
NewsletterProLog::writeStrip($e->getMessage(), NewsletterProLog::ERROR_FILE);
exit($e->getMessage());
}
return $this->output->render();
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiOpenedEmail extends NewsletterProApi
{
public function call()
{
$module = NewsletterProTools::module();
if (!$this->request->has('token')) {
exit('Invalid token');
}
$idTplHistory = (int) $module->getHistoryIdByToken($this->request->get('token'));
$email = $this->request->get('email');
if (0 == $idTplHistory) {
exit('Invalid token');
}
if (!$this->request->has('email')) {
exit('Invalid email address');
}
$openedEmail = new NewsletterProOpenedEmail();
if (!$openedEmail->isValid($idTplHistory, $email)) {
exit('Invalid token or email address');
}
if ($openedEmail->wasOpened()) {
exit('You already opened the template.');
}
$openedEmail->update();
return $this->output->render();
}
}

View File

@@ -0,0 +1,69 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiSyncChimp extends NewsletterProApi
{
public function call()
{
$module = NewsletterProTools::module();
if (!isset($module->chimp)) {
throw new Exception('The chimp is not defined');
}
$chimp = &$module->chimp;
ignore_user_abort(true);
set_time_limit(0);
@ini_set('max_execution_time', '0');
if (!NewsletterProConfig::test('LAST_DATE_CHIMP_SYNC')) {
NewsletterProConfig::save('LAST_DATE_CHIMP_SYNC', date('Y-m-d H:i:s'));
}
$dbFrom = NewsletterProConfig::get('LAST_DATE_CHIMP_SYNC');
if (strtotime($dbFrom)) {
$from = $dbFrom;
} else {
$from = date('Y-m-d H:i:s');
NewsletterProConfig::save('LAST_DATE_CHIMP_SYNC', $from);
}
$to = date('Y-m-d', strtotime('+1 days'));
if ($chimp->ping()) {
NewsletterProConfig::save('LAST_DATE_CHIMP_SYNC', date('Y-m-d H:i:s'));
}
if (Tools::isSubmit('forceSync')) {
$from = '0000-00-00 00:00:00';
}
$sync = $chimp->syncLists($from, $to);
$module->context->smarty->assign($sync);
$module->context->smarty->assign([
'last_date_chimp_sync' => NewsletterProConfig::get('LAST_DATE_CHIMP_SYNC'),
'chimp_last_date_sync_orders' => NewsletterProConfig::get('CHIMP_LAST_DATE_SYNC_ORDERS'),
'subscription_active' => (bool) pqnp_config('SUBSCRIPTION_ACTIVE'),
]);
return $module->context->smarty->fetch(pqnp_template_path($module->dir_location.'views/templates/admin/sync_chimp.tpl'));
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiSyncNewsletterBlock extends NewsletterProApi
{
public function call()
{
ignore_user_abort(true);
set_time_limit(0);
@ini_set('max_execution_time', '0');
$module = NewsletterProTools::module();
$response = Tools::jsonDecode($module->importEmailsFromBlockNewsletterCron(pqnp_config('LAST_DATE_NEWSLETTER_BLOCK_SYNC')), true);
echo '<pre>';
if (!empty($response['errors'])) {
echo $module->l('Errors');
echo '<br>';
echo '<br>';
exit(implode('<br>', $response['errors']));
} else {
pqnp_config('LAST_DATE_NEWSLETTER_BLOCK_SYNC', date('Y-m-d H:i:s'));
exit($response['msg']);
}
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProApiTask extends NewsletterProApi
{
public function call()
{
header('Access-Control-Allow-Origin: *');
$module = NewsletterProTools::module();
$today = new DateTime('now');
echo '<pre>';
echo 'Date : '.$today->format('Y-m-d H:i:s')."\n\n";
try {
if (NewsletterProTask::taskInProgress()) {
$task = NewsletterProTask::getTaskInProgress();
$taskExit = true;
$msg = "\n".$module->l('The task is in progress');
if ($task) {
if ($task->isTaskPaused()) {
$task->displayLog("\n")->emptyLog();
$msg = "\n".$module->l('The task is in paused');
} elseif ((strtotime($task->date_modified) + 120) <= time()) {
// start the task again after 2 minutes (300 seconds) if the date has not changes and the task status is showing in progress
echo $module->l('Task was forced to continue.');
$task->emptyLog();
$taskExit = false;
$task->displayLog("\n")->emptyLog();
$numSent = $task->send();
echo $msg;
exit;
} else {
$task->displayLog("\n")->emptyLog();
}
}
if ($taskExit) {
echo $msg;
exit;
}
}
$task = NewsletterProTask::getTask($today);
if ($task) {
$task->displayLog("\n")->emptyLog();
$numSent = $task->send();
echo "\n".sprintf($module->l('This script execution has sent %s emails.'), $numSent);
} else {
echo $module->l('There are no active task scheduled for today.');
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,110 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
namespace PQNP;
use Category;
use Context;
use Db;
class CategoryTree
{
public function getTree()
{
$root = Category::getRootCategory();
$root_id = $root->id;
$categories = Db::getInstance()->executeS('
SELECT c.`id_category`, cl.`name`, c.`id_parent`, c.`level_depth`, c.`active`
FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (
c.`id_category` = cl.`id_category`
AND cl.`id_lang` = '.(int) Context::getContext()->language->id.'
AND cl.`id_shop` = '.(int) Context::getContext()->shop->id.'
)
');
$categories_ids = [];
foreach ($categories as $category) {
$categories_ids[$category['id_category']] = $category;
}
unset($categories);
$tree = [];
$tree = $categories_ids[$root_id];
$this->addTreeChildrens($categories_ids, $tree);
return $tree;
}
public function getRoot()
{
$root = Category::getRootCategory();
return [
'id_category' => (int) $root->id,
'name' => $root->name,
'id_parent' => (int) $root->id_parent,
'level_depth' => (int) $root->level_depth,
'active' => (int) $root->active,
'childrens' => count($root->getChildrenWs()),
];
}
public function getChildrens($id_category)
{
$results = Db::getInstance()->executeS('
SELECT c.`id_category`, cl.`name`, c.`id_parent`, c.`level_depth`, c.`active`,
(
SELECT COUNT(gc_c.`id_category`)
FROM `'._DB_PREFIX_.'category` gc_c
WHERE gc_c.`id_parent` = c.`id_category`
) AS `childrens`
FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (
c.`id_category` = cl.`id_category`
AND cl.`id_lang` = '.(int) Context::getContext()->language->id.'
AND cl.`id_shop` = '.(int) Context::getContext()->shop->id.'
)
WHERE c.`id_parent` = '.(int) $id_category.'
');
return $results;
}
private function addTreeChildrens(&$categories_ids, &$node)
{
if (!isset($node['childrens'])) {
$node['childrens'] = [];
}
foreach ($categories_ids as $id_category => $category) {
if ($node['id_category'] == $category['id_parent']) {
$node['childrens'][] = $category;
if (count($node['childrens']) > 0) {
$category_ref = &$node['childrens'][count($node['childrens']) - 1];
$this->addTreeChildrens($categories_ids, $category_ref);
}
}
}
}
}

View File

@@ -0,0 +1,367 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
namespace PQNP;
use Configuration;
use Exception;
use ImageType;
use NewsletterPro;
use NewsletterProSubscriptionHook;
use NewsletterProTools;
use PQNP\Upgrade\Upgrade500;
class Config
{
const NAME = 'NEWSLETTER_PRO';
const DECODE_ERROR_LIMIT = 20;
const EVENT_CONFIG_SET = 'EVENT_CONFIG_SET';
protected static $initialized = false;
protected static $configuration;
protected static $ps_configuration_keys_cache;
public static function defaultConfig($key = null)
{
$data = [
'NEWSLETTER_TEMPLATE' => 'sample.html',
'PRODUCT_TEMPLATE' => 'sample.html',
'IMAGE_TYPE' => (
method_exists('ImageType', 'getFormattedName')
? ImageType::getFormattedName('home')
: (Version::isLower('1.5.1.0')
? 'home'
: 'home'.'_default')
),
'SLEEP' => '3',
'FWD_FEATURE_ACTIVE' => '1',
'CURRENCY' => (int) Configuration::get('PS_CURRENCY_DEFAULT'),
'LANG' => (int) Configuration::get('PS_LANG_DEFAULT'),
'CATEGORIES_DEPTH' => Version::isLower('1.5.0.5') ? 1 : 2,
'DISPLAY_PRODUCT_IMAGE' => '1',
'VIEW_ACTIVE_ONLY' => '1',
'SUBSCRIBE_BY_CATEGORY' => '1',
'SEND_NEWSLETTER_ON_SUBSCRIBE' => '0',
'SMTP_ACTIVE' => '0',
'SMTP' => '0',
'DEBUG_MODE' => '0',
'GOOGLE_ANALYTICS_ID' => '',
'TOKEN' => NewsletterProTools::module()->token,
'GOOGLE_ANALYTICS_ACTIVE' => '0',
'CAMPAIGN_ACTIVE' => '0',
'CAMPAIGN' => NewsletterProTools::module()->default_campaign_params,
'PRODUCT_LINK_REWRITE' => (int) Configuration::get('PS_REWRITING_SETTINGS'),
'ONLY_ACTIVE_PRODUCTS' => '1',
'GOOGLE_UNIVERSAL_ANALYTICS_ACTIVE' => '0',
'CONVERT_CSS_TO_INLINE_STYLE' => '1',
// subscription feature options
'SUBSCRIPTION_SECURE_SUBSCRIBE' => '1',
'SUBSCRIPTION_ACTIVE' => '0',
'LEFT_MENU_ACTIVE' => '1',
'CROSS_TYPE_CLASS' => 'np-icon-cross_5',
// send limit settings
'SEND_METHOD' => NewsletterPro::SEND_METHOD_DEFAULT, // 0 - Default, 1 - Anti flood. The values needs to be changed from the file init.js SEND_METHOD_DEFAULT and SEND_METHOD_ANTIFLOOD
'SEND_ANTIFLOOD_ACTIVE' => '1',
'SEND_ANTIFLOOD_EMAILS' => '100', // emails
'SEND_ANTIFLOOD_SLEEP' => '10', // seconds
'SEND_THROTTLER_ACTIVE' => '0',
'SEND_THROTTLER_LIMIT' => '100',
'SEND_THROTTLER_TYPE' => NewsletterPro::SEND_THROTTLER_TYPE_EMAILS, // 0 - Emails, 1 - MB. The values needs to be changed from the file init.js SEND_THROTTLER_TYPE_EMAILS and SEND_THROTTLER_TYPE_MB
'PAGE_HEADER_TOOLBAR' => [
'CSV' => 1,
'MANAGE_IMAGES' => 1,
'SELECT_PRODUCTS' => 1,
'CREATE_TEMPLATE' => 1,
'SEND_NEWSLETTERS' => 1,
'TASK' => 1,
'HISTORY' => 1,
'STATISTICS' => 1,
'CAMPAIGN' => 0,
'SMTP' => 1,
'MAILCHIMP' => 0,
'FORWARD' => 0,
'FRONT_SUBSCRIPTION' => 1,
'SETTINGS' => 0,
'TUTORIALS' => 1,
],
'SHOW_CLEAR_CACHE' => 0,
'SEND_EMBEDED_IMAGES' => 0,
'SHOW_CUSTOM_COLUMNS' => [],
'CHIMP_SYNC_UNSUBSCRIBED' => 1,
'SEND_LIMIT_END_SCRIPT' => 100,
'LAST_DATE_NEWSLETTER_BLOCK_SYNC' => '0000-00-00 00:00:00',
'CUSTOMER_SUBSCRIBE_BY_LOI' => '1',
'CUSTOMER_ACCOUNT_SUBSCRIBE_BY_LOI' => false,
'DISPLYA_MY_ACCOUNT_NP_SETTINGS' => '1',
'DEV_MODE' => '1',
'LOAD_MINIFIED' => true,
'SUBSCRIPTION_HOOK_POPUP_TYPE' => array_fill_keys(NewsletterProSubscriptionHook::getHooksUpper(), 0),
'SUBSCRIPTION_CONTROLLER_ENABLED' => false,
'SUBSCRIPTION_CONTROLLER_TEMPLATE_ID' => 0,
'EMAIL_MIME_TEXT' => true,
'TASK_MEMORY_CHECK_ENABLED' => true,
'CAMPAIGN' => [
'UTM_SOURCE' => 'Newsletter',
'UTM_MEDIUM' => 'email',
'UTM_CAMPAIGN' => '{newsletter_title}',
'UTM_CONTENT' => '{product_name}',
],
'CHIMP' => [
'INSTALLED' => false,
'API_KYE' => '',
'ID_LIST' => '',
'ID_GROUPING' => '',
'CUSTOMERS_GROUP_IDS' => [],
'FIELDS' => [],
'CUSTOMERS_CHECKBOX' => 0,
'VISITORS_CHECKBOX' => 0,
'ADDED_CHECKBOX' => 0,
'ORDERS_CHECKBOX' => 0,
],
];
if (is_null($key)) {
return $data;
}
if (!array_key_exists($key, $data)) {
throw new Exception(sprintf('Invalid get default configuration key [%s].', $key));
}
return $data[$key];
}
public static function psConfigutationKeys()
{
if (!isset(self::$ps_configuration_keys_cache)) {
self::$ps_configuration_keys_cache = array_keys(self::psDefault());
}
return self::$ps_configuration_keys_cache;
}
public static function psDefault()
{
return [
'PS_SHOP_EMAIL' => Configuration::get('PS_SHOP_EMAIL'),
'PS_MAIL_METHOD' => Configuration::get('PS_MAIL_METHOD'),
'PS_CURRENCY_DEFAULT' => Configuration::get('PS_CURRENCY_DEFAULT'),
'PS_LANG_DEFAULT' => Configuration::get('PS_LANG_DEFAULT'),
'PS_SHOP_DEFAULT' => Configuration::get('PS_SHOP_DEFAULT'),
'PS_MULTISHOP_FEATURE_ACTIVE' => Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE'),
'PS_LOGO_MAIL' => Configuration::get('PS_LOGO_MAIL'),
'PS_SHOP_NAME' => Configuration::get('PS_SHOP_NAME'),
'PS_LOCALE_COUNTRY' => Configuration::get('PS_LOCALE_COUNTRY'),
'PS_REWRITING_SETTINGS' => Configuration::get('PS_REWRITING_SETTINGS'),
];
}
public static function install()
{
return Configuration::updateValue(Config::NAME, json_encode(Config::defaultConfig()), false, 0, 0);
}
public static function init()
{
// this will convert the serizlized configuration into the json_encode configuration and also will solve te serialized bug
if (version_compare(NewsletterProTools::getDbVersion(), '5.0.0', '<')) {
if (false == (bool) Configuration::get('NEWSLETTER_PRO_CONFIGURATION_CALL')) {
Configuration::updateValue('NEWSLETTER_PRO_CONFIGURATION_CALL', true, false, 0, 0);
(new Upgrade500())->call();
}
}
$configuration_str = Configuration::get(Config::NAME);
$configuration = json_decode($configuration_str, true);
// this if for the installation proccess, will load the default configuration
if (Configuration::get(Config::NAME, null, null, null, 'null') === 'null') {
$configuration = self::defaultConfig();
} else if (!is_array($configuration) || (is_array($configuration) && count($configuration) < self::DECODE_ERROR_LIMIT)) {
throw new Exception('Unable the load the module configuration.');
}
$ps_configuration = self::psDefault();
$configuration = array_merge($configuration, $ps_configuration);
self::$configuration = $configuration;
self::$initialized = true;
}
public static function get($path = null, $defaultValue = null, $safe = false)
{
if (!self::$initialized) {
self::init();
}
$data = self::$configuration;
if (!isset($path)) {
return $data;
}
$parts = explode('.', $path);
$part_data = null;
if (count($parts) > 1) {
foreach ($parts as $part) {
if (!isset($part_data)) {
$part_data = $data;
}
if (!array_key_exists($part, $part_data)) {
if (true == $safe) {
return $defaultValue;
}
throw new Exception(sprintf('The module configuration [%s] does not exists into the database.', $path));
}
$part_data = $part_data[$part];
}
return $part_data;
} else {
if (!array_key_exists($path, $data)) {
if (true == $safe) {
return $defaultValue;
}
throw new Exception(sprintf('The module configuration [%s] does not exists into the database.', $path));
}
return $data[$path];
}
}
public static function write($path, $value, $safe = false)
{
return self::set($path, $value, true, $safe);
}
public static function set($path, $value, $write = false, $safe = false)
{
if (!self::$initialized) {
self::init();
}
Event::notify(Config::EVENT_CONFIG_SET, [
'path' => $path,
'value' => $value,
]);
$data = &self::$configuration;
$parts = explode('.', $path);
$part_data = null;
$count_parts = count($parts);
if ($count_parts > 0) {
foreach ($parts as $index => $part) {
if (!isset($part_data)) {
$part_data = &$data;
}
if (!$write && !array_key_exists($part, $part_data)) {
if ($safe) {
return false;
}
throw new Exception(sprintf('The module configuration [%s] does not exists into the database to be able to set it.', $path));
}
if ($index < $count_parts - 1) {
$part_data = &$part_data[$part];
}
}
$part_data[$part] = $value;
} else {
if (!$write && !array_key_exists($path, $data)) {
if ($safe) {
return false;
}
throw new Exception(sprintf('The module configuration [%s] does not exists into the database to be able to set it.', $path));
}
$data[$path] = $value;
}
$tmp = $data;
foreach (self::psConfigutationKeys() as $key) {
if (array_key_exists($key, $tmp)) {
unset($tmp[$key]);
}
}
if (count($tmp) < self::DECODE_ERROR_LIMIT) {
throw new Exception(sprintf('Unable to write the configuration. Configuration data is less than %s.', self::DECODE_ERROR_LIMIT));
}
if (!Configuration::updateValue(Config::NAME, json_encode($tmp), false, 0, 0)) {
if ($safe) {
return false;
}
throw new Exception(sprintf('Unable to write the configuration [%s] into database.', $path));
}
return true;
}
public static function delete($name)
{
if (!self::$initialized) {
self::init();
}
$data = &self::$configuration;
if (array_key_exists($name, $data)) {
unset($data[$name]);
}
if (false !== strpos($name, '.')) {
throw new Exception(sprintf('The dot notation deletion is not supported for [%s].', $name));
}
if (!Configuration::updateValue(Config::NAME, json_encode($data), false, 0, 0)) {
throw new Exception(sprintf('Unable to write the configuration [%s] into database.', $name));
}
return true;
}
public static function config($path = null, $value = null, $write = false)
{
if (isset($value)) {
return self::set($path, $value, $write);
}
return self::get($path);
}
public static function configSafe($path = null, $value = null, $write = false)
{
if (isset($value)) {
return self::set($path, $value, $write, true);
}
return self::get($path, null, true);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
namespace PQNP;
class Event
{
protected static $events = [];
public static function listen($event_name, callable $callback)
{
if (!isset(self::$events[$event_name])) {
self::$events[$event_name] = [];
}
self::$events[$event_name][] = $callback;
}
public static function detach($event_name)
{
if (array_key_exists($event_name, self::$events)) {
unset(self::$events[$event_name]);
}
}
public static function notify($event_name, $data)
{
if (array_key_exists($event_name, self::$events)) {
foreach (self::$events[$event_name] as $callback) {
call_user_func_array($callback, [$data]);
}
}
}
}

View File

@@ -0,0 +1,26 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,162 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
namespace PQNP;
use Db;
use Exception;
use Language;
use NewsletterProTemplate;
use NewsletterProTemplateHistory;
class HistoryExporter
{
protected $dest;
protected $export_dest;
public function __construct()
{
$this->dest = Path::join(_NEWSLETTER_PRO_DIR_, 'mail_templates/export_newsletter_history');
$this->export_dest = Path::join(_NEWSLETTER_PRO_DIR_, 'mail_templates/export');
}
public function export()
{
$templates = $this->getTemplates(false);
foreach ($templates as $template) {
$template_info = pathinfo($template['id'].'_'.$template['name']);
$name = $template_info['basename'];
$extension = $template_info['extension'];
$dirname = $template_info['filename'];
$dest = Path::join($this->dest, $dirname);
$this->createDir($dest);
$content_lang = $template['content'];
foreach ($content_lang as $iso_code => $content) {
$iso_code_dir = Path::join($dest, $iso_code);
$this->createDir($iso_code_dir);
$template_name_path = Path::join($iso_code_dir, $name);
if (file_put_contents($template_name_path, $content) === false) {
throw new Exception(sprintf('Unable to export the template "%s". Please check the CHMOD permissions.', $template_name_path));
}
}
}
}
public function downloadByIdHistory($id_history)
{
$template = NewsletterProTemplate::newHistory($id_history)->load();
return $template->export(false);
}
protected function getTemplates($with_unknown = false)
{
$results = Db::getInstance()->executeS('
SELECT th.`id_newsletter_pro_tpl_history`, th.`template_name`, thl.`id_lang`, thl.`template`
FROM `'._DB_PREFIX_.'newsletter_pro_tpl_history` th
LEFT JOIN `'._DB_PREFIX_.'newsletter_pro_tpl_history_lang` thl ON (
th.`id_newsletter_pro_tpl_history` = thl.`id_newsletter_pro_tpl_history`
)
');
$templates = [];
$languages = $this->getLanguages();
foreach ($results as $item) {
$id = $item['id_newsletter_pro_tpl_history'];
$name = $item['template_name'];
$id_lang = $item['id_lang'];
$template = $item['template'];
if (!isset($templates[$id])) {
$templates[$id] = [];
}
if (!isset($templates[$id]['content'])) {
$templates[$id]['content'] = [];
}
$templates[$id]['id'] = $id;
$templates[$id]['name'] = $name;
$key = null;
if (isset($languages[$id_lang])) {
$key = $languages[$id_lang]['iso_code'];
$templates[$id]['content'][$key] = $template;
} else if ($with_unknown) {
// not implement thie export of this
$key = $id_lang.'_unknown';
$templates[$id]['content'][$key] = $template;
}
}
return $templates;
}
protected function getLanguages($default = false)
{
$default_language_id = Config::get('PS_LANG_DEFAULT');
$languages = [];
foreach (Language::getLanguages(false) as $lang) {
$languages[$lang['id_lang']] = [
'id_lang' => $lang['id_lang'],
'iso_code' => $lang['iso_code'],
];
}
$default_language = $languages[$default_language_id];
if ($default) {
return $default_language;
}
return $languages;
}
protected function createDir($dest)
{
if (!file_exists($dest)) {
if (!mkdir($dest, 0755)) {
throw new Exception(sprintf('Unable to create the directory "%s".', $dest));
}
}
return $this->copyIndex($dest);
}
protected function copyIndex($target)
{
if (!file_exists($target)) {
throw new Exception(sprintf('The directoy does not exits "%s".', $target));
}
$index = Path::join($this->dest, 'index.php');
if (!file_exists($index)) {
throw new Exception(sprintf('The index file "%s" does not exists.', $index));
}
$target_index = Path::join($target, 'index.php');
if (!copy($index, $target_index)) {
throw new Exception(sprintf('Unable to copy the index file "%s" to the deistionation "%s".', $index, $target_index));
}
return true;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProAction
{
protected $response;
protected $request;
public function __construct()
{
$this->response = new NewsletterProResponse();
$this->request = new NewsletterProRequest();
}
public function call($action)
{
exit('Invalid Action');
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProAjaxResponse
{
public $errors = [];
public $data = [
'success' => false,
'errors' => [],
];
public function __construct($default_variables = [])
{
if (!empty($default_variables)) {
$this->data = array_merge($this->data, $default_variables);
}
}
public static function newInstance($default_variables = [])
{
return new self($default_variables);
}
public function set($key, $val)
{
$this->data[$key] = $val;
return $this;
}
public function setArray($array)
{
foreach ($array as $key => $value) {
$this->set($key, $value);
}
return $this;
}
public function getErrors()
{
return $this->errors;
}
public function addError($val)
{
$this->errors[] = $val;
return $this;
}
public function mergeErrors($errors = [])
{
$this->errors = array_merge($this->errors, $errors);
return $this;
}
public function success()
{
return empty($this->errors);
}
public function display()
{
if ($this->success()) {
$this->data['status'] = true;
$this->data['success'] = true;
$this->data['errors'] = &$this->errors;
} else {
$this->data['success'] = false;
$this->data['status'] = false;
$this->data['errors'] = &$this->errors;
}
return self::jsonEncode($this->data);
}
public static function jsonEncode($array)
{
@header('Content-Type: application/json');
return Tools::jsonEncode($array);
}
public function displayArray()
{
return $this->data;
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
use PQNP\CategoryTree;
class NewsletterProAppStorage
{
private static $extend_data = [];
public static function get($entry)
{
$module = NewsletterProTools::module();
$context = Context::getContext();
switch ($entry) {
case 'app':
$iso = file_exists(_PS_JS_DIR_.'tiny_mce/langs/'.$context->language->iso_code.'.js') ? $context->language->iso_code : 'en';
if (defined('_PS_CORE_DIR_')) {
$iso = file_exists(_PS_CORE_DIR_.'/js/tiny_mce/langs/'.$context->language->iso_code.'.js') ? $context->language->iso_code : 'en';
}
return array_merge([
'categories' => (new CategoryTree())->getTree(),
'tinymce' => [
'iso' => $iso,
'path_css' => _THEME_CSS_DIR_,
'ad' => __PS_BASE_URI__.basename(_PS_ADMIN_DIR_),
],
], self::$extend_data);
case 'app_front':
return array_merge([
'ajax_url' => $context->link->getModuleLink('newsletterpro', 'ajax', []),
'config' => [
'CROSS_TYPE_CLASS' => pqnp_config('CROSS_TYPE_CLASS'),
],
], self::$extend_data);
}
throw new Exception(sprintf('The entry "%s" is not defined.', $entry));
}
public static function extend($data = [])
{
self::$extend_data = array_merge(self::$extend_data, $data);
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProAppTranslate
{
public static function get($entry)
{
$translate = new NewsletterProTranslate(__CLASS__);
switch ($entry) {
case 'app':
return [
'global' => [
],
'CategoryTree' => [
'Expand All' => $translate->l('Expand All'),
'Check All' => $translate->l('Check All'),
'Uncheck All' => $translate->l('Uncheck All'),
],
'CategoryTreeSearch' => [
'search...' => $translate->l('search...'),
],
];
case 'app_front':
return [
'global' => [
],
'ajax' => [
'Oops, an error has occurred.' => $translate->l('Oops, an error has occurred.'),
'Error: The AJAX response is not JSON type.' => $translate->l('Error: The AJAX response is not JSON type.'),
],
'popup' => [
'Oops, an error has occurred.' => $translate->l('Oops, an error has occurred.'),
'close in %s seconds' => $translate->l('close in %s seconds'),
],
];
}
throw new Exception(sprintf('The entry "%s" is not defined.', $entry));
}
}

View File

@@ -0,0 +1,300 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProAttachment extends ObjectModel
{
public $template_name;
public $files;
private $files_array;
private $dir_mails;
private $dir_attachments;
public static $definition = [
'table' => 'newsletter_pro_attachment',
'primary' => 'id_newsletter_pro_attachment',
'fields' => [
'template_name' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true],
'files' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
],
];
public function __construct($id = null)
{
parent::__construct($id);
$this->dir_mails = NewsletterPro::getInstance()->tpl_location;
$this->dir_attachments = $this->dir_mails.'attachments/';
$this->files_array = NewsletterProTools::unSerialize($this->files);
}
public static function newInstance($id = null)
{
return new self($id);
}
public static function getTemplateAttachmentId($template_name)
{
$id = (int) Db::getInstance()->getValue('
SELECT `id_newsletter_pro_attachment`
FROM `'._DB_PREFIX_.'newsletter_pro_attachment`
WHERE `template_name` = "'.pSQL($template_name).'"
');
return $id;
}
public static function newInstanceByTemplateName($template_name)
{
$id = self::getTemplateAttachmentId($template_name);
$instance = new self($id);
return Validate::isLoadedObject($instance) ? $instance : false;
}
public function template($template_name)
{
$this->template_name = $template_name;
return $this;
}
public function attach($filename, $new_name = null, $copy = false)
{
if (!file_exists($filename)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The filename "%s" does not exists.'), $filename));
}
if (!NewsletterProTemplate::templateExists($this->template_name)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The template "%s" does not exists.'), $this->template_name));
}
if (!isset($new_name)) {
$basename = pathinfo($filename, PATHINFO_BASENAME);
$attachment_name = uniqid().'_'.$basename;
} else {
$attachment_name = uniqid().'_'.$new_name;
}
$attachment_filename = $this->dir_attachments.$attachment_name;
if (!$copy) {
if (!move_uploaded_file($filename, $attachment_filename)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The file "%s" cannot be attached. Please check the CHMOD permissions.'), $filename));
}
} else {
if (!copy($filename, $attachment_filename)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The file "%s" cannot be attached. Please check the CHMOD permissions.'), $filename));
}
}
$this->files_array[] = $attachment_name;
$this->files = serialize($this->files_array);
if ($this->save()) {
return true;
} else {
if (is_file($attachment_filename)) {
@unlink($attachment_filename);
}
return false;
}
}
public function detach($name)
{
$filename = $this->dir_attachments.$name;
if (file_exists($filename) && is_file($filename)) {
$unlink = unlink($filename);
}
$key = array_search($name, $this->files_array);
if (is_int($key)) {
unset($this->files_array[$key]);
$this->files_array = array_values($this->files_array);
$this->files = serialize($this->files_array);
$this->save();
}
return $unlink;
}
public function hasFile($name)
{
return in_array($name, $this->files_array);
}
public function files()
{
return $this->files_array;
}
public function filesPath()
{
$filespath = [];
foreach ($this->files() as $file) {
$path = $this->dir_attachments.$file;
if (file_exists($path) && is_readable($path) && is_file($path)) {
$filespath[] = $path;
}
}
return $filespath;
}
public function filesPathFilename()
{
$fpn = [];
foreach ($this->filesPath() as $fp) {
$fpn[] = [
'path' => $fp,
'name' => self::getRealName($fp),
];
}
return $fpn;
}
public static function getRealName($file)
{
$name = pathinfo($file, PATHINFO_BASENAME);
$real_name = $name;
$pos = strpos($name, '_');
if (false !== $pos) {
$real_name = Tools::substr($name, $pos + 1);
}
return $real_name;
}
public static function getTemplatesName()
{
$results = Db::getInstance()->executeS('
SELECT `template_name` FROM `'._DB_PREFIX_.'newsletter_pro_attachment`
');
$templates_name = [];
foreach ($results as $row) {
$templates_name[] = $row['template_name'];
}
return $templates_name;
}
public static function ajaxGetAttachments($template_name)
{
$results = [];
$attachment = self::newInstanceByTemplateName($template_name);
if ($attachment) {
foreach ($attachment->files() as $name) {
$results[] = [
'id_newsletter_pro_attachment' => $attachment->id,
'filename' => $name,
];
}
}
return Tools::jsonEncode($results);
}
public static function ajaxDeleteAttachment($id, $filename)
{
$response = NewsletterProAjaxResponse::newInstance();
try {
$attachment = self::newInstance($id);
if (!Validate::isLoadedObject($attachment)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The attachment with id "%s" does not exists.'), $id));
}
if (!$attachment->hasFile($filename)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The attachment filename "%s" does not exists.'), $filename));
}
if (!$attachment->detach($filename)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('An error occurred, please check the CHMOD permissions.')));
}
$files = $attachment->files();
if (empty($files)) {
$attachment->delete();
}
} catch (Exception $e) {
$response->addError($e->getMessage());
}
return $response->display();
}
public static function ajaxTemplateAttachFile($file, $template_name)
{
$response = NewsletterProAjaxResponse::newInstance();
try {
$name = $file['name'];
if (!preg_match('/^((?!.*php$|.*js$).*)$/i', $name)) {
throw new NewsletterProAttachmentException(sprintf(NewsletterPro::getInstance()->l('The file extension is not allowed.')));
}
$message = NewsletterPro::getInstance()->verifyFileErros($file);
if (true === $message) {
$attachment = self::newInstanceByTemplateName($template_name);
if (!$attachment) {
$attachment = self::newInstance();
$attachment->template($template_name);
}
$attachment->attach($file['tmp_name'], $name);
} else {
$response->addError($message);
}
} catch (Exception $e) {
$response->addError($e->getMessage());
}
return $response->display();
}
public static function setAttachmentToMessage($template_name, &$message)
{
// add attachments
$attachment = self::newInstanceByTemplateName($template_name);
if ($attachment) {
$files = $attachment->filesPathFilename();
if (!empty($files)) {
foreach ($files as $file) {
$attach = NewsletterPro_Swift_Attachment::fromPath($file['path'])->setFilename($file['name']);
$message->attach($attach);
}
}
}
}
}

View File

@@ -0,0 +1,21 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProAttachmentException extends Exception
{
}

View File

@@ -0,0 +1,115 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProAutoload
{
private static $instance;
protected $classes_path;
protected $api_path;
protected $controllers_path;
protected $libraries_path;
public function __construct()
{
if (!isset(self::$instance)) {
self::$instance = &$this;
}
$this->classes_path = _NEWSLETTER_PRO_DIR_.'/classes/';
$this->api_path = _NEWSLETTER_PRO_DIR_.'/classes/Api/';
$this->controllers_path = _NEWSLETTER_PRO_DIR_.'/controllers/';
$this->libraries_path = _NEWSLETTER_PRO_DIR_.'/libraries/';
$this->exceptions_path = _NEWSLETTER_PRO_DIR_.'/classes/exceptions/';
}
public static function newInstance()
{
return new self();
}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function init()
{
spl_autoload_register([$this, 'loadClasses']);
spl_autoload_register([$this, 'loadApi']);
spl_autoload_register([$this, 'loadControllers']);
spl_autoload_register([$this, 'loadLibraries']);
spl_autoload_register([$this, 'loadExceptions']);
}
public function loadClasses($class)
{
if ($class) {
$filename = $this->classes_path.$class.'.php';
if (file_exists($filename)) {
require_once $filename;
}
}
}
public function loadApi($class)
{
if ($class) {
$filename = $this->api_path.$class.'.php';
if (file_exists($filename)) {
require_once $filename;
}
}
}
public function loadControllers($class)
{
if ($class) {
$filename = $this->controllers_path.$class.'.php';
if (file_exists($filename)) {
require_once $filename;
}
}
}
public function loadLibraries($class)
{
if ($class) {
$filename = $this->libraries_path.$class.'.php';
if (file_exists($filename)) {
require_once $filename;
}
}
}
public function loadExceptions($class)
{
if ($class) {
$filename = $this->exceptions_path.$class.'.php';
if (file_exists($filename)) {
require_once $filename;
}
}
}
}

View File

@@ -0,0 +1,315 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProBackupSql
{
public $load_configuration;
public $load_configuration_shop;
public $load_tables;
public $load_data;
public $module;
public $header;
public function __construct()
{
$this->module = NewsletterPro::getInstance();
$this->header = [];
}
public static function path()
{
return realpath(dirname(__FILE__).'/../backup');
}
public static function formatName($path_name, $timestamp = false)
{
return preg_replace('/\s+/', '_', trim(Tools::strtolower($path_name))).($timestamp ? '_'.time() : '').'.php';
}
public static function pathNameExists($path_name, $md5 = false)
{
if ($md5) {
$path_name = self::formatMD5($path_name);
}
return file_exists(self::path().'/'.$path_name);
}
public static function pathName($path_name)
{
return self::path().'/'.$path_name;
}
public static function formatMD5($path_name)
{
$info_name = pathinfo($path_name, PATHINFO_FILENAME);
$info_extension = pathinfo($path_name, PATHINFO_EXTENSION);
$info_dirname = pathinfo($path_name, PATHINFO_DIRNAME);
$name = md5($info_name).($info_extension ? '.'.$info_extension : '');
$path_name = $info_dirname.'/'.$name;
return $path_name;
}
public function save($path_name, $format = true, $md5 = true)
{
$name = basename($path_name);
$name_display = $name;
if ($md5) {
$path_name = self::formatMD5($path_name);
}
if ($format) {
$path_filename = self::formatName($path_name);
} else {
$path_filename = $path_name;
}
$filename = basename($path_filename);
$this->setHeader('filename', $filename);
$this->setHeader('date', date('Y-m-d H:i:s', time()));
$this->setHeader('module_version', $this->module->version);
$this->setHeader('name', $name_display);
if (!isset($this->header['configuration_shop'])) {
$this->setHeader('configuration_shop', serialize([]));
}
if (!isset($this->header['configuration'])) {
$this->setHeader('configuration', serialize([]));
}
$header = '<?php exit; ?>'."\n";
$header .= $this->displayHeader();
$mysql = new NewsletterProMySQLDump(false);
$mysql->setHeader($header);
foreach ($this->tables as $table_name) {
$mysql->addTable($table_name);
}
return $mysql->save(self::path().'/'.$path_filename);
}
public function setHeader($name, $value)
{
$this->header[$name] = $value;
}
public function displayHeader()
{
$header = '';
$header .= "-- begin header\n";
foreach (array_reverse($this->header) as $name => $value) {
$header .= '-- '.$name.': '.$value."\n";
}
$header .= "-- end header\n";
$header .= "\n";
return $header;
}
public function create(array $tables)
{
$this->tables = $tables;
$tables_header = [];
foreach ($this->tables as $table_name) {
$tables_header[] = _DB_PREFIX_.$table_name;
}
$this->setHeader('tables', implode(',', $tables_header));
}
public static function getList($path = '')
{
$dirs = new DirectoryIterator(self::path().'/'.$path);
$files = new RegexIterator($dirs, '/.php$/', RecursiveRegexIterator::MATCH);
$results = [];
foreach ($files as $file) {
$file_basename = '';
if (method_exists($file, 'getBasename')) {
$file_basename = $file->getBasename();
} else {
$file_basename = basename($file->getFilename());
}
if ('index.php' !== $file_basename) {
$header = self::getLoadDataHeaderFilename($file->getPathname());
$header_name = 'Undefined';
if (isset($header['name'])) {
$header_name = $header['name'];
}
$item = [];
$item['m_date'] = date('Y-m-d H:i:s', $file->getMTime());
$item['name'] = $file_basename;
$item['name_display'] = Tools::ucfirst(str_replace('_', ' ', preg_replace('/\.php$/', '', $header_name)));
$item['filename'] = $file->getPathname();
$item['module_version'] = (isset($header['module_version']) ? $header['module_version'] : '0.00');
$results[] = $item;
}
}
return $results;
}
public static function getLoadDataHeaderFilename($filename)
{
$header = [];
if (file_exists($filename)) {
if ($file = fopen($filename, 'r')) {
$working_data = '';
while (!feof($file) && (0 == connection_status())) {
$working_data_temp = fread($file, 1024);
$working_data .= $working_data_temp;
$start_string = '-- end header';
$start = strpos($working_data, $start_string);
if (false !== $start) {
break;
}
flush();
}
fclose($file);
$header = self::getLoadDataHeader($working_data);
}
}
return $header;
}
public function load($path_name)
{
if (!self::pathNameExists($path_name)) {
throw new Exception(sprintf($this->module->l('The filename "%s" does not exists anymore.'), basename($path_name)));
}
$this->load_data = @Tools::file_get_contents(self::pathName($path_name));
if (false === $this->load_data) {
throw new Exception(sprintf($this->module->l('The filename "%s" is not readable. Please check the CHMOD permissions.'), basename($path_name)));
}
// if the file is php will remove the exit statement
$start_str = '<?php exit; ?>';
$start = strpos($this->load_data, $start_str);
if (false !== $start) {
$this->load_data = trim(Tools::substr($this->load_data, Tools::strlen($start_str)));
}
$header = self::getLoadDataHeader($this->getLoadDataHeaderString());
$this->load_tables = [];
if (isset($header['tables'])) {
$this->load_tables = explode(',', $header['tables']);
}
$this->load_configuration_shop = [];
if (isset($header['configuration_shop'])) {
$this->load_configuration_shop = NewsletterProTools::unSerialize($header['configuration_shop']);
}
$this->load_configuration = [];
if (isset($header['configuration'])) {
$this->load_configuration = NewsletterProTools::unSerialize($header['configuration']);
}
}
public function execute()
{
if (!$this->emptyTables()) {
throw new Exception($this->module->l('An error occurred when deleting the current data.'));
}
if (!NewsletterProConfigurationShop::replaceShopsCondiguration($this->load_configuration_shop)) {
throw new Exception($this->module->l('An error occurred when updating the configuration.'));
}
return Db::getInstance()->execute($this->load_data);
}
public function tableExists($table_name)
{
return count(Db::getInstance()->executeS('SHOW TABLES LIKE "'.pSQL($table_name).'"'));
}
public function getTableFields($table_name)
{
$fields = [];
$result = Db::getInstance()->executeS('SHOW FIELDS FROM `'.pSQL($table_name).'`');
foreach ($result as $value) {
$fields[$value['Field']] = $value['Default'];
}
return $fields;
}
public function emptyTables()
{
$success = [];
foreach ($this->load_tables as $table_name) {
$success[] = Db::getInstance()->execute('DELETE FROM `'.pSQL($table_name).'` WHERE 1');
}
return !in_array(false, $success);
}
public function getLoadDataHeaderString()
{
$header = '';
$start_match = '-- begin header';
$end_match = '-- end header';
$start = strpos($this->load_data, $start_match);
$end = strpos($this->load_data, $end_match);
if (false !== $start && false !== $end) {
$header = trim(Tools::substr($this->load_data, ($start + Tools::strlen($start_match)), ($end - Tools::strlen($start_match))));
}
return $header;
}
public static function getLoadDataHeader($header_str)
{
$header = [];
$header_lines = preg_split('/--\s/m', $header_str);
foreach ($header_lines as $line) {
if (preg_match('/^(?P<key>\w+):\s(?P<value>.*)$/', $line, $match)) {
$header[$match['key']] = trim($match['value']);
}
}
return $header;
}
}

View File

@@ -0,0 +1,443 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
use PQNP\Config;
class NewsletterProBackupXml
{
public $load_configuration;
public $load_configuration_campaign;
public $load_configuration_shop;
public $load_hooks;
public $load_tables;
public $load_data;
public $load_xml;
public $module;
public $headers;
public $tables;
public $hex;
public $default_path;
const PHP_HEADER = '<?php exit; ?>';
public function __construct($default_path = null)
{
$this->module = NewsletterPro::getInstance();
$this->headers = [];
if (!isset($default_path)) {
$this->default_path = self::path();
} else {
$this->default_path = $default_path;
}
}
/**
* Get the backup folder dirname.
*
* @return string Folder dirname
*/
public static function path()
{
return realpath(dirname(__FILE__).'/../backup');
}
/**
* Format pathname
* Ex: subscription/file name 123 -> subscription/file_name_123.php.
*
* @param string $path_name Pathname
* @param bool $timestamp Append a timestamp at the end of the filename
*
* @return string Formated path name
*/
public static function formatName($path_name, $timestamp = false)
{
return preg_replace('/\s+/', '_', trim(Tools::strtolower($path_name))).($timestamp ? '_'.time() : '').'.php';
}
/**
* Check if the path name exists.
*
* @param string $path_name Pathname
*
* @return bool
*/
public static function pathNameExists($path_name, $md5 = false)
{
if ($md5) {
$path_name = self::formatMD5($path_name);
}
return file_exists(self::path().'/'.$path_name);
}
/**
* Get the path dirname.
*
* @param string $path_name Pathname
*
* @return string
*/
public static function pathName($path_name)
{
return self::path().'/'.$path_name;
}
/**
* Setup the backup header information.
*
* @param string $name Header hey
* @param string $value Header value
*/
public function addHeader($name, $value)
{
$this->headers[$name] = $value;
}
/**
* Add tables for backup creation.
*
* @param array $tables Tables without the prefix
*/
public function create(array $tables, $hex = false)
{
$this->hex = $hex;
$this->tables = $tables;
$tables_header = [];
foreach ($this->tables as $table_name) {
$tables_header[] = _DB_PREFIX_.$table_name;
}
$this->addHeader('tables', implode(',', $tables_header));
}
public static function formatMD5($path_name)
{
$info_name = pathinfo($path_name, PATHINFO_FILENAME);
$info_extension = pathinfo($path_name, PATHINFO_EXTENSION);
$info_dirname = pathinfo($path_name, PATHINFO_DIRNAME);
$name = md5($info_name).($info_extension ? '.'.$info_extension : '');
$path_name = $info_dirname.'/'.$name;
return $path_name;
}
/**
* Save the backup xml.
*
* @param string $path_name Pathname
* @param bool $format Format the name
* @param bool $md5 Md5 format
*
* @return bool Success
*/
public function save($path_name, $format = true, $md5 = true)
{
$name = basename($path_name);
$name_display = $name;
if ($md5) {
$path_name = self::formatMD5($path_name);
}
if ($format) {
$path_filename = self::formatName($path_name);
} else {
$path_filename = $path_name;
}
$filename = basename($path_filename);
$this->addHeader('filename', $filename);
$this->addHeader('date', date('Y-m-d H:i:s', time()));
$this->addHeader('module_version', $this->module->version);
$this->addHeader('name', $name_display);
if (!isset($this->headers['configuration_shop'])) {
$this->addHeader('configuration_shop', serialize([]));
}
if (!isset($this->headers['configuration'])) {
$this->addHeader('configuration', serialize([]));
}
if (!isset($this->headers['configuration_campaign'])) {
$this->addHeader('configuration_campaign', null);
}
if (!isset($this->headers['hooks'])) {
$this->addHeader('hooks', serialize([]));
}
$mysql = new NewsletterProMySQLDumpXml($this->hex);
$mysql->prependString(self::PHP_HEADER."\n");
$mysql->addTables($this->tables);
$mysql->setHeader($this->headers);
return $mysql->save($this->default_path.'/'.$path_filename);
}
/**
* Det the backup files list.
*
* @param string $path Backup path
*
* @return array
*/
public static function getList($path = '')
{
$dirs = new DirectoryIterator(self::path().'/'.$path);
$files = new RegexIterator($dirs, '/.php$/', RecursiveRegexIterator::MATCH);
$results = [];
foreach ($files as $file) {
$file_basename = '';
if (method_exists($file, 'getBasename')) {
$file_basename = $file->getBasename();
} else {
$file_basename = basename($file->getFilename());
}
if ('index.php' !== $file_basename) {
$header = self::getHeaderFromFilename($file->getPathname());
$header_name = 'Undefined';
if (isset($header['name'])) {
$header_name = $header['name'];
}
$item = [];
$item['m_date'] = date('Y-m-d H:i:s', $file->getMTime());
$item['name'] = $file_basename;
$item['name_display'] = Tools::ucfirst(str_replace('_', ' ', preg_replace('/\.php$/', '', $header_name)));
$item['filename'] = $file->getPathname();
$item['module_version'] = (isset($header['module_version']) ? $header['module_version'] : '0.00');
$results[] = $item;
}
}
return $results;
}
/**
* Cet the header as array from a file.
*
* @param string $filename Filename path
*
* @return array
*/
public static function getHeaderFromFilename($filename)
{
$header = [];
if (file_exists($filename)) {
if ($file = fopen($filename, 'r')) {
$working_data = '';
while (!feof($file) && (0 == connection_status())) {
$working_data_temp = fread($file, 1024);
$working_data .= $working_data_temp;
$end_string = '</header>';
$end = strpos($working_data, $end_string);
if (false !== $end) {
break;
}
flush();
}
fclose($file);
$start_string = '<header>';
$start = strpos($working_data, $start_string);
if (false !== $start) {
$working_data = Tools::substr($working_data, $start);
$end_string = '</header>';
$end = strpos($working_data, $end_string);
if (false !== $end) {
$header_xml = Tools::substr($working_data, 0, $end + Tools::strlen($end_string));
libxml_use_internal_errors(true);
$xml_obj = simplexml_load_string($header_xml);
if (false === $xml_obj) {
$xml_errors = '';
foreach (libxml_get_errors() as $error) {
$xml_errors .= NewsletterProTools::displayXMLError($error, $xml_obj)."\n";
}
libxml_clear_errors();
// skip error if exits
} else {
foreach ($xml_obj as $header_name => $value) {
$header[$header_name] = trim((string) $value);
}
}
}
}
}
}
return $header;
}
/**
* Load the backup from a file.
*
* @param string $path_name Pathname
*/
public function load($path_name, $is_file = true)
{
if ($is_file) {
$full_path = isset($this->default_path) ? $this->default_path.'/'.$path_name : self::pathName($path_name);
if (!file_exists($full_path) || !is_file($full_path)) {
throw new Exception(sprintf($this->module->l('The filename "%s" does not exists anymore.'), basename($path_name)));
}
$this->load_data = @Tools::file_get_contents($full_path);
if (false === $this->load_data) {
throw new Exception(sprintf($this->module->l('The filename "%s" is not readable. Please check the CHMOD permissions.'), basename($path_name)));
}
libxml_use_internal_errors(true);
$this->load_xml = simplexml_load_file($full_path);
} else {
$this->load_data = $path_name; // is this case the $path_name is a string content
// remove the php exit
$this->removePHPHeader();
libxml_use_internal_errors(true);
$this->load_xml = simplexml_load_string($this->load_data);
}
if (false === $this->load_xml) {
$xml_errors = '';
foreach (libxml_get_errors() as $error) {
$xml_errors .= NewsletterProTools::displayXMLError($error, $this->load_xml)."\n";
}
libxml_clear_errors();
throw new Exception($xml_errors);
}
$header_xml = $this->load_xml->header;
$this->load_tables = [];
if (isset($header_xml->tables)) {
$this->load_tables = explode(',', (string) $header_xml->tables);
}
$this->load_configuration = [];
if (isset($header_xml->configuration)) {
$this->load_configuration = NewsletterProTools::unSerialize(trim((string) $header_xml->configuration));
}
$this->load_configuration_campaign = null;
if (isset($header_xml->configuration_campaign)) {
$this->load_configuration_campaign = $header_xml->configuration_campaign;
}
$this->load_configuration_shop = [];
if (isset($header_xml->configuration_shop)) {
$this->load_configuration_shop = NewsletterProTools::unSerialize(trim((string) $header_xml->configuration_shop));
}
$this->load_hooks = [];
if (isset($header_xml->hooks)) {
$this->load_hooks = NewsletterProTools::unSerialize(trim((string) $header_xml->hooks));
}
}
/**
* Remove the <?php exit; ?> from the begining of the line from the load_data.
*/
private function removePHPHeader()
{
$start = strpos($this->load_data, self::PHP_HEADER);
if (false !== $start) {
$this->load_data = trim(Tools::substr($this->load_data, Tools::strlen(self::PHP_HEADER)));
}
}
/**
* Execute a backup after is loaded.
*
* @return bool Reutrn true if success
*/
public function execute()
{
$success = [];
$success[] = NewsletterPro::executeHooksByInfo($this->load_hooks);
$configuration = array_merge(Config::get(), $this->load_configuration);
$success[] = Configuration::updateValue(Config::NAME, json_encode($configuration), false, 0, 0);
$success[] = Configuration::updateValue('NEWSLETTER_PRO_CAMPAIGN', $this->load_configuration_campaign, false, 0, 0);
$success[] = NewsletterProConfigurationShop::replaceShopsCondiguration($this->load_configuration_shop);
$xml_to_sql = new NewsletterProXMLToSQL($this->load_xml);
foreach ($xml_to_sql->getSQL() as $table_name => $sql_array) {
$success[] = $this->emptyTable($table_name);
foreach ($sql_array as $sql) {
$success[] = @Db::getInstance()->execute($sql);
}
}
return !in_array(false, $success);
}
/**
* Get the loaded xml.
*
* @return object
*/
public function getXML()
{
return $this->load_xml;
}
/**
* Set the load xml object.
*
* @param object $xml
*/
public function setXML($xml)
{
$this->load_xml = $xml;
}
public function emptyTable($table_name)
{
return Db::getInstance()->execute('DELETE FROM `'.pSQL($table_name).'` WHERE 1');
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProBlockNewsletter extends ObjectModel
{
public $id_shop;
public $id_shop_group;
public $email;
public $ip_registration_newsletter;
public $http_referer;
public $active;
public static $definition = [
'table' => 'newsletter',
'primary' => 'id',
'fields' => [
'id_shop' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'id_shop_group' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'email' => ['type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true],
'ip_registration_newsletter' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'http_referer' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
],
];
public function __construct($id = null)
{
self::$definition['table'] = NewsletterProDefaultNewsletterTable::getTableName();
parent::__construct($id);
}
public function newInstance($id = null)
{
return new self($id);
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProBounce
{
/**
* Bounce email from the four list.
*
* @param string $email
* @param array $lists [customers, visitors, visitors_np, added]
* @param int $method
*
* @return bool
*/
public static function execute($email, $lists = [], $method = -1)
{
$module = NewsletterProTools::module();
$intersect = array_intersect($lists, ['customers', 'visitors', 'visitors_np', 'added']);
if (!empty($lists) && empty($intersect)) {
throw new InvalidArgumentException(sprintf('Invalid parameter %s values (%s).', '$lists', implode(', ', $lists)));
}
$success = [];
if (empty($lists) || in_array('visitors', $lists)) {
$tableName = NewsletterProDefaultNewsletterTable::getTableName();
if (NewsletterProTools::tableExists($tableName)) {
$id_visitor = (int) Db::getInstance()->getValue('
SELECT `id` FROM `'._DB_PREFIX_.$tableName.'` WHERE `email` = "'.pSQL($email).'"
');
if ($id_visitor) {
if (-1 == $method) {
$success[] = $module->deleteVisitor($id_visitor);
} else {
$success[] = Db::getInstance()->update('newsletter', [
'active' => 0,
], '`id` = '.(int) $id_visitor);
}
}
}
}
if (empty($lists) || in_array('customers', $lists)) {
$id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `'._DB_PREFIX_.'customer` WHERE `email` = "'.pSQL($email).'"');
if ($id_customer) {
if (-1 == $method) {
$success[] = $module->deleteCustomer($id_customer);
} else {
$success[] = Db::getInstance()->update('customer', [
'newsletter' => 0,
], '`id_customer` = '.(int) $id_customer);
}
}
}
if (empty($lists) || in_array('added', $lists)) {
$id_added = (int) Db::getInstance()->getValue('SELECT `id_newsletter_pro_email` FROM `'._DB_PREFIX_.'newsletter_pro_email` WHERE `email` = "'.pSQL($email).'"');
if ($id_added) {
if (-1 == $method) {
$success[] = $module->deleteAdded($id_added);
} else {
$success[] = Db::getInstance()->update('newsletter_pro_email', [
'active' => 0,
], '`id_newsletter_pro_email` = '.(int) $id_added);
}
}
}
if (empty($lists) || in_array('visitors_np', $lists)) {
$id_visitor_np = (int) Db::getInstance()->getValue('SELECT `id_newsletter_pro_subscribers` FROM `'._DB_PREFIX_.'newsletter_pro_subscribers` WHERE `email` = "'.pSQL($email).'"');
if ($id_visitor_np) {
if (-1 == $method) {
$success[] = $module->deleteVisitorNP($id_visitor_np);
} else {
$success[] = Db::getInstance()->update('newsletter_pro_subscribers', [
'active' => 0,
], '`id_newsletter_pro_subscribers` = '.(int) $id_visitor_np);
}
}
}
return !empty($success) ? !in_array(false, $success) : false;
}
}

View File

@@ -0,0 +1,73 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCSStoInlineStyle extends NewsletterProEmogrifier
{
private $np_head_style;
public function __construct($html = '', $css = '')
{
$current_encode = mb_detect_encoding($html, 'UTF-8, ISO-8859-1, ISO-8859-15, HTML-ENTITIES', true);
// this will solve the trim last row bug in phpQuery plugin
$html = html_entity_decode($html, ENT_COMPAT | ENT_HTML401 | ENT_HTML5, $current_encode);
$html = mb_convert_encoding($html, 'UTF-8', $current_encode);
if ((bool) pqnp_ini_config('add_style_to_header')) {
// grep the heaser style
if (preg_match_all('/(?P<style><(style).*>?[\s\S]*?<\/\2>)/', $html, $match)) {
if (!empty($match['style'])) {
$this->np_head_style = implode("\n", $match['style']);
}
}
}
parent::__construct($html, $css);
}
public function output()
{
$html = $this->emogrify();
$html_return = html_entity_decode(str_replace(['%7B', '%7D'], ['{', '}'], $html));
if (isset($this->np_head_style)) {
if (preg_match('/<head.*?>/', $html_return, $match)) {
$head_text = $match[0];
$head_start = strpos($html_return, $head_text);
if (false !== $head_start) {
$head_end = $head_start + Tools::strlen($head_text);
$html_return = substr_replace($html_return, "\n\n".$this->np_head_style, $head_end, 0);
}
}
}
return $html_return;
}
public static function convert($html = '', $css = '')
{
try {
$obj = new NewsletterProCSStoInlineStyle($html, $css);
return $obj->output();
} catch (Exception $e) {
NewsletterProLog::writeStrip($e->getMessage(), NewsletterProLog::ERROR_FILE);
}
return $html;
}
}

View File

@@ -0,0 +1,126 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
use PQNP\Version;
class NewsletterProCategoryTree
{
private $home_id;
private $customer_id;
public function __construct($customer_id = 0)
{
$this->home_id = (Version::isLower('1.5.0.5') ? 1 : 2);
$this->customer_id = $customer_id;
}
public static function newInstance($customer_id = 0)
{
return new self($customer_id);
}
public function home($id_lang = null, $id_shop = null)
{
return $this->getCategoryById($this->home_id, $id_lang, $id_shop);
}
public function category($id_category, $id_lang = null, $id_shop = null)
{
if (is_array($id_category) && !empty($id_category)) {
$id_category = $id_category['id_category'];
}
return $this->getCategoryById($id_category, $id_lang, $id_shop);
}
public function childrens($id_category, $id_lang = null, $id_shop = null)
{
if (is_array($id_category) && !empty($id_category)) {
$id_category = $id_category['id_category'];
}
$categores = $this->getCategoryChildrensById($id_category, $id_lang, $id_shop);
return array_values(array_filter($categores, function ($category) {
$id = $category['id_category'];
$name = $category['name'];
return true;
}));
}
private function getQuery($id_category, $id_lang, $id_shop, $where)
{
return '
SELECT
c.`id_category`, c.`id_parent`, c.`active`, c.`level_depth`, cl.`id_lang`, cl.`name`,
(SELECT COUNT(*) FROM `'._DB_PREFIX_.'category`
WHERE `id_parent` = c.`id_category`
) AS `childrens_count`,
(SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_customer_category`
WHERE `id_customer` = '.(int) $this->customer_id.'
AND FIND_IN_SET(c.`id_category`, `categories`)
) AS `checked`
FROM `'._DB_PREFIX_.'category` c
INNER JOIN `'._DB_PREFIX_.'category_lang` cl ON (
c.`id_category` = cl.`id_category` AND
cl.`id_lang` = '.(int) $id_lang.'
)
INNER JOIN `'._DB_PREFIX_.'category_shop` cs ON (
c.`id_category` = cs.`id_category` AND
cs.`id_shop` = '.(int) $id_shop.'
)
WHERE '.pSQL($where).'
AND c.`active` = 1
'
;
}
private function getCategoryById($id_category, $id_lang = null, $id_shop = null)
{
$context = Context::getContext();
if (!isset($id_lang)) {
$id_lang = (int) $context->language->id;
}
if (!isset($id_shop)) {
$id_shop = (int) $context->shop->id;
}
$category = Db::getInstance()->getRow($this->getQuery($id_category, $id_lang, $id_shop, 'c.`id_category` = '.(int) $id_category));
return $category;
}
private function getCategoryChildrensById($id_category, $id_lang = null, $id_shop = null)
{
$context = Context::getContext();
if (!isset($id_lang)) {
$id_lang = (int) $context->language->id;
}
if (!isset($id_shop)) {
$id_shop = (int) $context->shop->id;
}
$childrens = Db::getInstance()->executeS($this->getQuery($id_category, $id_lang, $id_shop, 'c.`id_parent` = '.(int) $id_category));
return $childrens;
}
}

View File

@@ -0,0 +1,142 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProConfig
{
public static $table_name = 'newsletter_pro_config';
public static $errors = [];
public static $module;
public static function get($name)
{
$sql = 'SELECT `value` FROM `'._DB_PREFIX_.'newsletter_pro_config` WHERE `name` = "'.pSQL($name).'"';
return Db::getInstance()->getValue($sql);
}
public static function save($name, $value)
{
$sql = 'SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_config` WHERE `name` = "'.pSQL($name).'"';
if (Db::getInstance()->getValue($sql)) {
return Db::getInstance()->update('newsletter_pro_config', [
'value' => pSQL($value),
], '`name` = "'.pSQL($name).'"');
} else {
return Db::getInstance()->insert('newsletter_pro_config', [
'name' => pSQL($name),
'value' => pSQL($value),
]);
}
}
public static function test($name)
{
$sql = 'SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_config` WHERE `name` = "'.$name.'"';
return Db::getInstance()->getValue($sql);
}
public static function saveArray($name, $array)
{
$value = serialize($array);
return self::save($name, $value);
}
public static function getArray($name)
{
$get = self::get($name);
if ($get) {
return NewsletterProTools::unSerialize($get);
}
return false;
}
public static function delete($name)
{
return Db::getInstance()->delete('newsletter_pro_config', '`name` = "'.pSQL($name).'"');
}
public static function install()
{
$sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.self::$table_name.'` (
`id_newsletter_pro_config` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`value` TEXT NULL,
PRIMARY KEY (`id_newsletter_pro_config`),
UNIQUE INDEX `name` (`name`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET='._PQNP_MYSQL_CHARSET_.';';
if (!Db::getInstance()->execute($sql)) {
self::addError(sprintf(NewsletterPro::getInstance()->l('Cannot create the table "%s".'), _DB_PREFIX_.'newsletter_pro_config'));
return false;
} else {
if (!self::test('CHIMP_SYNC')) {
self::saveArray('CHIMP_SYNC', []);
}
if (!self::test('LAST_DATE_CHIMP_SYNC')) {
self::save('LAST_DATE_CHIMP_SYNC', '0000-00-00 00:00:00');
}
if (!self::test('CHIMP_LAST_DATE_SYNC_ORDERS')) {
self::save('CHIMP_LAST_DATE_SYNC_ORDERS', '0000-00-00 00:00:00');
}
}
return true;
}
public static function uninstall()
{
$sql = 'DROP TABLE IF EXISTS `'._DB_PREFIX_.self::$table_name.'`;';
if (!Db::getInstance()->execute($sql)) {
return false;
}
return true;
}
public static function addError($error)
{
self::$errors[] = $error;
}
public static function getErrors()
{
return self::$errors;
}
public static function dbSerialize($value)
{
return serialize($value);
}
public static function unSerialize($serialized)
{
if (is_string($serialized) && preg_match('/a:[0-9]+:\{.*\}/', $serialized)) {
return @unserialize($serialized);
}
return [];
}
}

View File

@@ -0,0 +1,228 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProConfigurationShop
{
public static $name = 'NEWSLETTER_PRO_SHOP';
public static $configuration = [];
public static $errors = [];
public static $init_id_shop;
public static $init_id_shop_group;
public static function install($all_shops = true)
{
$module = NewsletterPro::getInstance();
// at least one value should be available
self::$configuration = self::getDefaultConfiguration();
if ($all_shops) {
foreach (NewsletterProTools::getActiveShops() as $shop) {
if (!self::updateDb((int) $shop['id_shop'], (int) $shop['id_shop_group'])) {
self::$errors[] = sprintf($module->l('The configuration "%s" cannot be installed into "%s" table.'), self::$name, _DB_PREFIX_.'configuration');
return false;
}
}
foreach (NewsletterPro::getShopGroups() as $shop_group) {
if (!self::updateDb(null, (int) $shop_group->id)) {
self::$errors[] = sprintf($module->l('The configuration "%s" cannot be installed into "%s" table.'), self::$name, _DB_PREFIX_.'configuration');
return false;
}
}
} else {
if (!self::updateDb()) {
self::$errors[] = sprintf($module->l('The configuration "%s" cannot be installed into "%s" table.'), self::$name, _DB_PREFIX_.'configuration');
return false;
}
}
return true;
}
public static function getDefaultConfiguration()
{
return [
'SUBSCRIPTION_TEMPLATE' => 'default',
];
}
public static function uninstall()
{
return Configuration::deleteByName(self::$name);
}
public static function getErrors()
{
return self::$errors;
}
public static function init($id_shop = null, $id_shop_group = null)
{
if (!isset($id_shop)) {
$id_shop = NewsletterPro::getContextShopID(true);
}
self::$init_id_shop = $id_shop;
if (!isset($id_shop_group)) {
$id_shop_group = NewsletterPro::getContextShopGroupID(true);
}
self::$init_id_shop_group = $id_shop_group;
$cfg = json_decode(Configuration::get(self::$name, null, self::$init_id_shop_group, self::$init_id_shop), true);
if (!empty($cfg)) {
self::$configuration = $cfg;
} else {
self::$configuration = self::getDefaultConfiguration();
}
}
public static function get($name = null)
{
if (isset($name)) {
if (isset(self::$configuration[$name])) {
return self::$configuration[$name];
}
return false;
}
return self::$configuration;
}
public static function getAll()
{
return self::get();
}
public static function updateValue($name, $value)
{
if (isset(self::$configuration[$name])) {
return self::set($name, $value);
} else {
return false;
}
}
public static function set($name, $value)
{
self::$configuration[$name] = $value;
return self::updateDb();
}
public static function deleteByName($name)
{
if (isset(self::$configuration[$name])) {
unset(self::$configuration[$name]);
}
return self::updateDb();
}
public static function updateDb($id_shop = null, $id_shop_group = null)
{
if (!isset($id_shop)) {
$id_shop = NewsletterPro::getContextShopID(true);
}
self::$init_id_shop = $id_shop;
if (!isset($id_shop_group)) {
$id_shop_group = NewsletterPro::getContextShopGroupID(true);
}
self::$init_id_shop_group = $id_shop_group;
return Configuration::updateValue(self::$name, json_encode(self::$configuration), false, (int) $id_shop_group, (int) $id_shop);
}
public static function getDbConfigurations()
{
$recoreds = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'configuration`
WHERE `name` = "'.pSQL(self::$name).'"
');
foreach ($recoreds as &$recored) {
if (!array_key_exists('id_shop_group', $recored) && array_key_exists('id_group_shop', $recored)) {
$recored['id_shop_group'] = $recored['id_group_shop'];
}
}
return $recoreds;
}
public static function replaceShopsCondiguration($to_replace = [])
{
$configs = self::getDbConfigurations();
$success = [];
$column_name = NewsletterProTools::getInShopGroupColumnName();
foreach ($configs as &$config) {
foreach ($to_replace as &$to_confg) {
if ($config['id_shop'] == $to_confg['id_shop'] && $config['id_shop_group'] == $to_confg['id_shop_group']) {
$current_config = json_decode($config['value'], true);
$current_config = array_merge($current_config, $to_confg['value']);
$config['value'] = json_encode($current_config);
$success[] = Db::getInstance()->update('configuration', [
'value' => $config['value'],
], '`name` = "'.pSQL(self::$name).'" AND `id_shop` '.(is_null($config['id_shop']) ? 'IS NULL' : '='.(int) $config['id_shop']).' AND `'.$column_name.'` '.(is_null($config['id_shop_group']) ? 'IS NULL' : '='.$config['id_shop_group']).' ', 0, true);
}
}
}
return !in_array(false, $success);
}
public static function getAllShopsConfiguration($filter = [])
{
$result = [];
foreach (self::getDbConfigurations() as $config) {
$value = json_decode($config['value'], true);
$config_keys = array_keys($value);
$intersection = array_intersect($filter, $config_keys);
$value_filter = [];
foreach ($intersection as $cfg_name) {
if (isset($value[$cfg_name])) {
$value_filter[$cfg_name] = $value[$cfg_name];
}
}
$result[] = [
'id_shop' => $config['id_shop'],
'id_shop_group' => $config['id_shop_group'],
'value' => empty($filter) ? $value : $value_filter,
];
}
return $result;
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCookie
{
public $name;
public $parent_cookie;
public $cookie;
public function __construct($name, $expire = null)
{
$this->name = $name;
$this->parent_cookie = new Cookie($this->name, '', $expire);
if (!isset($this->parent_cookie->{$this->name})) {
$this->parent_cookie->{$this->name} = serialize([]);
}
$this->cookie = unserialize($this->parent_cookie->{$this->name});
}
public function set($key, $value)
{
$this->cookie[$key] = $value;
return $this->write();
}
/**
* this is used only if the target is array.
*/
public function append($key, $value)
{
$get = $this->get($key);
if (is_array($get)) {
$this->cookie[$key][] = $value;
} else {
$this->cookie[$key] = [];
$this->cookie[$key][] = $value;
}
return $this->write();
}
public function get($key)
{
if (isset($this->cookie[$key])) {
return $this->cookie[$key];
}
return false;
}
public function exists($key)
{
return isset($this->cookie[$key]);
}
public function destroy()
{
if (isset($this->parent_cookie->{$this->name})) {
$this->parent_cookie->{$this->name} = null;
}
}
public function getCookies()
{
return $this->cookie;
}
public function write()
{
$this->parent_cookie->{$this->name} = serialize($this->cookie);
}
}

View File

@@ -0,0 +1,92 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCreateXML extends DOMDocument
{
public $root_name;
public $root;
const USE_CDATA = false;
public function __construct($root_name)
{
parent::__construct('1.0', 'UTF-8');
$this->root_name = $root_name;
$this->root = $this->createElement($this->root_name);
$this->root = $this->appendChild($this->root);
}
public function getContent($node = null)
{
$this->preserveWhiteSpace = false;
$this->formatOutput = true;
$xml = $this->saveXML($node);
return $xml;
}
public function getRoot()
{
return $this->root;
}
public function display($node = null)
{
$this->preserveWhiteSpace = false;
$this->formatOutput = true;
echo '<pre>';
echo htmlentities($this->saveXML($node));
echo '</pre>';
}
public function append($to, $name, $value = '')
{
$value_format = htmlspecialchars($value);
// $value_format = pSQL($value, true);
// $value_format = htmlentities($value, ENT_COMPAT | ENT_XML1, 'UTF-8');
// $value_format = htmlspecialchars(stripslashes(trim($value)));
if (self::USE_CDATA) {
$element = $this->createElement($name);
$element->appendChild($this->createCDATASection($value_format));
} else {
$element = $this->createElement($name, $value_format);
}
return $to->appendChild($element);
}
public function attribute($to, $name, $value = '')
{
$attribute = $this->createAttribute($name);
$attribute->value = $value;
return $to->appendChild($attribute);
}
public function create($to, $name, $a_name = '', $a_value = '', $value = '')
{
$child = $this->append($to, $name, $value);
if ('' != $a_name) {
$this->attribute($child, $a_name, $a_value);
}
return $child;
}
}

View File

@@ -0,0 +1,269 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCurl
{
public $url;
public $response;
public $headers;
public $config;
public $request_params;
public $format;
public $errors;
public $module;
public function __construct($config = [])
{
$this->module = NewsletterPro::getInstance();
$this->errors = [];
if (!extension_loaded('curl')) {
throw new Exception(sprintf($this->module->l('The availability of php %s library is not available on your server. You can talk with the hosting provider to enable it.'), 'curl'));
}
if (!isset($config['url'])) {
$config['url'] = '';
}
$this->config = $config;
}
public function curlit()
{
if (!function_exists('curl_init')) {
throw new Exception(sprintf($this->module->l('The availability of php %s library is not available on your server. You can talk with the hosting provider to enable it.'), 'curl'));
} else {
$c = curl_init();
curl_setopt_array($c, [
CURLOPT_USERAGENT => 'spider',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_HEADERFUNCTION => [$this, 'curlHeader'],
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_ENCODING => '',
CURLOPT_URL => $this->url,
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 60,
CURLOPT_TIMEOUT => 45,
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
]);
switch ($this->method) {
case 'GET':
$content_length = 0;
break;
case 'POST':
curl_setopt($c, CURLOPT_POST, true);
$post_body = $this->safeEncode($this->xml);
curl_setopt($c, CURLOPT_POSTFIELDS, $post_body);
$this->request_params['xml'] = $post_body;
$content_length = Tools::strlen($post_body);
break;
case 'PUT':
$fh = tmpfile();
if ('file' == $this->format) {
$put_body = $this->xml;
} else {
$put_body = $this->safeEncode($this->xml);
}
fwrite($fh, $put_body);
rewind($fh);
curl_setopt($c, CURLOPT_PUT, true);
curl_setopt($c, CURLOPT_INFILE, $fh);
curl_setopt($c, CURLOPT_INFILESIZE, Tools::strlen($put_body));
$content_length = Tools::strlen($put_body);
break;
default:
$content_length = 0;
curl_setopt($c, CURLOPT_CUSTOMREQUEST, $this->method);
break;
}
if (!empty($this->request_params)) {
if (!$this->config['multipart']) {
$ps = [];
foreach ($this->request_params as $k => $v) {
$ps[] = "{$k}={$v}";
}
$this->request_params = implode('&', $ps);
}
curl_setopt($c, CURLOPT_POSTFIELDS, $this->request_params);
} else {
$this->headers['Content-Type'] = '';
$this->headers['Content-Length'] = $content_length;
}
$this->headers['Expect'] = '';
if (!empty($this->headers)) {
$headers = [];
foreach ($this->headers as $k => $v) {
$headers[] = trim($k.': '.$v);
}
curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
}
if (isset($this->config['prevent_request']) && false == $this->config['prevent_request']) {
return;
}
$response = curl_exec($c);
if (false === $response) {
$response = 'Curl error: '.curl_error($c);
$code = 1;
} else {
$code = curl_getinfo($c, CURLINFO_HTTP_CODE);
}
$info = curl_getinfo($c);
curl_close($c);
if (isset($fh)) {
fclose($fh);
}
$this->response['code'] = $code;
$this->response['response'] = $response;
$this->response['info'] = $info;
$this->response['format'] = $this->format;
return $code;
}
}
public function url($request = '', $format = 'json')
{
if (isset($format)) {
switch ($format) {
case 'html':
$this->headers['Accept'] = 'text/plain';
break;
case 'pdf':
$this->headers['Accept'] = 'application/pdf';
break;
case 'json':
$this->headers['Accept'] = 'application/json';
break;
case 'xml':
default:
$this->headers['Accept'] = 'application/xml';
break;
}
}
$this->format = $format;
return implode([
$this->config['url'],
$request,
]);
}
public function request($method, $url, $params = [], $xml = '')
{
$multipart = false;
if ('' !== $xml) {
$this->xml = $xml;
}
if ('xml' == $method) {
$params['xml'] = $xml;
}
$this->prepareMethod($method);
$this->config['multipart'] = $multipart;
$this->url = $url.(false !== strpos($url, '?') ? '&' : '?').$this->buildQuery($params);
$this->curlit();
return $this->response;
}
public function curlHeader($ch, $header)
{
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_', Tools::strtolower(Tools::substr($header, 0, $i)));
$value = trim(Tools::substr($header, $i + 2));
$this->response['headers'][$key] = $value;
}
return Tools::strlen($header);
}
private function prepareMethod($method)
{
$this->method = Tools::strtoupper($method);
}
public function buildQuery($params)
{
return '' != http_build_query($params) ? http_build_query($params) : '';
}
public function parseResponse($response, $format)
{
if (isset($format)) {
switch ($format) {
case 'html':
$the_response = $response;
break;
case 'pdf':
$the_response = $response;
break;
case 'json':
$the_response = Tools::jsonDecode($response);
break;
default:
$the_response = simplexml_load_string($response);
break;
}
}
return $the_response;
}
public function success()
{
return empty($this->errors);
}
public function getErrors()
{
return $this->errors;
}
}

View File

@@ -0,0 +1,160 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCustomerCategory extends ObjectModel
{
public $id_customer;
public $categories;
public $date_add;
public $date_upd;
public static $definition = [
'table' => 'newsletter_pro_customer_category',
'primary' => 'id_newsletter_pro_customer_category',
'fields' => [
'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true],
'categories' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
],
];
public function __construct($id = null)
{
parent::__construct($id);
}
public static function getInstanceByCustomerId($id_customer)
{
$id = (int) Db::getInstance()->getValue('
SELECT `id_newsletter_pro_customer_category`
FROM `'._DB_PREFIX_.'newsletter_pro_customer_category`
WHERE `id_customer` = '.(int) $id_customer.'
');
return new NewsletterProCustomerCategory($id);
}
public function getCategories()
{
return explode(',', trim($this->categories, ','));
}
public function setCategories(array $categories)
{
$this->categories = trim(implode(',', $categories), ',');
}
public static function getCategoriesByIdCustomer($id_customer)
{
return Db::getInstance()->getValue('
SELECT `categories` FROM `'._DB_PREFIX_.'newsletter_pro_customer_category`
WHERE `id_customer` = '.(int) $id_customer.'
');
}
public static function exportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter_pro_customer_category', $email);
try {
$results = Db::getInstance()->executeS('
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
');
if (count($results) > 0) {
$count = 0;
foreach ($results as $row) {
$id_customer = (int) $row['id_customer'];
$res = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'newsletter_pro_customer_category`
WHERE `id_customer` = '.(int) $id_customer.'
');
foreach ($res as $valu) {
$count += count(explode(',', $valu['categories']));
}
}
$response->addToExport([
NewsletterPro::getInstance()->l('Category subscription') => '',
NewsletterPro::getInstance()->l('Total') => $count,
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function privacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter_pro_customer_category', $email);
try {
$results = Db::getInstance()->executeS('
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
');
foreach ($results as $row) {
$id_customer = (int) $row['id_customer'];
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_customer_category`
WHERE `id_customer` = '.(int) $id_customer.'
');
$response->addToCount($count);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function clearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter_pro_customer_category', $email);
try {
$results = Db::getInstance()->executeS('
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
');
foreach ($results as $row) {
$id_customer = (int) $row['id_customer'];
if (Db::getInstance()->delete('newsletter_pro_customer_category', '`id_customer` = '.(int) $id_customer)) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCustomerContext
{
public static $currencies;
public static function getContext($id_customer = null)
{
$context = Context::getContext();
$context->customer = new Customer((int) $id_customer);
if (Validate::isLoadedObject($context->customer)) {
if (isset($context->customer->id_shop)) {
$context->shop = new Shop((int) $context->customer->id_shop);
}
if (isset($context->customer->id_lang)) {
$context->language = new Language((int) $context->customer->id_lang);
}
$currency = Currency::getDefaultCurrency();
if (Validate::isLoadedObject($currency)) {
$context->currency = $currency;
}
if (!isset($context->cart)) {
$context->cart = new Cart();
}
$id_country = (int) Customer::getCurrentCountry((int) $context->customer->id);
if ($id_country) {
$context->country = new Country($id_country);
}
}
return $context;
}
public static function getCurrenciesByIdShop($id_shop = 0)
{
if (!isset(self::$currencies)) {
self::$currencies = NewsletterPro::getCurrenciesByIdShop($id_shop);
}
return self::$currencies;
}
}

View File

@@ -0,0 +1,182 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProCustomerListOfInterests extends ObjectModel
{
public $id_customer;
public $categories;
public $date_add;
public $date_upd;
public static $definition = [
'table' => 'newsletter_pro_customer_list_of_interests',
'primary' => 'id_newsletter_pro_customer_list_of_interests',
'fields' => [
'id_customer' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true],
'categories' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
],
];
public function __construct($id = null)
{
parent::__construct($id);
}
public static function getInstanceByCustomerId($id_customer)
{
$id = (int) Db::getInstance()->getValue('
SELECT `id_newsletter_pro_customer_list_of_interests`
FROM `'._DB_PREFIX_.'newsletter_pro_customer_list_of_interests`
WHERE `id_customer` = '.(int) $id_customer.'
');
$instance = new NewsletterProCustomerListOfInterests($id);
$instance->id_customer = (int) $id_customer;
return $instance;
}
public static function getInstanceByCustomerEmail($email, $id_shop = null)
{
if (!isset($id_shop)) {
$id_shop = (int) Context::getContext()->shop->id;
}
$row = Db::getInstance()->getRow('
SELECT loi.`id_newsletter_pro_customer_list_of_interests`, loi.`id_customer`
FROM `'._DB_PREFIX_.'newsletter_pro_customer_list_of_interests` loi
WHERE loi.`id_customer` = (
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
AND `id_shop` = '.(int) $id_shop.'
LIMIT 1
)
');
if (empty($row)) {
return new NewsletterProCustomerListOfInterests();
}
$instance = new NewsletterProCustomerListOfInterests((int) $row['id_newsletter_pro_customer_list_of_interests']);
$instance->id_customer = (int) $row['id_customer'];
return $instance;
}
public function getCategories()
{
return explode(',', trim($this->categories, ','));
}
public function setCategories(array $categories)
{
$this->categories = trim(implode(',', $categories), ',');
}
public static function exportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter_pro_customer_list_of_interests', $email);
try {
$results = Db::getInstance()->executeS('
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
');
if (count($results) > 0) {
$count = 0;
foreach ($results as $row) {
$id_customer = (int) $row['id_customer'];
$res = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'newsletter_pro_customer_list_of_interests`
WHERE `id_customer` = '.(int) $id_customer.'
');
foreach ($res as $valu) {
$count += count(explode(',', $valu['categories']));
}
}
$response->addToExport([
NewsletterPro::getInstance()->l('List of interests') => '',
NewsletterPro::getInstance()->l('Total') => $count,
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function privacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter_pro_customer_list_of_interests', $email);
try {
$results = Db::getInstance()->executeS('
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
');
foreach ($results as $row) {
$id_customer = (int) $row['id_customer'];
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_customer_list_of_interests`
WHERE `id_customer` = '.(int) $id_customer.'
');
$response->addToCount($count);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function clearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter_pro_customer_list_of_interests', $email);
try {
$results = Db::getInstance()->executeS('
SELECT `id_customer` FROM `'._DB_PREFIX_.'customer`
WHERE `email` = "'.pSQL($email).'"
');
foreach ($results as $row) {
$id_customer = (int) $row['id_customer'];
if (Db::getInstance()->delete('newsletter_pro_customer_list_of_interests', '`id_customer` = '.(int) $id_customer)) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,41 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProDb
{
public static function getInstance($master = true)
{
$db = Db::getInstance($master);
$db->disconnect();
$db->connect();
return $db;
}
public static function refresh()
{
$db = Db::getInstance();
$db->disconnect();
$db->connect();
}
public static function clear()
{
return Db::getInstance()->execute('RESET QUERY CACHE');
}
}

View File

@@ -0,0 +1,147 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProDbTransaction
{
const DB_TYPE_MYSQL = 'MySQL';
const DB_TYPE_PDO = 'DbPDO';
const DB_TYPE_MYSQLI = 'DbMySQLi';
const FETCH_ASSOC = 1;
private $type;
public $db;
public $conn;
/**
* The transaction will fetch only one record.
*/
public function __construct()
{
$this->type = Db::getClass();
$this->db = Db::getInstance();
$this->conn = $this->db->connect();
}
public static function newInstance()
{
return new self();
}
public function begin()
{
if (self::DB_TYPE_PDO == $this->type) {
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->beginTransaction();
} elseif (self::DB_TYPE_MYSQLI == $this->type) {
$this->conn->begin_transaction();
} elseif (self::DB_TYPE_MYSQL == $this->type) {
mysql_query('START TRANSACTION', $this->conn);
mysql_query('BEGIN', $this->conn);
} else {
$this->throwDatabaseTypeError();
}
}
public function exec($query)
{
if (self::DB_TYPE_PDO == $this->type) {
$this->conn->exec($query);
} elseif (self::DB_TYPE_MYSQLI == $this->type) {
$this->conn->query($query);
} elseif (self::DB_TYPE_MYSQL == $this->type) {
mysql_query($query, $this->conn);
} else {
$this->throwDatabaseTypeError();
}
}
public function query($query, $fetch = self::FETCH_ASSOC)
{
if (self::DB_TYPE_PDO == $this->type) {
$q = $this->conn->query($query);
$f = PDO::FETCH_ASSOC;
switch ($fetch) {
case self::FETCH_ASSOC:
default:
$f = PDO::FETCH_ASSOC;
break;
}
return $q->fetch($f);
} elseif (self::DB_TYPE_MYSQLI == $this->type) {
$q = $this->conn->query($query);
$f = 'fetch_assoc';
switch ($fetch) {
case self::FETCH_ASSOC:
default:
$f = 'fetch_assoc';
break;
}
return call_user_func([$q, $f]);
} elseif (self::DB_TYPE_MYSQL == $this->type) {
$q = mysql_query($query);
$f = 'mysql_fetch_assoc';
switch ($fetch) {
case self::FETCH_ASSOC:
default:
$f = 'mysql_fetch_assoc';
break;
}
return call_user_func($f, $q);
} else {
$this->throwDatabaseTypeError();
}
}
public function commit()
{
if (self::DB_TYPE_PDO == $this->type || self::DB_TYPE_MYSQLI == $this->type) {
$this->conn->commit();
} elseif (self::DB_TYPE_MYSQL == $this->type) {
mysql_query('COMMIT', $this->conn);
} else {
$this->throwDatabaseTypeError();
}
}
public function rollback()
{
if (self::DB_TYPE_PDO == $this->type || self::DB_TYPE_MYSQLI == $this->type) {
$this->conn->rollback();
} elseif (self::DB_TYPE_MYSQL == $this->type) {
mysql_query('ROLLBACK', $this->conn);
} else {
$this->throwDatabaseTypeError();
}
}
private function throwDatabaseTypeError()
{
throw new Exception(sprintf('Invalid database type "%s".'), $this->type);
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProDefaultNewsletterTable
{
public function __construct()
{
}
public static function newInstance()
{
return new self();
}
public static function getTableName()
{
if (NewsletterProTools::tableExists('newsletter')) {
return 'newsletter';
} elseif (NewsletterProTools::tableExists('emailsubscription')) {
return 'emailsubscription';
}
return false;
}
public static function hasIdLang()
{
return NewsletterProTools::columnExists(self::getTableName(), 'id_lang');
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProDemoMode
{
/**
* DISABLED.
*/
public static function saveProductTemplate($template)
{
$data = pqnp_demo_mode('demo_product_default_templates');
if (in_array($template, $data)) {
$data = [];
$data['message'] = NewsletterPro::getInstance()->l('You cannot override the default templates in this demo. You must create a new template by pressing the "Save As" button, after that you can save it.');
$data['type'] = false;
return Tools::jsonEncode($data);
}
return false;
}
public static function deleteProductTemplate($path)
{
$response = NewsletterProAjaxResponse::newInstance();
$template = pathinfo($path, PATHINFO_BASENAME);
$data = pqnp_demo_mode('demo_product_default_templates');
if (in_array($template, $data)) {
$response->addError(NewsletterPro::getInstance()->l('This is a demo, you cannot delete the default templats.'));
return $response->display();
}
return false;
}
public static function deleteTemplate($name)
{
$response = NewsletterProAjaxResponse::newInstance();
$template = pathinfo($name, PATHINFO_FILENAME);
$data = pqnp_demo_mode('demo_newsletter_default_templates');
if (in_array($template, $data)) {
$response->addError(NewsletterPro::getInstance()->l('This is a demo, you cannot delete the default templats.'));
return $response->display();
}
return false;
}
public static function deleteSMTP($name)
{
$name = Tools::strtolower($name);
$name_demo = Tools::strtolower(pqnp_demo_mode('demo_freeze_smtp_name'));
if ($name == $name_demo) {
$response = NewsletterProAjaxResponse::newInstance([
'demo_mode' => true,
]);
$response->addError(NewsletterPro::getInstance()->l('This is a demo, you cannot delete this SMTP connection.'));
return $response->display();
}
return false;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProDot
{
public static function create(array $array)
{
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$result = [];
foreach ($ritit as $leafValue) {
$keys = [];
foreach (range(0, $ritit->getDepth()) as $depth) {
$keys[] = $ritit->getSubIterator($depth)->key();
}
$result[join('.', $keys)] = $leafValue;
}
return $result;
}
}

View File

@@ -0,0 +1,208 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProEmail extends ObjectModel
{
public $id_shop;
public $id_shop_group;
public $id_lang;
public $firstname;
public $lastname;
public $email;
public $ip_registration_newsletter;
public $filter_name;
public $date_add;
public $active;
/* defined */
public $context;
public $module;
public $errors = [];
public static $definition = [
'table' => 'newsletter_pro_email',
'primary' => 'id_newsletter_pro_email',
'fields' => [
'id_shop' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'id_shop_group' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'id_lang' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'firstname' => ['type' => self::TYPE_STRING, 'validate' => 'isName'],
'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isName'],
'email' => ['type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true],
'ip_registration_newsletter' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'filter_name' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
],
];
public function __construct($id = null)
{
$this->context = Context::getContext();
$this->module = NewsletterPro::getInstance();
parent::__construct($id);
$this->id_shop = $this->context->shop->id;
$this->id_shop_group = $this->context->shop->id_shop_group;
$this->id_lang = $this->context->language->id;
$this->firstname = '';
$this->lastname = '';
$this->ip_registration_newsletter = Tools::getRemoteAddr();
$this->date_add = date('Y-m-d H:i:s');
$this->active = 1;
}
public static function newInstance($id = null)
{
return new self($id);
}
public function add($autodate = true, $null_values = false)
{
try {
if (!Validate::isName($this->firstname)) {
$this->addError(sprintf(NewsletterPro::getInstance()->l('The "%s" is not a valid name.'), $this->firstname));
}
if (!Validate::isName($this->lastname)) {
$this->addError(sprintf(NewsletterPro::getInstance()->l('The "%s" is not a valid name.'), $this->lastname));
}
if (!Validate::isEmail($this->email)) {
$this->addError(sprintf(NewsletterPro::getInstance()->l('The email "%s" is not a valid email address.'), $this->email));
}
if ($this->isDuplicateEmail()) {
$this->addError(sprintf(NewsletterPro::getInstance()->l('The email "%s" already exists in our database.'), $this->email));
}
if (!$this->hasErrors()) {
return parent::add($autodate, $null_values);
}
} catch (Exception $e) {
$this->addError(NewsletterPro::getInstance()->l('An error occurred when inserting the record into database!'));
}
return false;
}
public function isDuplicateEmail()
{
return Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_email` WHERE `email` = "'.pSQL($this->email).'"
');
}
public function addError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return $this->errors;
}
public function hasErrors()
{
return !empty($this->errors);
}
public static function exportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter_pro_email', $email);
try {
$results = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'newsletter_pro_email`
WHERE `email` = "'.pSQL($email).'"
');
if (count($results) > 0) {
$data = null;
foreach ($results as $row) {
if (true == (bool) $row['active']) {
$data = $row;
break;
}
}
if (!isset($data)) {
$data = $row;
}
$response->addToExport([
NewsletterPro::getInstance()->l('Personal list') => '',
NewsletterPro::getInstance()->l('Subscribed') => ((int) $data['active'] ? NewsletterPro::getInstance()->l('Yes') : NewsletterPro::getInstance()->l('No')),
NewsletterPro::getInstance()->l('Firstname') => (string) $data['firstname'],
NewsletterPro::getInstance()->l('Lastname') => (string) $data['lastname'],
NewsletterPro::getInstance()->l('Email') => (string) $data['email'],
NewsletterPro::getInstance()->l('IP address') => (string) $data['ip_registration_newsletter'],
NewsletterPro::getInstance()->l('Date add') => (string) $data['date_add'],
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function privacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter_pro_email', $email);
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_email` WHERE `email` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function clearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter_pro_email', $email);
try {
if (Db::getInstance()->delete('newsletter_pro_email', '`email` = "'.pSQL($email).'"')) {
$response->addToCount((int) Db::getInstance()->Affected_Rows());
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,218 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProEmailExclusion
{
public static function newInstance()
{
return new self();
}
public function add($emails)
{
$added = 0;
$duplicate = 0;
if (is_array($emails)) {
foreach ($emails as $email) {
if ($this->emailExists($email)) {
++$duplicate;
} else {
$added += $this->addStr($email);
}
}
} else {
if ($this->emailExists($emails)) {
++$duplicate;
} else {
$added += $this->addStr($emails);
}
}
return [$added, $duplicate];
}
private function addStr($email)
{
try {
return (int) Db::getInstance()->insert('newsletter_pro_email_exclusion', [
'email' => $email,
]);
} catch (Exception $e) {
return 0;
}
}
public function emailExists($email)
{
return Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `'._DB_PREFIX_.'newsletter_pro_email_exclusion`
WHERE `email` = "'.pSQL($email).'"
');
}
public function emptyList()
{
return Db::getInstance()->execute('
DELETE FROM `'._DB_PREFIX_.'newsletter_pro_email_exclusion` WHERE 1
');
}
/**
* Get emails from table.
*
* @param array $tables [0] - table name [1] - left join table name
* @param array $ids
* @param bool $bool_remaining_emails
* @param bool $bool_sent_emails
*
* @return array
*/
private function getEmailsFromTable($tables, $ids, $bool_remaining_emails, $bool_sent_emails)
{
if (empty($ids) || (!$bool_remaining_emails && !$bool_sent_emails)) {
return [];
}
$table = $tables[0];
$join = $tables[1];
$sql = 'SELECT ts.`emails_to_send`, ts.`emails_sent` FROM `'._DB_PREFIX_.pSQL($table).'` t
LEFT JOIN `'._DB_PREFIX_.pSQL($join).'` ts ON (ts.`id_'.pSQL($table).'` = t.`id_'.pSQL($table).'`)
WHERE t.`id_'.pSQL($table).'` IN (';
foreach ($ids as $id) {
$sql .= (int) $id.',';
}
$sql = rtrim($sql, ',').')';
$result = Db::getInstance()->executeS($sql);
$emails_to_send = [];
$emails_sent = [];
foreach ($result as $value) {
if ($bool_remaining_emails) {
$em = NewsletterProTools::unSerialize($value['emails_to_send']);
$emails_to_send = array_merge($emails_to_send, $em);
}
if ($bool_sent_emails) {
$em = NewsletterProTools::unSerialize($value['emails_sent']);
}
$emails_m = [];
foreach ($em as $val) {
$emails_m[] = $val['email'];
}
$emails_sent = array_merge($emails_sent, $emails_m);
}
return array_unique(array_merge($emails_to_send, $emails_sent));
}
/**
* Get emails from task.
*
* @param array $ids
* @param bool $bool_remaining_emails
* @param bool $bool_sent_emails
*
* @return array
*/
public function getEmailsFromTask($ids, $bool_remaining_emails, $bool_sent_emails)
{
return $this->getEmailsFromTable(['newsletter_pro_task', 'newsletter_pro_task_step'], $ids, $bool_remaining_emails, $bool_sent_emails);
}
/**
* Get emails from sent.
*
* @param array $ids
* @param bool $bool_remaining_emails
* @param bool $bool_sent_emails
*
* @return array
*/
public function getEmailsFromSend($ids, $bool_remaining_emails, $bool_sent_emails)
{
return $this->getEmailsFromTable(['newsletter_pro_send', 'newsletter_pro_send_step'], $ids, $bool_remaining_emails, $bool_sent_emails);
}
public function countList()
{
return Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_email_exclusion`
');
}
public static function exportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter_pro_email_exclusion', $email);
try {
$row = Db::getInstance()->getRow('
SELECT * FROM `'._DB_PREFIX_.'newsletter_pro_email_exclusion`
WHERE `email` = "'.pSQL($email).'"
');
if ($row) {
$response->addToExport([
NewsletterPro::getInstance()->l('Excluded from send') => '',
NewsletterPro::getInstance()->l('Email') => $row['email'],
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function privacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter_pro_email_exclusion', $email);
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_email_exclusion` WHERE `email` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function clearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter_pro_email_exclusion', $email);
try {
if (Db::getInstance()->delete('newsletter_pro_email_exclusion', '`email` = "'.pSQL($email).'"')) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProEmbedImages
{
private $template;
private $images;
public function __construct($template)
{
$this->template = $template;
$this->images = [];
if ((bool) pqnp_config('SEND_EMBEDED_IMAGES')) {
$this->template = preg_replace_callback('/(<img.*src=("|\'))(http.*?)(\2[^>]+>)/', [$this, 'replaceEmbedCallback'], $this->template);
}
}
public function getTemplate()
{
return $this->template;
}
public function getImages()
{
return $this->images;
}
public function replaceEmbedCallback($matches)
{
$path = $matches[3];
if (preg_match('/data-embed=("|\')0\1/', $matches[0])) {
return $matches[0];
}
$swift_image = NewsletterPro_Swift_Image::fromPath($path);
$this->images[] = $swift_image;
return $matches[1].'cid:'.$swift_image->getId().$matches[4];
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,42 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProEvaluate
{
private $success;
public function __construct()
{
$this->success = [];
}
public static function newInstance()
{
return new self();
}
public function add($value)
{
$this->success[] = (bool) $value;
}
public function success()
{
return !in_array(false, $this->success);
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProExtendProductVariables
{
private $module;
private $images;
private $attributes_groups;
private $attributes_combinations;
private $prices;
private $prices_attributes;
private $variables;
private $variables_lang;
public function __construct(&$params, $product, $context)
{
$this->module = NewsletterPro::getInstance();
$this->images = &$params['images'];
$this->attributes_groups = &$params['attributes_groups'];
$this->attributes_combinations = &$params['attributes_combinations'];
$this->prices = &$params['prices'];
$this->prices_attributes = &$params['prices_attributes'];
$this->variables = &$params['variables'];
$this->variables_lang = &$params['variables_lang'];
// Variables
$new_variables = $this->extendVariables($this->variables);
if (!empty($new_variables)) {
foreach ($new_variables as $key => $value) {
$this->variables[$key] = $value;
}
}
// Variables Lang
$languages = Language::getLanguages(false);
$new_variables = [];
foreach ($languages as $lang) {
$new_variables[$lang['id_lang']] = $this->extendVariablesLang($lang);
}
if (!empty($new_variables)) {
foreach ($new_variables as $id_lang => $content) {
foreach ($content as $variable_name => $value) {
$this->variables_lang[$variable_name][$id_lang] = $value;
}
}
}
// Prices
$currencies = Currency::getCurrencies(true, false, true);
$new_variables = [];
foreach ($currencies as $currency) {
$new_variables[$currency->id] = $this->extendPrices($currency, $this->prices[$currency->id]);
}
if (!empty($new_variables)) {
foreach ($new_variables as $id_currency => $content) {
foreach ($content as $variable_name => $value) {
$this->prices[$id_currency][$variable_name] = $value;
}
}
}
}
public static function newInstance(&$params, $product, $context)
{
return new self($params, $product, $context);
}
/**
* Here you can extend the variables.
*/
private function extendVariables()
{
$new_variables = [];
$new_variables['hello_world'] = 'Hello World!';
return $new_variables;
}
/**
* Here you can extend the language variables.
*/
private function extendVariablesLang(array $lang)
{
$new_variables = [];
if ('en' == $lang['iso_code']) {
$new_variables['hello_world_lang'] = 'Hello World!';
} else {
$new_variables['hello_world_lang'] = 'Hello World Translated!';
}
return $new_variables;
}
/**
* Here you can extend the price variables.
*/
private function extendPrices(Currency $currency, $price_variables)
{
$new_variables = [];
$new_variables['hello_world_price'] = 'Just for test - '.$price_variables['price_display'];
return $new_variables;
}
}

View File

@@ -0,0 +1,85 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProExtendTemplateVars
{
public static $external_vars = [
'variables/last_delivery_address/last_delivery_address.php' => false,
'variables/gender/gender.php' => false,
];
public static function newInstance()
{
return new self();
}
/**
* Here you can process the current user information to create your newsletter template variables
* You can work aslo with database.
*
* assign variables as object :
* $user->hello_world = 'Hello World!';
* The variable name will be {hello_world}
*/
public function set($user)
{
$user->hello_world = 'Hello World!';
$this->loadExternalVars($user);
return $this;
}
/**
* The user parameter is used in the include path.
*/
public function loadExternalVars(&$user)
{
try {
$declared_classes = get_declared_classes();
foreach (self::$external_vars as $path => $to_load) {
$path = dirname(dirname(__FILE__)).'/'.$path;
if (file_exists($path) && $to_load) {
$pathinfo = pathinfo($path);
$variable_name = $pathinfo['filename'];
$class_name_array = explode('_', $variable_name);
$class_name = '';
foreach ($class_name_array as $value) {
if ('' !== trim($value)) {
$class_name .= Tools::ucfirst($value);
}
}
$class_name = 'NewsletterProTemplateVariable'.$class_name;
if (preg_match('/^[A-Za-z0-9-]+$/', $class_name) && !class_exists($class_name) && !in_array($class_name, $declared_classes)) {
include $path;
if (class_exists($class_name)) {
$declared_classes[] = $class_name;
new $class_name($user);
}
}
}
}
} catch (Exception $e) {
NewsletterProLog::writeStrip($e->getMessage(), NewsletterProLog::ERROR_FILE);
}
}
}

View File

@@ -0,0 +1,149 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProFilters
{
const TYPE_SELECTION = 'selection';
const TYPE_FILTER = 'filter';
private $selection_tables = [
'customer' => 'c',
'newsletter' => 's',
'newsletter_pro' => 'a',
];
public function get($srt)
{
if (self::TYPE_SELECTION == $this->getType($srt)) {
return $this->getSelection($srt);
} elseif (self::TYPE_FILTER == $this->getType($srt)) {
return $this->getFilter($srt);
}
return [];
}
private function getType($srt)
{
$srt = Tools::substr($srt, 0, 20);
if (preg_match('/^'.self::TYPE_SELECTION.':/', $srt)) {
return self::TYPE_SELECTION;
} elseif (preg_match('/^'.self::TYPE_FILTER.':/', $srt)) {
return self::TYPE_FILTER;
}
return false;
}
public function getSelection($str)
{
$selection = $this->matchSelection($str);
$sqls = $this->getSelectionSql($selection);
$result = $this->runSelectSql($sqls);
return $result;
}
private function matchSelection($str)
{
$selection = [];
foreach ($this->selection_tables as $table => $short) {
if (preg_match('/'.$short.':\[(?P<selection>[^]]+)/', $str, $match)) {
$selection[$table] = str_replace(' ', '', $match['selection']);
}
}
return $selection;
}
private function getSelectionSql($selection)
{
$sqls = [];
foreach ($selection as $table => $ids) {
$array_ids = explode(',', $ids);
$list = [];
$range = [];
foreach ($array_ids as $value) {
if (false !== strpos($value, '-')) {
$range[] = $value;
} else {
$list[] = $value;
}
}
$fields = $this->getTableFields($table);
$id_field = $fields[0];
if ((isset($fields[1]) && '*' == $fields[1]) || 1 == count($fields)) {
$sql_fields = '*';
} else {
$sql_fields = '`'.join($fields, '`,`').'` ';
}
$sqls[$table] = 'SELECT '.$sql_fields.' FROM `'._DB_PREFIX_.$table.'` ';
$sqls[$table] .= 'WHERE `'.$id_field.'` ';
$between = '';
$range_end = ' OR `'.$id_field.'` ';
foreach ($range as $value) {
$between .= ' BETWEEN '.str_replace('-', ' AND ', $value).$range_end;
}
$sqls[$table] .= rtrim($between, $range_end).' ';
$list_join = join($list, ',');
if (!empty($list)) {
$sqls[$table] .= ' OR `'.$id_field.'` IN ('.$list_join.') ';
}
$sqls[$table] .= ';';
}
return $sqls;
}
private function runSelectSql($sqls)
{
$result = [];
foreach ($sqls as $table => $sql) {
$res = Db::getInstance()->executeS($sql);
if (!empty($res)) {
$result[$table] = $res;
}
}
return $result;
}
private function getTableFields($table)
{
$tables = [];
// If the second parameter is * the entire fields will be selected.
// Write more then two arguments to select sepecific fields.
$tables['customer'] = ['id_customer'];
$tables['newsletter'] = ['id'];
$tables['newsletter_pro'] = ['newsletter_pro'];
return $tables[$table];
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProFiltersSelection extends ObjectModel
{
public $name;
public $value;
public static $definition = [
'table' => 'newsletter_pro_filters_selection',
'primary' => 'id_newsletter_pro_filters_selection',
'fields' => [
'name' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true],
'value' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
],
];
public static function newInstance($id = null)
{
return new self($id);
}
public function nameExists()
{
return (bool) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_filters_selection`
WHERE `name` = "'.pSQL($this->name).'"
');
}
public static function getFilters()
{
return Db::getInstance()->executeS('
SELECT `id_newsletter_pro_filters_selection`, `name`
FROM `'._DB_PREFIX_.'newsletter_pro_filters_selection`
');
}
}

View File

@@ -0,0 +1,336 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProForward extends ObjectModel
{
public $from;
public $to;
public $date_add;
/* defined vars */
public $errors = [];
public $context;
public $module;
const FOREWORD_LIMIT = 5;
public static $static_errors = [];
public static $definition = [
'table' => 'newsletter_pro_forward',
'primary' => 'id_newsletter_pro_forward',
'fields' => [
'from' => ['type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true],
'to' => ['type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDateFormat'],
],
];
public function __construct($id = null)
{
parent::__construct($id);
$this->context = Context::getContext();
$this->module = $this->context->controller->module;
}
public function addError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return array_unique($this->errors);
}
public function add($autodate = true, $null_values = false)
{
if ($this->limitExceeded()) {
$this->addError(sprintf($this->module->l('You cannot add more emails. You exceeded the limit of %s emails.'), self::FOREWORD_LIMIT));
return false;
}
if ($this->isToDuplicate()) {
$this->addError(sprintf($this->module->l('Your friend with the email %s is already subscribed at our newsletter.'), $this->to));
return false;
}
if ($info = $this->getUserTableByEmail($this->to)) {
$is_subscribed = (int) Db::getInstance()->getValue('SELECT `'.$info['newsletter'].'` FROM `'._DB_PREFIX_.$info['table'].'` WHERE `email` = "'.pSQL($this->to).'"');
if ($is_subscribed) {
$this->addError(sprintf($this->module->l('Your friend with the email %s is already subscribed at our newsletter.'), $this->to));
return false;
}
}
try {
$return = parent::add($autodate, $null_values);
if (!$return) {
$this->addError(sprintf($this->module->l('An error occurred when adding the email %s into the database.'), $this->to));
}
return $return;
} catch (Exception $e) {
$this->addError(sprintf($this->module->l('An error occurred when adding the email %s into the database.'), $this->to));
}
return false;
}
public function limitExceeded()
{
$limit = (int) Db::getInstance()->getValue('SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_forward` WHERE `from` = "'.pSQL($this->from).'"');
if ($limit >= self::FOREWORD_LIMIT) {
return true;
}
return false;
}
public static function addMultiple($from, $emails)
{
foreach ($emails as $email) {
$instance = new NewsletterProForward();
$instance->from = $from;
$instance->to = $email;
$instance->add();
if ($instance->hasErrors()) {
self::$static_errors = array_merge(self::$static_errors, $instance->getErrors());
}
}
}
public static function getStaticErrors()
{
return array_unique(self::$static_errors);
}
public static function addStaticError($error)
{
self::$static_errors[] = $error;
}
public static function hasStaticErrors()
{
return !empty(self::$static_errors);
}
public function hasErrors()
{
return !empty($this->errors);
}
public function delete()
{
try {
$result = parent::delete();
if (!$result) {
$this->addError(sprintf($this->module->l('An error occurred when deleting the email %s.'), $this->to));
}
return $result;
} catch (Exception $e) {
$this->addError(sprintf($this->module->l('An error occurred when deleting the email %s.'), $this->to));
}
return false;
}
public function isToDuplicate()
{
if (self::getInstanceByTo($this->to)) {
return true;
}
return false;
}
public static function getInstanceByTo($to)
{
$id = (int) Db::getInstance()->getValue('SELECT `id_newsletter_pro_forward` FROM `'._DB_PREFIX_.'newsletter_pro_forward` WHERE `to` = "'.pSQL($to).'"');
if ($id) {
return new NewsletterProForward($id);
}
return false;
}
public function getUserTableByEmail($email)
{
$definition = [
'customer' => ['email' => 'email', 'newsletter' => 'newsletter'],
'newsletter' => ['email' => 'email', 'newsletter' => 'active'],
'emailsubscription' => ['email' => 'email', 'newsletter' => 'active'],
'newsletter_pro_email' => ['email' => 'email', 'newsletter' => 'active'],
];
foreach ($definition as $table => $fields) {
if (NewsletterProTools::tableExists($table)) {
$sql = 'SELECT COUNT(*) FROM `'._DB_PREFIX_.$table.'` WHERE `'.$fields['email'].'` = "'.pSQL($email).'"';
if (Db::getInstance()->getValue($sql)) {
return [
'table' => $table,
'email' => $fields['email'],
'newsletter' => $fields['newsletter'],
];
}
}
}
return false;
}
public static function getEmailsToByEmailFrom($from)
{
if (is_array($from)) {
reset($from);
$from = key($from);
}
$emails = [];
$result = Db::getInstance()->executeS('SELECT `to` FROM `'._DB_PREFIX_.'newsletter_pro_forward` WHERE `from` = "'.pSQL($from).'"');
if ($result) {
foreach ($result as $email) {
$emails[] = $email['to'];
}
}
return $emails;
}
public static function getForwarders($from)
{
$emails = self::getEmailsToByEmailFrom($from);
$emails_join = '"'.trim(join($emails, '","')).'"';
$definition = [
'customer' => ['email' => 'email', 'newsletter' => 'newsletter'],
'newsletter_pro_email' => ['email' => 'email', 'newsletter' => 'active'],
'newsletter_pro_subscribers' => ['email' => 'email', 'newsletter' => 'active'],
];
if (NewsletterProTools::tableExists('newsletter')) {
$definition['newsletter'] = ['email' => 'email', 'newsletter' => 'active'];
}
if (NewsletterProTools::tableExists('emailsubscription')) {
$definition['emailsubscription'] = ['email' => 'email', 'newsletter' => 'active'];
}
$valid_emails = [];
$delete_emails = [];
if (!empty($emails)) {
foreach ($definition as $table => $fields) {
$sql = 'SELECT `'.$fields['email'].'` FROM `'._DB_PREFIX_.$table.'` WHERE `'.$fields['email'].'` IN ('.$emails_join.')';
if ($result = Db::getInstance()->executeS($sql)) {
foreach ($result as $value) {
$delete_emails[] = $value['email'];
}
}
}
}
$delete_emails = array_unique($delete_emails);
foreach ($delete_emails as $to) {
Db::getInstance()->delete('newsletter_pro_forward', '`to` = "'.pSQL($to).'"', 1);
}
$valid_emails = array_diff($emails, $delete_emails);
return $valid_emails;
}
public static function exportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter_pro_forward', $email);
try {
$from_count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_forward`
WHERE `from` = "'.pSQL($email).'"
');
if ($from_count > 0) {
$response->addToExport([
NewsletterPro::getInstance()->l('Send forward') => '',
NewsletterPro::getInstance()->l('Total Emails') => $from_count,
]);
}
$to_count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_forward`
WHERE `to` = "'.pSQL($email).'"
');
if ($to_count > 0) {
$response->addToExport([
NewsletterPro::getInstance()->l('Receive forward') => '',
NewsletterPro::getInstance()->l('Total emails') => $to_count,
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function privacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter_pro_forward', $email);
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_forward`
WHERE `from` = "'.pSQL($email).'"
OR `to` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function clearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter_pro_forward', $email);
try {
if (Db::getInstance()->delete('newsletter_pro_forward', '`from` = "'.pSQL($email).'" OR `to` = "'.pSQL($email).'"')) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,101 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProForwardRecipients
{
public $recipients = [];
public $recipients_name = [];
public static function newInstance()
{
return new self();
}
public function add($from, $to)
{
if (is_array($to)) {
foreach ($to as $email) {
$this->addRecipient($from, $email);
}
} else {
$this->addRecipient($from, $to);
}
}
private function addRecipient($from, $to)
{
if (is_array($from)) {
reset($from);
$name = key($from);
$email = $from[$name];
$this->recipients_name[$email] = $name;
$this->recipients[$email][] = $to;
} else {
$this->recipients[$from][] = $to;
}
}
public function buildForwardersRecursive($parent_email, $level = 100)
{
// this is for security
if ($level > 0) {
if ($child_emails = $this->getRecipient($parent_email)) {
foreach ($child_emails as $email) {
if ($forwards = NewsletterProForward::getForwarders($email)) {
$this->add($email, $forwards);
return $this->buildForwardersRecursive($email, --$level);
}
}
}
}
return false;
}
public function getRecipients()
{
return $this->recipients;
}
public function getRecipientsName()
{
return $this->recipients_name;
}
public function getRecipient($email)
{
if (isset($this->recipients[$email])) {
return $this->recipients[$email];
}
return false;
}
public function getRecipientName($email)
{
if (isset($this->recipients_name[$email])) {
return $this->recipients_name[$email];
}
return '';
}
}

View File

@@ -0,0 +1,97 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProFwdUnsubscribed extends ObjectModel
{
public $id_newsletter_pro_tpl_history;
public $email;
public $date_add;
public $date_upd;
public static $definition = [
'table' => 'newsletter_pro_fwd_unsibscribed',
'primary' => 'id_newsletter_pro_fwd_unsibscribed',
'fields' => [
'id_newsletter_pro_tpl_history' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true],
'email' => ['type' => self::TYPE_STRING, 'validate' => 'isEmail', 'size' => 255, 'required' => true],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
],
];
public function __construct($id = null)
{
parent::__construct($id);
}
public static function exportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter_pro_fwd_unsibscribed', $email);
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_fwd_unsibscribed` WHERE `email` = "'.pSQL($email).'"
');
if ($count > 0) {
$response->addToExport([
NewsletterPro::getInstance()->l('Forward unsubscribed') => '',
NewsletterPro::getInstance()->l('Total') => $count,
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function privacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter_pro_fwd_unsibscribed', $email);
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_fwd_unsibscribed` WHERE `email` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
public static function clearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter_pro_fwd_unsibscribed', $email);
try {
if (Db::getInstance()->delete('newsletter_pro_fwd_unsibscribed', '`email` = "'.pSQL($email).'"')) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,272 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProGenerateCustomers
{
private $id_shop;
private $id_shop_group;
private $id_lang;
private $id_gender;
private $email_prefix = 'demo.com';
public function __construct()
{
ini_set('max_execution_time', '15000');
$this->id_shop = [];
$this->id_shop_group = [];
$this->id_lang = [];
$this->id_gender = [];
foreach (Shop::getShops() as $value) {
$this->id_shop[] = (int) $value['id_shop'];
}
foreach (ShopGroup::getShopGroups() as $value) {
$this->id_shop_group[] = (int) $value->id;
}
foreach (Language::getLanguages() as $value) {
$this->id_lang[] = (int) $value['id_lang'];
}
foreach (Gender::getGenders() as $value) {
$this->id_gender[] = (int) $value->id;
}
}
public static function newInstance()
{
return new self();
}
public function generate($customers, $visitors, $visitors_np, $added)
{
$sum = 0;
$sum += $this->generateCustomers($customers);
$sum += $this->generateVisitors($visitors);
$sum += $this->generateVisitorsNp($visitors_np);
$sum += $this->generateAdded($added);
return $sum;
}
public function generateCustomers($num)
{
$sum = 0;
for ($i = 0; $i < $num; ++$i) {
$email = $this->getEmail();
$firstname = $this->getFirstNameFromEmail($email);
$lastname = $this->getLastNameFromEmail($email);
$customer = new Customer();
$customer->id_shop = $this->getIdShop();
$customer->id_shop_group = $this->getIdShopGroup($customer->id_shop);
$customer->note = 'sas';
$customer->id_gender = $this->getIdGender();
$customer->id_default_group = $this->getDefaultGroup();
$customer->id_lang = $this->getIdLang();
$customer->lastname = $firstname;
$customer->firstname = $lastname;
$customer->birthday = date('Y-m-d');
$customer->email = $email;
$customer->newsletter = 1;
$customer->ip_registration_newsletter = '127.0.0.1';
$customer->newsletter_date_add = '2013-06-17 19:28:06';
$customer->website = 'www.nowebsite.com';
$customer->company = 'freelancer';
$customer->show_public_prices = 1;
$customer->id_risk = 0;
$customer->passwd = 'abcdefghijklmnoprstuvxyz';
$customer->active = 1;
$customer->is_guest = 0;
$customer->deleted = 0;
$customer->date_add = date('Y-m-d H:i:s');
$customer->date_upd = date('Y-m-d H:i:s');
if ($customer->save()) {
++$sum;
}
}
return $sum;
}
public function generateVisitors($num)
{
$sum = 0;
if (NewsletterProTools::tableExists('newsletter')) {
for ($i = 0; $i < $num; ++$i) {
$id_shop = $this->getIdShop();
$sql = 'INSERT INTO `'._DB_PREFIX_.'newsletter`
(`id_shop`, `id_shop_group`, `email`, `newsletter_date_add`, `ip_registration_newsletter`, `http_referer`, `active`)
VALUES
('.(int) $id_shop.', '.(int) $this->getIdShopGroup($id_shop).", '".pSQL($this->getEmail())."', NULL, '127.0.0.1', NULL, 1);";
if (Db::getInstance()->execute($sql)) {
++$sum;
}
}
} elseif (NewsletterProTools::tableExists('emailsubscription')) {
for ($i = 0; $i < $num; ++$i) {
$id_shop = $this->getIdShop();
$sql = 'INSERT INTO `'._DB_PREFIX_.'emailsubscription`
(`id_shop`, `id_shop_group`, `email`, `newsletter_date_add`, `ip_registration_newsletter`, `http_referer`, `active`)
VALUES
('.(int) $id_shop.', '.(int) $this->getIdShopGroup($id_shop).", '".pSQL($this->getEmail())."', NULL, '127.0.0.1', NULL, 1);";
if (Db::getInstance()->execute($sql)) {
++$sum;
}
}
}
return $sum;
}
public function generateVisitorsNp($num)
{
$sum = 0;
for ($i = 0; $i < $num; ++$i) {
$email = $this->getEmail();
$id_shop = $this->getIdShop();
$sql = 'INSERT INTO `'._DB_PREFIX_.'newsletter_pro_subscribers`
(`id_shop`, `id_shop_group`, `id_lang`, `id_gender`, `firstname`, `lastname`, `email`, `birthday`, `ip_registration_newsletter`, `list_of_interest`, `date_add`, `active`)
VALUES
('.(int) $id_shop.', '.(int) $this->getIdShopGroup($id_shop).', '.(int) $this->getIdLang().', '.(int) $this->getIdGender().', "'.pSQL($this->getFirstNameFromEmail($email)).'", "'.pSQL($this->getLastNameFromEmail($email)).'", "'.pSQL($email).'", "'.pSQL(date('Y-m-d')).'", "'.pSQL('127.0.0.1').'", NULL, "'.pSQL(date('Y-m-d H:i:s')).'", 1)';
if (Db::getInstance()->execute($sql)) {
++$sum;
}
}
return $sum;
}
public function generateAdded($num)
{
$sum = 0;
for ($i = 0; $i < $num; ++$i) {
$email = $this->getEmail();
$id_shop = $this->getIdShop();
$sql = 'INSERT INTO `'._DB_PREFIX_.'newsletter_pro_email`
(`id_shop`, `id_shop_group`, `id_lang`, `firstname`, `lastname`, `email`, `date_add`, `ip_registration_newsletter`, `active`)
VALUES
('.(int) $id_shop.', '.(int) $this->getIdShopGroup($id_shop).', '.(int) $this->getIdLang().", '".pSQL($this->getFirstNameFromEmail($email))."', '".pSQL($this->getLastNameFromEmail($email))."', '".pSQL($email)."', NULL, '127.0.0.1', 1 );";
if (Db::getInstance()->execute($sql)) {
++$sum;
}
}
return $sum;
}
private function getIdShop()
{
return $this->random($this->id_shop);
}
private function getIdShopGroup($id_shop)
{
$shop = new Shop($id_shop);
if (Validate::isLoadedObject($shop)) {
return (int) $shop->id_shop_group;
}
return $this->id_shop_group[0];
}
private function getDefaultGroup()
{
return (int) Configuration::get('PS_CUSTOMER_GROUP');
}
private function getIdRandomShopGroup()
{
return $this->random($this->id_shop_group);
}
private function getIdLang()
{
return $this->random($this->id_lang);
}
private function getIdGender()
{
return $this->random($this->id_gender);
}
private function getEmail()
{
$upper = 'ABCDEFGHIJKLMNOPRSTUVXYZ';
$lower = 'abcdefghijklmnoprstuvxyz';
$firstname = Tools::substr(str_shuffle($upper), 0, 1).Tools::substr(str_shuffle($lower), 0, rand(5, 8));
$lastname = Tools::substr(str_shuffle($upper), 0, 1).Tools::substr(str_shuffle($lower), 0, rand(5, 8));
$email = Tools::strtolower($firstname).'.'.Tools::strtolower($lastname).'@'.$this->email_prefix;
return $email;
}
private function getFirstNameFromEmail($email)
{
if (preg_match('/^(\w+)\.(\w+)/', $email, $match)) {
return Tools::ucfirst($match[1]);
}
return 'Unknown';
}
private function getLastNameFromEmail($email)
{
if (preg_match('/^(\w+)\.(\w+)/', $email, $match)) {
return Tools::ucfirst($match[2]);
}
return 'Unknown';
}
private function getName()
{
$upper = 'ABCDEFGHIJKLMNOPRSTUVXYZ';
$lower = 'abcdefghijklmnoprstuvxyz';
$name = Tools::substr(str_shuffle($upper), 0, 1).Tools::substr(str_shuffle($lower), 0, rand(5, 8));
return $name;
}
private function random($object)
{
return rand($object[0], $object[count($object) - 1]);
}
}

View File

@@ -0,0 +1,117 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProGenerateOrders
{
private $customers;
private $id_address;
public function __construct()
{
// for prestashop 1.7 not working
if (file_exists(_PS_MODULE_DIR_.'bankwire/bankwire.php')) {
include_once _PS_MODULE_DIR_.'bankwire/bankwire.php';
$this->customers = Customer::getCustomers();
$id_customer = Db::getInstance()->getValue('SELECT * FROM `'._DB_PREFIX_.'customer` WHERE `email` = "'.pSQL('pub@prestashop.com').'"');
$pub = new Customer($id_customer);
$address = $pub->getAddresses(Configuration::get('PS_LANG_DEFAULT'));
$this->id_address = $address[key($address)]['id_address'];
}
}
public static function newInstance()
{
return new self();
}
public function generate()
{
if (!file_exists(_PS_MODULE_DIR_.'bankwire/bankwire.php')) {
return 0;
}
echo '<pre>';
$id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
$orders = 0;
foreach ($this->customers as $cus) {
++$orders;
$id_customer = $_GET['id_customer'] = (int) $cus['id_customer'];
$customer = new Customer((int) $id_customer);
$this->context = Context::getContext();
$this->context->customer = &$customer;
$this->context->shop = new Shop($this->context->customer->id_shop);
$configuration = Configuration::getMultiple([
'PS_LANG_DEFAULT',
'PS_CURRENCY_DEFAULT',
]);
$id_address_delivery = $id_address_invoice = $this->id_address;
$currency = new Currency((int) $configuration['PS_CURRENCY_DEFAULT']);
$this->context->currency = &$currency;
$cart = new Cart();
$cart->id_currency = (int) $configuration['PS_CURRENCY_DEFAULT'];
$cart->id_lang = (int) $customer->id_lang;
$cart->id_shop_group = (int) $this->context->shop->id_shop_group;
$cart->secure_key = $customer->secure_key;
$cart->add();
$id_cart = (int) $cart->id;
$cart = new Cart((int) $id_cart);
$this->context->cart = &$cart;
$cart->id_address_delivery = (int) $id_address_delivery;
$cart->id_address_invoice = (int) $id_address_invoice;
$cart->id_carrier = (int) $id_carrier;
$cart->id_customer = (int) $customer->id;
$products_id = [1, 2, 3, 4, 5, 6, 7];
$qty = rand(1, 3);
$nb = rand(1, count($products_id) / 2);
if ($nb < 1) {
$nb = 1;
}
for ($i = 0; $i < $nb; ++$i) {
$id_product = $products_id[$i];
$cart->updateQty($qty, $id_product);
}
$bankwire = new BankWire();
$total = (float) ($cart->getOrderTotal(true, Cart::BOTH));
try {
$bankwire->validateOrder($cart->id, Configuration::get('PS_OS_BANKWIRE'), $total, $bankwire->displayName, null, [], (int) $currency->id, false, $customer->secure_key);
new Order($bankwire->currentOrder);
} catch (Exception $e) {
echo $customer->email.' -> '.$e->getMessage().'<br>';
}
}
echo '</pre>';
return $orders;
}
}

View File

@@ -0,0 +1,350 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProHTMLRender
{
/**
* @version: 2.0
*
* Format columns
* Example;
*
* {# title({product_name}, 'Product Name') #} {# title({serial_nubmer.value}, 'S/N') #} {# title({product_reference}, 'Reference') #} {# title({warranty_time_month}, 'Warranty') #}
* <!-- @foreach {serial_nubmer} as {sn} -->
* {# column({product_name}) #} {# column({sn.value}) #} {# column({product_reference}) #} {# column({warranty_time_month} months) #}
* <!-- @endforeach -->
*
* <!-- @if intVal({warranty_valid}) == 1 -->
* Condition content here.
* <!-- @endif -->
*
* <!-- @if intVal({warranty_valid}) == 1 -->
* If content here.
* <!-- @else -->
* Else content here.
* <!-- @endif -->
*
* <!-- @foreach {serial_nubmer} as {sn} -->
* Serial number: {sn.value}
* <!-- @endforeach -->
*
* <input condition-if="intval({display_list_of_interest}) == 1" checked="true" condition-else checked="false" condition-endif type="checkbox" name="list_of_interest[]" value="{item.id_newsletter_pro_list_of_interest}">
*
* Example of the render attributes:
*
* {np_zip_code attrs="class: pqnp-popup-form-control"}
* {np_select attrs="class: pqnp-popup-form-control"}
* {np_checkbox containerAttrs="class: pqnp-popup-row" labelAttrs="class: pqnp-popup-col-sm-6"}
* {np_radio containerAttrs="class: pqnp-custom-radio-inline"}
* {np_textarea attrs="class: pqnp-popup-form-control"}
*/
public static function output($content, $variables = [], $use_conditions = true, $format_columns = false)
{
if ($format_columns) {
$columns = [];
$column_index = 0;
$content = preg_replace_callback('/\{\#(?:\s+?)(title)\((.*?),(?:\s+?)(\'|\")(.*?)\3\)(?:\s+?)\#\}/', function ($match) use ($variables, &$columns) {
$func_name = $match[1];
$argument = $match[2];
$title = $match[4];
if ('{' === Tools::substr($argument, 0, 1)) {
$variable_content = Tools::substr($argument, 1, -1);
$variable_exp = explode('.', $variable_content);
$variable_name = $variable_exp[0];
if (array_key_exists($variable_name, $variables)) {
$variable_value = $variables[$variable_name];
$title_len = Tools::strlen($title);
if (is_array($variable_value)) {
$max = 0;
foreach ($variable_value as $value) {
$len = Tools::strlen((string) $value[$variable_exp[1]]);
if ($len > $max) {
$max = $len;
}
}
$columns[] = [
'title' => $title,
'len' => $max,
'title_len' => $title_len,
];
if ($title_len > $max) {
return $title.str_repeat(' ', 1);
} else {
return $title.str_repeat(' ', $max - $title_len);
}
} else {
$item_len = Tools::strlen((string) $variable_value);
$columns[] = [
'title' => $title,
'len' => $item_len,
'title_len' => $title_len,
];
if ($title_len > $item_len) {
return $title.str_repeat(' ', 1);
} else {
return $title.str_repeat(' ', $item_len - $title_len);
}
}
}
}
return ' ';
}, $content);
$content = preg_replace_callback('/\{\#(?:\s+?)(column)\((.*?)\)(?:\s+?)\#\}/', function ($match) use ($columns, &$column_index) {
$column = $columns[$column_index++];
if ($column['title_len'] > $column['len']) {
return $match[2].str_repeat(' ', $column['title_len'] - $column['len'] + 1);
}
return $match[2];
}, $content);
}
if ($use_conditions) {
$content = self::renderIfElse($content, $variables, false, false);
$content = self::renderIfElse($content, $variables, false, true);
$content = preg_replace_callback('/<!--\s+?@foreach\s+\{(?P<variable_name>\w+)\}\s+as\s+\{(?P<item>\w+)\}\s+?-->(?P<row>[\s\S]+?)<!--\s+?@endforeach\s+-->/', function ($match) use ($variables) {
$variable_name = $match['variable_name'];
$item = $match['item'];
$row = $match['row'];
if (array_key_exists($variable_name, $variables) && is_array($variables[$variable_name])) {
$loop_data = [];
foreach ($variables[$variable_name] as $variable_value) {
$row_conditions = self::renderIfElse($row, $variable_value, true, false);
$row_conditions = self::renderIfElse($row, $variable_value, true, true);
$row_render = preg_replace_callback('/\{'.preg_quote($item).'(\.(?P<key>[\w]+))?\}/', function ($row_match) use ($variable_value) {
if (is_array($variable_value)) {
if (array_key_exists($row_match['key'], $variable_value)) {
return $variable_value[$row_match['key']];
}
} else {
return $variable_value;
}
return $row_match[0];
}, $row_conditions);
$loop_data[] = $row_render;
}
return implode("\n", $loop_data);
}
return $match[0];
}, $content);
}
// render attributes
$render_attribues = preg_replace_callback('/\{(\w+)(?:\.(\w+))?(\s+?(?:\w+)="[\s\S]+?")\}/', function ($match) use ($variables) {
$variable = $match[0];
$key = $match[1];
$array_key = array_key_exists(2, $match) ? $match[2] : null;
if (preg_match_all('/(\w+)="([\s\S]+?)"/', $match[3], $match_params)) {
$data = [];
foreach ($match_params[1] as $k => $value) {
$data[$value] = $match_params[2][$k];
}
foreach ($data as $date_key => $data_value) {
$attrs_exp = explode(',', $data_value);
$data[$date_key] = array_map(function ($row) {
$row_exp = explode(':', $row);
foreach ($row_exp as $kk => $value) {
$row_exp[$kk] = trim($value);
}
return $row_exp[0].'="'.$row_exp[1].'"';
}, $attrs_exp);
$data[$date_key] = trim(implode(' ', $data[$date_key]));
}
}
$value = $variable;
if (isset($array_key) && array_key_exists($key, $variables) && is_array($variables[$key]) && array_key_exists($array_key, $variables[$key])) {
$value = $variables[$key][$array_key];
} elseif (array_key_exists($key, $variables) && !is_array($variables[$key])) {
$value = $variables[$key];
}
$value = preg_replace_callback('/%(\w+)%/', function ($value_match) use ($data) {
if (array_key_exists($value_match[1], $data)) {
return $data[$value_match[1]];
}
return '';
}, $value);
return $value;
}, $content);
$render = preg_replace_callback('/\{(\w+)(?:\.(\w+))?\}/', function ($match) use ($variables) {
$variable = $match[0];
$key = $match[1];
$array_key = array_key_exists(2, $match) ? $match[2] : null;
if (isset($array_key) && array_key_exists($key, $variables) && is_array($variables[$key]) && array_key_exists($array_key, $variables[$key])) {
return $variables[$key][$array_key];
} elseif (array_key_exists($key, $variables) && !is_array($variables[$key])) {
return $variables[$key];
}
return $variable;
}, $render_attribues);
return $render;
}
public static function renderIfElse($content, $variables = [], $match_iterator = false, $tag_conditions = false)
{
$regexp = '/<!--\s+?@if\s+?(\w+)\((?:\s+)?\{(\w+)\}(?:\s+)?\)\s+?(<=|<|>=|>|==|!=)\s+?([0-9.]+|\{\w+\}|(\'|\").*\5)\s+?-->([\s\S]+?)<!--\s+?@endif\s+?-->/';
if ($tag_conditions) {
$regexp = '/condition-if=\"(?:\s+)?(\w+)\((?:\s+)?\{(\w+)\}(?:\s+)?\)(?:\s+)?(<=|<|>=|>|==|!=)(?:\s)?([0-9.]+|\{\w+\}|(\'|\").*\5)(?:\s+)?\"(.*)?condition-endif(?:=\"\")?/';
}
if ($match_iterator) {
$regexp = '/<!--\s+?@if\s+?(\w+)\((?:\s+)?\{\w+\.(\w+)\}(?:\s+)?\)\s+?(<=|<|>=|>|==|!=)\s+?([0-9.]+|\{\w+\}|(\'|\").*\5)\s+?-->([\s\S]+?)<!--\s+?@endif\s+?-->/';
if ($tag_conditions) {
$regexp = '/condition-if=\"(?:\s+)?(\w+)\((?:\s+)?\{\w+\.(\w+)\}(?:\s+)?\)(?:\s+)?(<=|<|>=|>|==|!=)(?:\s)?([0-9.]+|\{\w+\}|(\'|\").*\5)(?:\s+)?\"(.*)?condition-endif(?:=\"\")?/';
}
}
return preg_replace_callback($regexp, function ($match) use ($variables, $tag_conditions) {
$success = false;
$has_else = false;
$func_name = $match[1];
$variable_name = $match[2];
$sign = $match[3];
$compare = $match[4];
$full_condition_value = $match[6];
$if_content = '';
$else_content = '';
$first = Tools::substr($compare, 0, 1);
if (is_numeric($first)) {
$compare = (int) $compare;
} elseif ('\'' == $first || '"' == $first) {
$compare = str_replace(['\'', '"'], '', $compare);
} else {
$compare = str_replace(['{', '}'], '', $compare);
if (array_key_exists($compare, $variables)) {
$compare = $variables[$compare];
} else {
$compare = null;
}
}
$else_regex = '/<!--\s+?@else\s+?-->/';
if ($tag_conditions) {
$else_regex = '/condition-else(?:=\"\")?/';
}
if (preg_match($else_regex, $full_condition_value, $match_else)) {
$start_pos = strpos($full_condition_value, $match_else[0]);
$match_else_len = Tools::strlen($match_else[0]);
$if_content = Tools::substr($full_condition_value, 0, $start_pos);
$else_content = Tools::substr($full_condition_value, $start_pos + $match_else_len);
$has_else = true;
}
if (array_key_exists($variable_name, $variables)) {
$variable = $variables[$variable_name];
if (function_exists($func_name)) {
$result = call_user_func($func_name, $variable);
switch ($sign) {
case '<':
$success = $result < $compare;
break;
case '<=':
$success = $result <= $compare;
break;
case '>':
$success = $result > $compare;
break;
case '>=':
$success = $result >= $compare;
break;
case '==':
$success = $result == $compare;
break;
case '!=':
$success = $result != $compare;
break;
}
}
}
if ($has_else) {
if ($success) {
return $if_content;
} else {
return $else_content;
}
} else {
if ($success) {
return $full_condition_value;
} else {
return false;
}
}
return $success ? $full_condition_value : '';
}, $content);
}
public static function clearHTML($content)
{
return preg_replace_callback('/(>)([\s\S]+?)(<)/', function ($match) {
return $match[1].trim($match[2]).$match[3];
}, trim($content));
}
public static function getTitle($content)
{
if (preg_match('/<((?:\s+)?title(?:\s+)?>)([\s\S]+?)<\/\1/', $content, $match)) {
return $match[2];
}
return '';
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
require_once _NEWSLETTER_PRO_DIR_.'/libraries/htmltotext/NewsletterProHtml2Text.php';
require_once _NEWSLETTER_PRO_DIR_.'/libraries/htmltotext/NewsletterProHtml2TextException.php';
class NewsletterProHtmlToText
{
public static function convert($template)
{
return NewsletterProHtml2Text::convert($template, [
'ignore_errors' => true,
]);
}
}

View File

@@ -0,0 +1,196 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProInstall
{
public $query;
public $errors;
public $tables;
public function __construct()
{
$this->module = NewsletterPro::getInstance();
$this->query = [];
$this->errors = [];
$this->tables = [];
}
public function getErrors()
{
return $this->errors;
}
public function addError($error)
{
$this->errors[] = $error;
}
public function createTable($table_name, $sql)
{
$this->addQuery('execute', [
'table_name' => $table_name,
'sql' => $sql,
'callback' => 'createTableCallback',
]);
if (!in_array($table_name, $this->tables)) {
$this->tables[] = $table_name;
}
}
public function insert($table_name, $sql)
{
$this->addQuery('execute', [
'table_name' => $table_name,
'sql' => $sql,
'callback' => 'insertCallback',
]);
}
public function delete($table_name, $sql)
{
$this->addQuery('execute', [
'table_name' => $table_name,
'sql' => $sql,
'callback' => 'deleteCallback',
]);
}
public function update($table_name, $sql)
{
$this->addQuery('execute', [
'table_name' => $table_name,
'sql' => $sql,
'callback' => 'updateCallback',
]);
}
public function addQuery($name, $data)
{
$this->query[$name][] = $data;
}
public function getQuery($name = null)
{
if (is_null($name)) {
return $this->query;
}
if (isset($this->query[$name])) {
return $this->query[$name];
}
return false;
}
public function getTables()
{
return array_merge($this->tables, [
NewsletterProConfig::$table_name,
]);
}
public function queryExists($name)
{
return isset($this->query[$name]);
}
public function execute()
{
if (!empty($this->errors)) {
return false;
}
// create tables
if ($this->queryExists('execute')) {
$execute = $this->getQuery('execute');
foreach ($execute as $data) {
if (!call_user_func_array([$this, $data['callback']], [$data])) {
return false;
}
} // stop the exescution if some of the queries fail
}
return true;
}
public function displayQuery($display_array = true)
{
if ($this->queryExists('execute')) {
$execute = $this->getQuery('execute');
if ($display_array) {
echo '<pre>';
print_r($execute);
echo '</pre>';
} else {
echo '<pre>';
foreach ($execute as $data) {
echo $data['sql'].'<br><br>';
}
echo '</pre>';
}
}
}
public function createTableCallback($data)
{
if (!Db::getInstance()->execute($data['sql'])) {
$this->errors[] = sprintf($this->module->l('Cannot create the table "%s".'), _DB_PREFIX_.$data['table_name']);
return false;
}
return true;
}
public function insertCallback($data)
{
if (!Db::getInstance()->execute($data['sql'])) {
$this->errors[] = sprintf($this->module->l('Cannot insert the data into the table "%s".'), _DB_PREFIX_.$data['table_name']);
return false;
}
return true;
}
public function deleteCallback($data)
{
if (!Db::getInstance()->execute($data['sql'])) {
$this->errors[] = sprintf($this->module->l('Cannot delete the records from the table "%s".'), _DB_PREFIX_.$data['table_name']);
return false;
}
return true;
}
public function updateCallback($data)
{
if (!Db::getInstance()->execute($data['sql'])) {
$this->errors[] = sprintf($this->module->l('Cannot dupdate the records from the table "%s".'), _DB_PREFIX_.$data['table_name']);
return false;
}
return true;
}
}

View File

@@ -0,0 +1,125 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProInstallData
{
private $errors = [];
private $module;
private $languages;
private $languages_iso;
private $translate;
private $shops;
private $call_functions = [
'installSubscriptionTpl',
];
public function __construct()
{
$this->module = NewsletterProTools::module();
$this->translate = new NewsletterProTranslate(__CLASS__);
$this->languages = Language::getLanguages(false);
$this->languages_iso = [];
foreach ($this->languages as $lang) {
$this->languages_iso[$lang['iso_code']] = $lang;
}
$this->shops = Shop::getShops(false);
}
public static function newInstance()
{
return new self();
}
private function success()
{
return empty($this->errors);
}
public function execute(&$errors = [], $ignore = [])
{
try {
foreach ($this->call_functions as $func_name) {
if (in_array($func_name, $ignore)) {
continue;
}
if (!$this->{$func_name}()) {
break;
}
}
} catch (Exception $e) {
if (_PS_MODE_DEV_) {
$this->errors[] = $e->__toString();
} else {
$this->errors[] = $e->getMessage();
}
}
$errors = $this->errors;
return $this->success();
}
private function installSubscriptionTpl()
{
$files_dir = _NEWSLETTER_PRO_DIR_.'/install/tables/subscription_tpl/';
$files = NewsletterProTools::getDirectoryIterator($files_dir, '/^[a-zA-Z0-9_-]+$/');
$default = 'responsive_new';
$default_id = 0;
foreach ($files as $file) {
if ($file->isDir() && !$file->isDot()) {
$dirname = $file->getPathname().'/';
$basename = $file->getBasename();
$subscription_tpl = NewsletterProSubscriptionTpl::loadFile($dirname);
if ($basename === $default) {
$subscription_tpl->active = true;
}
if (!$subscription_tpl->add()) {
$this->errors[] = sprintf($this->translate->l('Unable to install the subscription templates [%s].'), $dirname);
}
if ($basename === $default) {
$default_id = (int) $subscription_tpl->id;
}
}
}
if ((int) $default_id > 0) {
NewsletterProSubscriptionTpl::setActive($default_id, Shop::CONTEXT_ALL);
$subscription_tpl = new NewsletterProSubscriptionTpl((int) $default_id);
if (Validate::isLoadedObject($subscription_tpl)) {
NewsletterProConfigurationShop::updateValue('SUBSCRIPTION_TEMPLATE', $subscription_tpl->name);
}
}
return $this->success();
}
}

View File

@@ -0,0 +1,70 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProLink
{
// TODO: change all the links to this one because on some websites the generated links are not working
public static function createUrl($controller, $params = [], $urldecode = false, $id_lang = null, $id_shop = null)
{
if (is_null($id_lang) || 0 == (int) $id_lang) {
$id_lang = (int) Context::getContext()->language->id;
}
if (is_null($id_shop)) {
$id_shop = (int) Context::getContext()->shop->id;
}
$shop = new Shop((int) $id_shop);
$rewrite = (bool) Configuration::get('PS_REWRITING_SETTINGS');
$tial = http_build_query($params);
$base_uri = __PS_BASE_URI__;
$default_shop_url = Tools::getHttpHost(true).$base_uri;
$shop_url = '';
if ((bool) Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && Validate::isLoadedObject($shop)) {
$shop_url = $shop->getBaseURL();
} else {
$shop_url = $default_shop_url;
}
$len = Tools::strlen($shop_url);
if (isset($shop_url[$len - 1])) {
$char = $shop_url[$len - 1];
if ('/' !== $char) {
$shop_url .= '/';
}
}
$language_iso = Language::isMultiLanguageActivated($id_shop) ? Language::getIsoById($id_lang).'/' : '';
if ($rewrite) {
$link = $shop_url.$language_iso.'module/'.NewsletterProTools::module()->name.'/'.(string) $controller.(Tools::strlen($tial) > 0 ? '?' : '').$tial;
} else {
$link = $shop_url.'index.php?fc=module&module='.NewsletterProTools::module()->name.'&controller='.(string) $controller.'&id_lang='.(int) $id_lang.(Tools::strlen($tial) > 0 ? '&' : '').$tial;
}
if ($urldecode) {
return urldecode($link);
}
return $link;
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
abstract class NewsletterProListManager
{
const TABLE_ALL = 0x0F;
const TABLE_CUSTOMER = 0x01;
const TABLE_NEWSLETTER = 0x02;
const TABLE_EMAIL = 0x04;
const TABLE_SUBSCRIBER = 0x08;
public static $tables = [
'emailsubscription' => [
'flag' => self::TABLE_NEWSLETTER,
'fields' => [
'email' => 'email',
'active' => 'active',
],
],
'newsletter' => [
'flag' => self::TABLE_NEWSLETTER,
'fields' => [
'email' => 'email',
'active' => 'active',
],
],
'newsletter_pro_subscribers' => [
'flag' => self::TABLE_SUBSCRIBER,
'fields' => [
'email' => 'email',
'active' => 'active',
],
],
'newsletter_pro_email' => [
'flag' => self::TABLE_EMAIL,
'fields' => [
'email' => 'email',
'active' => 'active',
],
],
'customer' => [
'flag' => self::TABLE_CUSTOMER,
'fields' => [
'email' => 'email',
'active' => 'newsletter',
],
],
];
public static function parse($callback, $flags = null)
{
if (!isset($flags)) {
$flags = self::TABLE_ALL;
}
$data = [];
foreach (self::$tables as $table_name => $info) {
if (NewsletterProTools::tableExists($table_name) && ($flags & $info['flag']) > 0) {
$data[$table_name] = $callback($table_name, [
'email' => $info['fields']['email'],
'active' => $info['fields']['active'],
]);
}
}
return $data;
}
}

View File

@@ -0,0 +1,241 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProListOfInterest extends ObjectModel
{
public $active;
public $name;
public $position;
/* defined variables */
public $errors = [];
public static $definition = [
'table' => 'newsletter_pro_list_of_interest',
'primary' => 'id_newsletter_pro_list_of_interest',
'multilang' => true,
'multilang_shop' => true,
'fields' => [
/* Lang fields */
'name' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isString', 'required' => true, 'size' => 255],
/* Shop fields */
'active' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'shop' => true],
'position' => ['type' => self::TYPE_INT, 'shop' => true],
],
];
public function __construct($id = null, $id_lang = null, $id_shop = null)
{
self::initAssoTables();
parent::__construct($id, $id_lang, $id_shop);
$this->context = Context::getContext();
$this->module = NewsletterPro::getInstance();
}
public static function initAssoTables()
{
NewsletterProTools::addTableAssociationArray(self::getAssoTables());
}
public static function isAvaliable($loi_id)
{
return (bool) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_list_of_interest`
WHERE `id_newsletter_pro_list_of_interest` = '.(int) $loi_id.'
AND `active` = 1
');
}
public static function getAssoTables()
{
return [
'newsletter_pro_list_of_interest' => ['type' => 'shop'],
// if it si liltiland multishop the fk_shop is requered, all the values will be availalbe in all the shop
'newsletter_pro_list_of_interest_lang' => ['type' => 'shop'],
];
}
public function add($autodate = true, $null_values = false)
{
try {
$position = (int) Db::getInstance()->getValue('SELECT MAX(`position`) FROM `'._DB_PREFIX_.'newsletter_pro_list_of_interest` WHERE 1');
$this->position = ++$position;
$return = parent::add($autodate, $null_values);
if (!$return) {
$this->addError($this->module->l('An error occurred when adding the record into database.'));
}
return $return;
} catch (Exception $e) {
if (_PS_MODE_DEV_) {
$this->addError($e->getMessage());
} else {
$this->addError($this->module->l('An error occurred when adding the record into database.'));
}
}
return false;
}
public function addError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return $this->errors;
}
public function hasErrors()
{
return !empty($this->errors);
}
public static function getListSql($cfg = [])
{
$context = Context::getContext();
if (!isset($cfg['id_lang'])) {
$cfg['id_lang'] = $context->language->id;
}
if (!isset($cfg['id_shop'])) {
$cfg['id_shop'] = $context->shop->id;
}
$sql = [];
$sql[] = 'SELECT i.`id_newsletter_pro_list_of_interest`, il.`name`, iss.`id_shop`, iss.`active`, iss.`position`
FROM `'._DB_PREFIX_.'newsletter_pro_list_of_interest` i
LEFT JOIN `'._DB_PREFIX_.'newsletter_pro_list_of_interest_lang` il
ON (i.`id_newsletter_pro_list_of_interest` = il.`id_newsletter_pro_list_of_interest`)
LEFT JOIN `'._DB_PREFIX_.'newsletter_pro_list_of_interest_shop` iss
ON (i.`id_newsletter_pro_list_of_interest` = iss.`id_newsletter_pro_list_of_interest`
AND il.`id_shop` = iss.`id_shop`)
WHERE il.`id_lang` = '.(int) $cfg['id_lang'].'
AND il.`id_shop` = '.(int) $cfg['id_shop'];
if (isset($cfg['and'])) {
$sql[] = $cfg['and'];
}
$sql[] = ' ORDER BY iss.`position`';
return implode(' ', $sql);
}
public static function getList($id_lang = null, $id_shop = null)
{
$id_lang = (isset($id_lang) ? $id_lang : Context::getContext()->language->id);
$id_shop = (isset($id_shop) ? $id_shop : Context::getContext()->shop->id);
$sql = self::getListSql([
'id_lang' => (int) $id_lang,
'id_shop' => (int) $id_shop,
]);
return Db::getInstance()->executeS($sql);
}
public static function getListActive($id_lang = null, $id_shop = null)
{
$id_lang = (!isset($id_lang) ? Context::getContext()->language->id : $id_lang);
$id_shop = (!isset($id_shop) ? Context::getContext()->shop->id : $id_shop);
$sql = self::getListSql([
'id_lang' => (int) $id_lang,
'id_shop' => (int) $id_shop,
'and' => ' AND iss.`active` = 1 ',
]);
return Db::getInstance()->executeS($sql);
}
public static function getListActiveCustomer($id_customer, $id_lang = null, $id_shop = null)
{
$list = self::getListActive($id_lang, $id_shop);
$customer_loi = NewsletterProCustomerListOfInterests::getInstanceByCustomerId((int) $id_customer);
if (Validate::isLoadedObject($customer_loi) && count($customer_loi->getCategories()) > 0) {
$categories = $customer_loi->getCategories();
foreach ($list as $key => $value) {
$id = $value['id_newsletter_pro_list_of_interest'];
$list[$key]['checked'] = false;
if (in_array($id, $categories)) {
$list[$key]['checked'] = true;
}
}
} else {
foreach ($list as $key => $value) {
$list[$key]['checked'] = false;
}
}
return $list;
}
public static function getListActiveSubscriber($email, $id_lang = null, $id_shop = null)
{
$list = self::getListActive($id_lang, $id_shop);
$loi = [];
$subscriber = NewsletterProSubscribers::getInstanceByEmail($email);
if (Validate::isLoadedObject($subscriber)) {
$loi = $subscriber->getListOfInterest();
}
if (count($loi) > 0) {
foreach ($list as $key => $value) {
$id = $value['id_newsletter_pro_list_of_interest'];
$list[$key]['checked'] = false;
if (in_array($id, $loi)) {
$list[$key]['checked'] = true;
}
}
} else {
foreach ($list as $key => $value) {
$list[$key]['checked'] = false;
}
}
return $list;
}
public function fillField($field_name, $values)
{
$default_lang = pqnp_config('PS_SHOP_DEFAULT');
foreach (Language::getLanguages(true) as $lang) {
$id_lang = $lang['id_lang'];
$this->{$field_name}[$id_lang] = (isset($values[$id_lang]) ? $values[$id_lang] : $values[$default_lang]);
}
}
}

View File

@@ -0,0 +1,210 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProLog
{
const MAX_FILE_SIZE = 10485760;
const ERROR_FILE = 'errors.log';
const LOG_FILE = 'info.log';
const SEND_FILE = 'send.log';
private $visible = false;
private $log = [];
public static function newInstance()
{
return new self();
}
public function show()
{
$this->visible = true;
return $this;
}
public function hide()
{
$this->visible = false;
return $this;
}
public function visible($bool)
{
$this->visible = (bool) $bool;
return $this;
}
public function add($string)
{
if ($this->visible) {
$this->log[] = $string;
}
return $this;
}
public function display($separator = '<br>')
{
return implode($separator, $this->log);
}
public function clearLog()
{
$this->log = [];
return $this;
}
public function displayFlush()
{
if ($this->visible) {
@ini_set('output_buffering', 'on');
@ini_set('zlib.output_compression', 0);
@ob_implicit_flush(true);
@ob_end_flush();
echo $this->display("\n");
$this->clearLog();
@ob_flush();
@flush();
}
}
public function writeSend()
{
if ($this->visible) {
$content = $this->display("\n");
if (!empty($this->log)) {
self::write($content, self::SEND_FILE);
}
$this->clearLog();
}
}
public static function clearSend()
{
self::clear(self::SEND_FILE);
}
public static function write($content, $filename = null, $filesize = null, $content_only = false)
{
$status = [];
if (is_array($content)) {
foreach ($content as $cont) {
$status[] = @self::writeString($cont, $filename, $filesize, $content_only);
}
} else {
$status[] = @self::writeString($content, $filename, $filesize, $content_only);
}
return !in_array(false, $status);
}
public static function writeStrip($content, $filename = null, $filesize = null)
{
return @self::write(strip_tags($content), $filename, $filesize);
}
public static function writeString($content, $filename = null, $filesize = null, $content_only = false)
{
$success = false;
if (!isset($filename)) {
$filename = self::LOG_FILE;
}
$filename = self::getLogDir().'/'.$filename;
if (!isset($filesize)) {
$filesize = self::MAX_FILE_SIZE;
}
if (filesize($filename) > $filesize) {
@file_put_contents($filename, '');
}
$handle = @fopen($filename, 'a+');
if (false !== $handle) {
if ($content_only) {
$str = '';
$str .= $content;
$str .= "\r\n";
} else {
$str = '';
if (isset($_SERVER['REMOTE_ADDR'])) {
$str .= date('Y-m-d H:i:s').' ['.$_SERVER['REMOTE_ADDR'].'] > ';
} else {
$str .= date('Y-m-d H:i:s').' > ';
}
$str .= $content;
$str .= "\r\n";
}
if (false !== @fwrite($handle, $str)) {
$success = true;
}
}
@fclose($handle);
return $success;
}
public static function clear($filename = null)
{
if (!isset($filename)) {
$filename = self::LOG_FILE;
}
$filename = self::getLogDir().'/'.$filename;
if (file_exists($filename)) {
if (false === @file_put_contents($filename, '')) {
return false;
}
}
return true;
}
public static function getLogDir()
{
return realpath(dirname(__FILE__).'/../logs');
}
public static function getLogFile($filename)
{
return self::getLogDir().'/'.$filename;
}
public static function getFiles()
{
return [
self::LOG_FILE,
self::ERROR_FILE,
self::SEND_FILE,
];
}
}

View File

@@ -0,0 +1,456 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
/* Swfit Version 5.3.1 */
require_once dirname(__FILE__).'/../libraries/swift/swift_required.php';
if ((int) pqnp_ini_config('swift_init')) {
require_once dirname(__FILE__).'/../libraries/swift/swift_init.php';
}
require_once dirname(__FILE__).'/NewsletterProTemplateDecoratorReplacements.php';
class NewsletterProMail extends NewsletterProMailSwift implements NewsletterProMailInterface
{
public $failed_recipients = [];
public $charset = 'UTF-8';
private $message;
private $template_name;
private $attachment_exists;
public function __construct($id = null)
{
parent::__construct($id);
$this->context = Context::getContext();
$this->module = NewsletterPro::getInstance();
$this->attachment_exists = false;
if ('tls' != Tools::strtolower($this->encryption) && 'ssl' != Tools::strtolower($this->encryption)) {
$this->encryption = false;
}
if ('' == trim($this->from_name)) {
$this->from_name = (string) $this->context->shop->name;
}
if ('' == trim($this->reply_to)) {
$this->reply_to = (string) $this->from_email;
}
}
public function mimeEncodeTo($to)
{
if (is_array($to)) {
foreach ($to as $address => $name) {
if (!is_int($address)) {
$to[$address] = self::mimeEncode($name);
}
}
}
return $to;
}
private function validateEmail(&$email)
{
$invalid_to_email_message = $this->module->l('The email address "%s" is not valid.');
if (is_array($email)) {
foreach ($email as $address => $name) {
if (is_int($address)) {
// in this case name is email
if (!NewsletterPro_Swift_Validate::email($name)) {
if (1 == count($email)) {
$this->addError(sprintf($invalid_to_email_message, $name));
return false;
} else {
$this->failed_recipients[] = $name;
unset($email[$address]);
}
}
} else {
if (!NewsletterPro_Swift_Validate::email($address)) {
if (1 == count($email)) {
$this->addError(sprintf($invalid_to_email_message, $address));
return false;
} else {
$this->failed_recipients[] = $address;
unset($email[$address]);
}
}
}
}
} elseif (!NewsletterPro_Swift_Validate::email($email)) {
$this->addError(sprintf($invalid_to_email_message, $email));
return false;
}
return true;
}
private function validateSubject($subject)
{
if (!Validate::isMailSubject($subject)) {
$this->addError($this->module->l('Invalid email subject.'));
return false;
}
return true;
}
public function newSwiftTransport()
{
if (self::METHOD_MAIL == $this->method) {
return NewsletterPro_Swift_MailTransport::newInstance();
} elseif (self::METHOD_SMTP == $this->method) {
return NewsletterPro_Swift_SmtpTransport::newInstance()
->setHost($this->server)
->setPort($this->port)
->setEncryption($this->getEncryption())
->setUsername($this->user)
->setPassword($this->passwd);
}
throw new Exception(NewsletterPro::getInstance()->l('Invalid mail method.'));
}
public function newSwiftMessage()
{
$message = NewsletterPro_Swift_Message::newInstance()->setCharset($this->charset)->setFrom([$this->from_email => $this->from_name])->setSender([$this->from_email => $this->from_name])->setReplyTo([$this->reply_to => $this->from_name]);
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'utf-8');
return $message;
}
public function newSwiftMailer($transport = null)
{
return NewsletterPro_Swift_Mailer::newInstance(isset($transport) ? $transport : $this->newSwiftTransport());
}
public function getSentFaildRecipients()
{
return $this->failed_recipients;
}
public function setTemplateNameForAttachment($template_name)
{
$this->template_name = $template_name;
}
/**
* Send one email
* This method accept also multiple to emails, but is not recommended.
*
* @param string $subject Email subject
* @param string $template Email html template
* @param array/string $to Email to
*
* @return bool Retrun true if the email was successfuly sent
*/
public function send($subject, $template, $to, &$failed_recipients = [])
{
$this->failed_recipients = $failed_recipients;
$num_sent = 0;
try {
if (!$this->validateSubject($subject)) {
return 0;
}
if (!$this->validateEmail($to)) {
return 0;
}
$to = $this->mimeEncodeTo($to);
$transport = $this->newSwiftTransport();
$message = $this->message = NewsletterPro_Swift_Message::newInstance()->setCharset($this->charset)->setContentType('text/html')->setFrom([$this->from_email => $this->from_name])->setSender([$this->from_email => $this->from_name])->setReplyTo([$this->reply_to => $this->from_name])->setTo($to)->setSubject($subject);
if ((int) $this->list_unsubscribe_active) {
self::setHeaderListUnsubscribe($message, self::getEmailFromTo($to), null, null, $this->list_unsubscribe_email);
}
$content = [];
$embed = new NewsletterProEmbedImages($template);
$template = $embed->getTemplate();
$attachments = NewsletterProMailAttachment::get($this->template_name);
$content[] = NewsletterPro_Swift_MimePart::newInstance($template, 'text/html');
if ((bool) pqnp_config('EMAIL_MIME_TEXT')) {
$content[] = NewsletterPro_Swift_MimePart::newInstance(NewsletterProHtmlToText::convert($template), 'text/plain');
}
$message->setChildren(array_merge($content, $embed->getImages(), $attachments));
$mailer = NewsletterPro_Swift_Mailer::newInstance($transport);
$num_sent = $mailer->send($message, $this->failed_recipients);
if (!$num_sent) {
if (self::METHOD_MAIL == $this->method) {
$this->addError(sprintf($this->module->l('Failed to send the email. The problem can be related with the %s function.'), 'php mail()'));
} else {
if (!function_exists('proc_open') && self::METHOD_SMTP == $this->method) {
$this->addError(sprintf($this->module->l('Failed to send the email. The problem is related with the %s function and is happen only if you use the SMTP method. You need to contact your hosting provider to solve the problem with that function.'), 'php proc_open'));
} else {
$this->addError($this->module->l('Failed to send the email.'));
}
}
}
} catch (NewsletterPro_Swift_RfcComplianceException $e) {
$this->addError($e->getMessage());
}
return (int) $num_sent;
}
/**
* Send the newsletter to the forwarders
* If a forwarder exists in the database, will be deleted from the forwarder list.
*
* @param array/string $from The forwarder email
*
* @return bool Retrun true if the email was successfuly sent
*/
public function sendForward($data, $type, $from, $sleep = 1)
{
$errors_status = [];
try {
if ($forwards = NewsletterProForward::getForwarders($from)) {
$email_info = self::getEmailInfo($from);
$fwd_recipients = new NewsletterProForwardRecipients();
$fwd_recipients->add([$email_info['name'] => $email_info['email']], $forwards);
$fwd_recipients->buildForwardersRecursive($email_info['email']);
$recipients = $fwd_recipients->getRecipients();
foreach ($recipients as $parent_email => $child_emails) {
$this->from_name = $fwd_recipients->getRecipientName($parent_email);
$this->from_email = $parent_email;
foreach ($child_emails as $email) {
if ($template = $this->getTemplate($email, $data, $type)) {
$template->setForwarder(true);
$template->setForwarderData([
'is_forwarder' => 1,
'forwarder_email' => $email_info['email'],
]);
$template_content = $template->getContent();
$subject = $template_content['render']['title'];
$render = $template_content['render']['full'];
if (pqnp_config('DEBUG_MODE')) {
$send = $this->send($subject, $render, $email);
} else {
$send = @$this->send($subject, $render, $email);
}
if ($send) {
$this->addSuccessFwd($email);
} else {
$errors_status[] = true;
}
sleep($sleep);
}
}
}
return empty($errors_status);
}
} catch (Exception $e) {
$this->addError($e->getMessage());
}
return !$this->hasErrors();
}
/**
* Get email info.
*
* @param array/string $email Name and Email address
*
* @return array
*/
public static function getEmailInfo($email)
{
if (is_array($email)) {
reset($email);
$from_email = key($email);
$from_name = $email[$from_email];
if (!Validate::isMailName($from_name)) {
$from_name = '';
}
} else {
$from_name = '';
$from_email = $email;
}
return [
'name' => $from_name,
'email' => $from_email,
];
}
/**
* Extract the full name and email from the user object.
*
* @param object $user The user object
*
* @return array/string User full name and email address
*/
public static function getToFromUser($user)
{
$to = $user->email;
if (Tools::strlen($user->firstname) > 0) {
$current_encode_fn = mb_detect_encoding($user->firstname, 'UTF-8, ISO-8859-1, ISO-8859-15, HTML-ENTITIES', true);
$firstname = mb_convert_encoding($user->firstname, 'UTF-8', $current_encode_fn);
$current_encode_ln = mb_detect_encoding($user->lastname, 'UTF-8, ISO-8859-1, ISO-8859-15, HTML-ENTITIES', true);
$lastname = mb_convert_encoding($user->lastname, 'UTF-8', $current_encode_ln);
$to = [$user->email => self::mimeEncode($firstname.' '.$lastname)];
}
return $to;
}
public static function mimeEncode($string, $charset = 'UTF-8', $newline = "\r\n")
{
if (function_exists('mb_encode_mimeheader')) {
return mb_encode_mimeheader($string, $charset);
}
return Mail::mimeEncode($string, $charset, $newline);
}
public static function getEmailFromTo($to)
{
if (is_array($to)) {
$kyes = array_keys($to);
$to_email = $kyes[0];
if (is_int($to_email)) {
$values = array_values($to);
$to_email = $values[0];
}
} else {
$to_email = $to;
}
return $to_email;
}
public static function setHeaderListUnsubscribe(&$message, $email, $id_lang, $id_shop = null, $mail_to = null)
{
$context = Context::getContext();
$module = NewsletterPro::getInstance();
$unsubscribe_link = urldecode($context->link->getModuleLink($module->name, 'unsubscribe', [
'email' => $email,
'u_token' => Tools::encrypt($email),
'msg' => false,
], null, $id_lang, $id_shop));
$headers = &$message->getHeaders();
$u_header = '';
if (isset($mail_to) && Tools::strlen(trim($mail_to)) > 0) {
$u_header = '<mailto:'.$mail_to.'>, <'.$unsubscribe_link.'>';
} else {
$u_header = '<'.$unsubscribe_link.'>';
}
$li_un = $headers->get('List-Unsubscribe');
if (!$li_un) {
$headers->addTextHeader('List-Unsubscribe', $u_header);
} else {
$li_un->setValue($u_header);
}
}
public function toTerminalInfo($default = false)
{
$output = [];
$data = [];
if (!$default) {
$data = [
'ID' => $this->id,
'Name' => $this->name,
];
}
$data = array_merge($data, [
'Method' => (self::METHOD_MAIL == $this->method ? 'MAIL' : 'SMTP'),
'From Name' => $this->from_name,
'From Email' => $this->from_email,
'From Reply To' => $this->reply_to,
]);
if (self::METHOD_SMTP == $this->method) {
$data = array_merge($data, [
'Domain' => $this->domain,
'Server' => $this->server,
'User' => $this->user,
'Encryption' => Tools::strtoupper($this->encryption),
'Port' => $this->port,
'List-Unsubscribe Active' => $this->list_unsubscribe_active,
'List-Unsubscribe Email' => $this->list_unsubscribe_email,
]);
}
$max_len = 0;
$keys = array_keys($data);
foreach ($keys as $key) {
if (Tools::strlen($key) > $max_len) {
$max_len = Tools::strlen($key);
}
}
foreach ($data as $key => $value) {
$diff = $max_len - Tools::strlen($key);
if ($diff < 0) {
$diff = 0;
}
$output[] = $key.': '.str_repeat(' ', $diff).$value;
}
return $output;
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailAttachment
{
public static function get($templateName)
{
$attachments = [];
if (isset($templateName)) {
$attachment = NewsletterProAttachment::newInstanceByTemplateName($templateName);
if ($attachment) {
$files = $attachment->filesPathFilename();
if (!empty($files)) {
foreach ($files as $file) {
$attach = NewsletterPro_Swift_Attachment::fromPath($file['path'])->setFilename($file['name']);
$attachments[] = $attach;
}
}
}
}
return $attachments;
}
}

View File

@@ -0,0 +1,478 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimp extends NewsletterProMailChimpApi
{
public function ping()
{
$response = $this->call('helper/ping');
if ($response) {
return $response['msg'];
}
return false;
}
public function getLists($params = [])
{
$response = $this->call('lists/list', $params);
if ($response) {
return $response['data'];
}
return false;
}
public function getListById($id)
{
$response = $this->call('lists/list', [
'filters' => [
'list_id' => $id,
],
]);
if ($this->hasErrors()) {
return false;
}
return $response['data'][0];
}
public function getListMembers($id_list, $start = 0, $limit = 100, $params = [])
{
$params['id'] = $id_list;
$params['opts'] = [
'start' => $start,
'limit' => $limit,
];
$response = $this->call('lists/members', $params);
if (!$response) {
return false;
}
return $response['data'];
}
private function buildSubscribeUsers($users)
{
$array = [];
foreach ($users as $user) {
$array[] = [
'email' => [
'email' => $user['EMAIL'],
],
'merge_vars' => $user,
];
}
return $array;
}
public function subscribe($id, $users = [], $params = [])
{
$params = array_merge($params, [
'update_existing' => true,
'members' => $users,
]);
return $this->api3->call("/lists/{$id}", $params);
}
private function buildUnsubscribeUsers($users)
{
$array = [];
foreach ($users as $user) {
$array[] = [
'email' => $user['email'],
];
}
return $array;
}
public function unsubscribe($id, $users = [], $params = [])
{
$params['id'] = $id;
if ($users) {
$params['batch'] = $this->buildUnsubscribeUsers($users);
}
// default options
$params['delete_member'] = false;
$params['send_goodbye'] = false;
$params['send_notify'] = false;
return $this->call('lists/batch-unsubscribe', $params);
}
public function deleteUsers($id, $users = [], $params = [])
{
$params['delete_member'] = true;
return $this->unsubscribe($id, $users, $params);
}
public function validateTag($tag)
{
if (!preg_match('/^[A-Z0-9_]+$/', $tag)) {
$this->addError('Invalid tag name "'.$tag.'" for creation. The tag need to have the format [A-Z0-9_].');
} elseif (Tools::strlen($tag) > 10) {
$this->addError('Invalid tag length for tag "'.$tag.'".');
}
if ($this->hasErrors()) {
return false;
}
return true;
}
public function listAddVar($id, $tag, $name, $params = [])
{
Tools::strtoupper($tag);
$params['id'] = $id;
$params['tag'] = $tag;
$params['name'] = $name;
if (!$this->validateTag($tag)) {
return false;
}
return $this->call('lists/merge-var-add', $params);
}
public function listUpdateVar($id, $tag, $name, $params = [])
{
Tools::strtoupper($tag);
$params['id'] = $id;
$params['tag'] = $tag;
$params['options']['name'] = $name;
if (!$this->validateTag($tag)) {
return false;
}
return $this->call('lists/merge-var-update', $params);
}
public function listSetVar($id, $tag, $value, $params = [])
{
Tools::strtoupper($tag);
$params['id'] = $id;
$params['tag'] = $tag;
$params['value'] = $value;
if (!$this->validateTag($tag)) {
return false;
}
return $this->call('lists/merge-var-set', $params);
}
public function listResetVar($id, $tag, $params = [])
{
Tools::strtoupper($tag);
$params['id'] = $id;
$params['tag'] = $tag;
if (!$this->validateTag($tag)) {
return false;
}
return $this->call('lists/merge-var-reset', $params);
}
public function listDeleteVar($id, $tag, $params = [])
{
$params['id'] = $id;
$params['tag'] = $tag;
return $this->call('lists/merge-var-del', $params);
}
public function listDeleteVars($id)
{
$errors = [];
$vars = $this->listGetVars($id);
$tags_name = self::grep($vars['merge_vars'], 'tag');
$search = array_search('EMAIL', $tags_name);
if (false !== $search) {
unset($tags_name[$search]);
}
foreach ($tags_name as $tag) {
$res = $this->listDeleteVar($id, $tag);
if (!$res) {
$this->mergeErrors($errors);
}
}
if (empty($errors)) {
return true;
}
return false;
}
public function listGetVars($id, $params = [])
{
$params['id'] = [$id];
$response = $this->call('lists/merge-vars', $params);
if ($this->hasErrors()) {
return false;
}
return $response['data'][0];
}
public function listAddGroup($id, $name, $grouping_id = null, $params = [])
{
$params['id'] = $id;
$params['group_name'] = $name;
if (isset($grouping_id)) {
$params['grouping_id'] = $grouping_id;
}
return $this->call('lists/interest-group-add', $params);
}
public function listUpdateGroup($id, $old_name, $new_name, $grouping_id = null, $params = [])
{
$params['id'] = $id;
$params['old_name'] = $old_name;
$params['new_name'] = $new_name;
if (isset($grouping_id)) {
$params['grouping_id'] = $grouping_id;
}
return $this->call('lists/interest-group-update', $params);
}
public function listDeleteGroup($id_list, $name, $grouping_id = null, $params = [])
{
$params['id'] = $id_list;
$params['group_name'] = $name;
if (isset($grouping_id)) {
$params['grouping_id'] = $grouping_id;
}
return $this->call('lists/interest-group-del', $params);
}
public function listAddGrouping($id, $name, $type = 'checkboxes', $groups = [], $params = [])
{
$params['id'] = $id;
$params['name'] = $name;
$params['type'] = $type;
$params['groups'] = $groups;
$response = $this->call('lists/interest-grouping-add', $params);
if ($this->hasErrors()) {
return false;
}
return $response['id'];
}
public function listDeleteGrouping($grouping_id, $params = [])
{
$params['grouping_id'] = $grouping_id;
$response = $this->call('lists/interest-grouping-del', $params);
if ($this->hasErrors()) {
return false;
}
return $response['complete'];
}
public function listUpdateGroupingName($grouping_id, $value, $params = [])
{
$params['grouping_id'] = $grouping_id;
$params['name'] = 'name';
$params['value'] = $value;
$this->call('lists/interest-grouping-update', $params);
if ($this->hasErrors()) {
return false;
}
return true;
}
public function listGetGroupings($id_list, $params = [])
{
$params['id'] = $id_list;
return $this->call('lists/interest-groupings', $params);
}
public function listGroupGetInterest($idList, $interestCategoryId, $params = [])
{
$response = $this->api3->call("/lists/{$idList}/interest-categories/{$interestCategoryId}/interests", [], 'GET');
if (!$response->success()) {
$this->mergeErrors($response->getErrors(true));
return false;
}
$interests = array_map(function ($item) {
return [
'id' => $item['id'],
'name' => $item['name'],
];
}, $response->getContent('interests'));
return [
$interestCategoryId => $interests,
];
}
public function listUpdateMember($id_list, $user = [], $params = [])
{
$params['id'] = $id_list;
$params['email'] = [
'email' => $user['EMAIL'],
];
$params['merge_vars'] = $user;
$params['replace_interests'] = true;
return $this->call('lists/update-member', $params);
}
public function getAccountDetails($params = [])
{
return $this->call('helper/account-details', $params);
}
public function getTemplates($types = null, $filters = null, $params = [])
{
if (isset($types)) {
$params['types'] = $types;
} else {
$params['types']['user'] = true;
$params['types']['gallery'] = true;
$params['types']['base'] = true;
}
if (isset($filters)) {
$params['filters'] = $filters;
}
return $this->call('templates/list', $params);
}
public function getTemplateContent($template_id, $type = null, $params = [])
{
$params['template_id'] = $template_id;
if (isset($type)) {
$params['type'] = $type;
}
return $this->call('templates/info', $params);
}
public function templateAdd($name, $html, $folder_id = null, $params = [])
{
$params['name'] = $name;
$params['html'] = $html;
if (isset($folder_id)) {
$params['folder_id'] = $folder_id;
}
return $this->call('templates/add', $params);
}
public function templateUpdate($template_id, $name, $html, $folder_id = null, $params = [])
{
$params['template_id'] = $template_id;
$params['values']['name'] = $name;
$params['values']['html'] = $html;
if (isset($folder_id)) {
$params['values']['folder_id'] = $folder_id;
}
return $this->call('templates/update', $params);
}
public function templateUndel($template_id, $params = [])
{
$params['template_id'] = $template_id;
return $this->call('templates/undel', $params);
}
public function orderAdd($order, $params = [])
{
$params['order'] = $order;
return $this->call('ecomm/order-add', $params);
}
public function orderDelete($store_id, $order_id, $params = [])
{
$params['store_id'] = $store_id;
$params['order_id'] = $order_id;
return $this->call('ecomm/order-del', $params);
}
public function getOrders($cid = null, $start = null, $limit = null, $since = null, $params = [])
{
if (isset($cid)) {
$params['cid'] = (string) $cid;
}
if (isset($start)) {
$params['start'] = (int) $start;
}
if (isset($limit)) {
$params['limit'] = (int) $limit;
}
if (isset($since)) {
$params['since'] = (string) $since;
}
return $this->call('ecomm/orders', $params);
}
}

View File

@@ -0,0 +1,282 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpApi
{
public $key;
public $url;
public $url_defined = 'https://<dc>.api.mailchimp.com/2.0/';
public $verify_ssl = false;
public $errors = [];
public $module;
/**
* @var NewsletterProMailChimpApi3
*/
protected $api3 = null;
public function __construct($key, $url_defined = null)
{
$this->module = NewsletterPro::getInstance();
if (isset($url_defined)) {
$this->url_defined = $url_defined;
}
$this->api3 = new NewsletterProMailChimpApi3($key);
$this->key = $key;
$this->url = $this->createUrl($key);
}
protected function updateApiKey($key)
{
$this->api3 = new NewsletterProMailChimpApi3($key);
$this->key = $key;
$this->url = $this->createUrl($key);
}
private function createUrl($key)
{
$exp = explode('-', $key);
if (count($exp) > 1) {
list(, $dc) = explode('-', $key);
} else {
$dc = '';
}
return str_replace('<dc>', $dc, $this->url_defined);
}
public function clearErrors()
{
$this->errors = [];
}
public function call($method, $params = [])
{
$this->clearErrors();
$content = $this->request($method, $params);
if (false === $content) {
return false;
}
if ($this->hasErrors()) {
return false;
}
$content = Tools::jsonDecode($content['content'], true);
if (empty($content)) {
$this->addError('MailChimp response is empty.');
return false;
} elseif (isset($content['status']) && 'error' == $content['status']) {
$this->addError($content['error']);
return false;
}
if (isset($content['errors']) && !empty($content['errors'])) {
$this->addResponseErrors($content['errors']);
}
return $content;
}
public function request($method, $params = [])
{
if (function_exists('curl_init')) {
$params['apikey'] = $this->key;
$url = $this->url.$method.'.json';
$options = [
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_USERAGENT => 'PHP-MCAPI/2.0',
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => Tools::jsonEncode($params),
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => $this->verify_ssl,
];
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch);
$info = curl_getinfo($ch);
$info['errno'] = $err;
$info['errmsg'] = $errmsg;
$info['content'] = $content;
if (200 != (int) $info['http_code']) {
$response = Tools::jsonDecode($content, true);
if (isset($response['status']) && 'error' == $response['status']) {
$this->addError($response['error']);
} else {
$this->addError('The HTTP response code is not 200.');
}
}
return $info;
} else {
$this->addError(sprintf($this->module->l('The availability of php %s library is not available on your server. You can talk with the hosting provider to enable it.'), 'curl'));
}
return false;
}
public function addError($error, $code = null)
{
$add_error = [
'code' => $code,
'error' => $error,
// this causes problems if an error occurred when synchronizing the lists
// 'error' => Tools::displayError($error),
];
$this->errors[] = $add_error;
}
public function hasErrors()
{
return !empty($this->errors);
}
public function getErrors($only_errors = false, $collapse_same_code = false)
{
$errors = $this->errors;
if ($collapse_same_code) {
$errors_collapse = [];
$errors_coldes = [];
foreach ($errors as $error) {
if (!in_array($error['code'], $errors_coldes)) {
$errors_collapse[] = $error;
$errors_coldes[] = $error['code'];
}
}
$errors = $errors_collapse;
}
$return_errors = [];
if ($only_errors) {
foreach ($errors as $error) {
if (is_array($error) && isset($error['error'])) {
$return_errors[] = $error['error'];
} else {
$return_errors[] = $error;
}
}
} else {
$return_errors = $errors;
}
return $return_errors;
}
public function addResponseErrors($errors)
{
foreach ($errors as $error) {
$this->addError($error['error'], $error['code']);
}
}
public function addParams(&$params, $data)
{
foreach ($data as $key => $item) {
$this->addParam($params, $key, $item);
}
}
public function addParam(&$params, $key, $name)
{
$params[$key] = $name;
}
public function mergeErrors(&$errors)
{
$errors = array_merge($errors, $this->getErrors(true));
}
public static function grep($array, $name)
{
$return_array = [];
foreach ($array as $value) {
if (isset($value[$name])) {
$return_array[] = $value[$name];
}
}
return $return_array;
}
public static function makeDate($date, $format = 'm/d/Y')
{
return date($format, strtotime($date));
}
public static function formatPhone($phone)
{
$phone = explode(' ', trim(preg_replace('/[()\s.-]+/', ' ', $phone)));
$result = '';
$len = count($phone);
$i = 0;
foreach ($phone as $value) {
$result .= $value;
if (($i >= $len - 3) && ($i < $len - 1)) {
$result .= '-';
} else {
$result .= ' ';
}
++$i;
}
return $result;
}
public static function searchFind($respose)
{
if (false === $respose) {
return false;
}
return true;
}
public static function arrayMerge(&$array1, $array2)
{
foreach ($array2 as $key => $value) {
$array1[$key] = $value;
}
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpApi3
{
public $key;
public $url = 'https://<dc>.api.mailchimp.com/3.0';
public $verify_ssl = false;
// private $module;
public function __construct($key, $url = null)
{
// $this->module = pqnp_module();
if (isset($url)) {
$this->url = $url;
}
$this->key = $key;
$exp = explode('-', $this->key);
if (count($exp) > 1) {
list(, $dc) = explode('-', $this->key);
} else {
$dc = '';
}
$this->url = str_replace('<dc>', $dc, $this->url);
}
public function call($action, $params = [], $method = 'POST')
{
return $this->request($action, $params, $method);
}
public function callError($error, $method = 'POST')
{
return $this->request('', [
'CURLOPT_HTTPHEADER' => ['X-Trigger-Error: '.$error],
], $method);
}
public function request($action, $params = [], $method = 'POST')
{
if (!function_exists('curl_init')) {
throw new Exception(sprintf(pqnp_module()->l('The availability of php %s library is not available on your server. You can talk with the hosting provider to enable it.'), 'curl'));
}
$url = $this->url.'/'.$action;
$httpHeader = [
'Content-Type: application/json',
'Authorization: apikey '.$this->key,
];
if (array_key_exists('CURLOPT_HTTPHEADER', $params)) {
$httpHeader = array_merge($httpHeader, $params['CURLOPT_HTTPHEADER']);
}
$options = [
CURLOPT_HTTPHEADER => $httpHeader,
CURLOPT_USERAGENT => 'PHP-MCAPI/3.0',
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => Tools::jsonEncode($params),
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => $this->verify_ssl,
];
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
$info = curl_getinfo($ch);
$info = array_merge($info, [
'errno' => $errno,
'errmsg' => $errmsg,
'content' => $content,
]);
return new NewsletterProMailChimpResponse($info);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,299 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpFields
{
public $errors = [];
public $data = [];
public $context;
public $list_vars;
public static $fields = [];
public function __construct($list_vars)
{
$this->context = Context::getContext();
$this->list_vars = $list_vars;
$this->defineData();
$this->defineFields();
}
public function defineFields()
{
$this->addField('FNAME', [
'name' => 'First Name',
'options' => [
'field_type' => 'text',
'req' => false,
],
]);
$this->addField('LNAME', [
'name' => 'Last Name',
'options' => [
'field_type' => 'text',
'req' => false,
],
]);
$this->addField('SHOP', [
'name' => 'Shop',
'options' => [
'field_type' => 'dropdown',
'default_value' => $this->getData('default_shop_name'),
'choices' => ($this->getData('shops') ? $this->getData('shops_name') : $this->getData('default_shop_name')),
'req' => false,
],
]);
$this->addField('SUBSCRIBED', [
'name' => 'Subscribed',
'options' => [
'field_type' => 'dropdown',
'default_value' => 'yes',
'choices' => ['yes', 'no'],
'req' => false,
],
]);
$this->addField('USER_TYPE', [
'name' => 'User Type',
'options' => [
'field_type' => 'dropdown',
'default_value' => 'Added',
'choices' => ['Customer', 'Visitor', 'Added'],
'req' => false,
],
]);
$this->addField('LANGUAGE', [
'name' => 'Language',
'options' => [
'field_type' => 'text',
'default_value' => $this->getData('default_language_name'),
'req' => false,
],
]);
$this->addField('LAST_ORDER', [
'name' => 'Last Order',
'options' => [
'field_type' => 'date',
'dateformat' => 'MM/DD/YYYY',
'req' => false,
],
]);
$this->addField('OPTIN_IP', [
'name' => 'Ip',
'options' => [
'field_type' => 'text',
'req' => false,
],
]);
$this->addField('BIRTHDAY', [
'name' => 'Birthday',
'options' => [
'field_type' => 'birthday',
'dateformat' => 'MM/DD',
'req' => false,
],
]);
$this->addField('ADDRESS', [
'name' => 'Address',
'options' => [
'field_type' => 'address',
'req' => false,
],
]);
$this->addField('COMPANY', [
'name' => 'Company',
'options' => [
'field_type' => 'text',
'req' => false,
],
]);
$this->addField('DATE_ADD', [
'name' => 'Registration Date',
'options' => [
'field_type' => 'date',
'dateformat' => 'MM/DD/YYYY',
'req' => false,
],
]);
$this->addField('PHONE', [
'name' => 'Phone',
'options' => [
'field_type' => 'phone',
'req' => false,
],
]);
$this->addField('PHONE_MOB', [
'name' => 'Phone Mobile',
'options' => [
'field_type' => 'phone',
'req' => false,
],
]);
}
public function addField($name, $field)
{
self::$fields[$name] = $field;
}
public function defineData()
{
$id_lang_default = (int) Configuration::get('PS_LANG_DEFAULT');
$this->addData('id_lang_default', $id_lang_default);
$this->addData('locale_country', Tools::strtoupper(Configuration::get('PS_LOCALE_COUNTRY')));
$this->addData('id_shop_default', (int) Configuration::get('PS_SHOP_DEFAULT'));
$groups = Group::getGroups($id_lang_default);
$this->addData('groups', $groups);
$this->addData('groups_name', self::grep($groups, 'name'));
$shops = Shop::getShops(false);
$this->addData('shops', $shops);
$this->addData('shops_name', self::grep($shops, 'name'));
$this->addData('default_shop_name', Configuration::get('PS_SHOP_NAME'));
$default_language = Language::getLanguage($id_lang_default);
$this->addData('default_language', $default_language);
$this->addData('default_language_name', $default_language['name']);
$languages = Language::getLanguages(false);
$this->addData('languages', $languages);
$this->addData('languages_name', self::grep($languages, 'name'));
}
public function getData($name)
{
if (isset($this->data[$name])) {
return $this->data[$name];
}
return false;
}
public function addData($name, $data)
{
$this->data[$name] = $data;
}
public function getSyncVars()
{
$save_tags = [];
$fields = $this->getFields();
$vars_tags = self::grep($this->list_vars, 'tag');
foreach ($fields as $tag => $value) {
if (in_array($tag, $vars_tags)) {
$save_tags['update'][$tag] = $value;
} else {
$save_tags['add'][$tag] = $value;
}
}
return $save_tags;
}
public function getRestVars()
{
$fields = $this->getFields();
$vars_tags = self::grep($this->list_vars, 'tag');
$vars_tags_rest = array_diff($vars_tags, array_keys($fields));
$searched_key = array_search('EMAIL', $vars_tags_rest);
if (false !== $searched_key) {
unset($vars_tags_rest[$searched_key]);
}
return $vars_tags_rest;
}
public static function grep($array, $name)
{
$return_array = [];
foreach ($array as $value) {
if (isset($value[$name])) {
$return_array[] = $value[$name];
}
}
return $return_array;
}
public function getFields()
{
return self::$fields;
}
public function addError($error, $code = null)
{
$add_error = [
'code' => $code,
'error' => Tools::displayError($error),
];
$this->errors[] = $add_error;
}
public function hasErrors()
{
return !empty($this->errors);
}
public function getErrors($only_errors = false, $collapse_same_code = false)
{
$errors = $this->errors;
if ($collapse_same_code) {
$errors_collapse = [];
$errors_coldes = [];
foreach ($errors as $error) {
if (!in_array($error['code'], $errors_coldes)) {
$errors_collapse[] = $error;
$errors_coldes[] = $error['code'];
}
}
$errors = $errors_collapse;
}
$return_errors = [];
if ($only_errors) {
foreach ($errors as $error) {
$return_errors[] = $error['error'];
}
} else {
$return_errors = $this->errors;
}
return $return_errors;
}
}

View File

@@ -0,0 +1,287 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpOrder
{
/**
* the Order Id.
*
* @var string
*/
private $id;
/**
* NOT IN USE
* optional the Campaign Id to track this order against (see the "mc_cid" query string variable a campaign passes).
*
* @var string
*/
private $campaign_id;
/**
* NOT IS USE
* optional (kind of) the Email Id of the subscriber we should attach this order to (see the "mc_eid" query string variable a campaign passes) - required if campaign_id is passed, otherwise either this or email is required. If both are provided, email_id takes precedence.
*
* @var string
*/
private $email_id;
/**
* optional (kind of) the Email Address we should attach this order to - either this or email_id is required. If both are provided, email_id takes precedence.
*
* @var string
*/
private $email;
/**
* The Order Total (ie, the full amount the customer ends up paying).
*
* @var float
*/
private $total;
/**
* optional the date of the order - if this is not provided, we will default the date to now. Should be in the format of 2012-12-30.
*
* @var string
*/
private $order_date;
/**
* optional the total paid for Shipping Fees.
*
* @var float
*/
private $shipping;
/**
* optional the total tax paid.
*
* @var float
*/
private $tax;
/**
* a unique id for the store sending the order in (32 bytes max).
*
* @var string
*/
private $store_id;
/**
* optional a "nice" name for the store - typically the base web address (ie, "store.mailchimp.com"). We will automatically update this if it changes (based on store_id).
*
* @var string
*/
private $store_name;
/**
* structs for each individual line item including.
*
* @var array
*/
private $items = [];
private $db_cache = [];
public function __construct($id_order, $id_currency = null)
{
$order = new Order($id_order);
$id_currency = $to_currency = (isset($id_currency) ? $id_currency : pqnp_config('PS_CURRENCY_DEFAULT'));
$from_currency = $order->id_currency;
$tax_excl = PS_TAX_EXC == $order->getTaxCalculationMethod();
$customer = new Customer($order->id_customer);
$shop = new Shop($order->id_shop);
$line_num = 0;
foreach ($order->getProducts() as $product) {
$id_category_default = $product['id_category_default'];
if ($tax_excl) {
$cost = $product['unit_price_tax_excl'];
} else {
$cost = $product['unit_price_tax_incl'];
}
$item = [
'line_num' => ++$line_num,
'product_id' => (int) $product['product_id'],
'sku' => (string) $product['product_reference'],
'product_name' => (string) $product['product_name'],
'category_id' => (int) $id_category_default,
'category_name' => $this->getCategoryName($id_category_default, $order->id_lang),
'qty' => (float) $product['product_quantity'],
'cost' => (float) $cost,
];
$this->addItem($item);
}
if ($tax_excl) {
$total = $order->total_paid_tax_excl;
$shipping = $order->total_shipping_tax_excl;
} else {
$total = $order->total_paid_tax_incl;
$shipping = $order->total_shipping_tax_incl;
}
$tax = $order->total_paid_tax_incl - $order->total_paid_tax_excl;
$this->setId($order->id);
$this->setEmail($customer->email);
$this->setTotal($total, $from_currency, $to_currency);
$this->setOrderDate($order->date_add);
$this->setShipping($shipping, $from_currency, $to_currency);
$this->setTax($tax, $from_currency, $to_currency);
$this->setStoreId($shop->id);
$this->setStoreName($shop->name);
}
public static function newInstance($id_order, $id_currency = null)
{
return new self($id_order, $id_currency);
}
public static function getOrdersIdSinceDate($date)
{
$db_orders = Db::getInstance()->executeS('
SELECT `id_order`, `date_add`
FROM `'._DB_PREFIX_.'orders`
WHERE `date_add` > "'.pSQL($date).'"
');
return $db_orders;
}
public function toArray()
{
$order = [
'id' => $this->id,
'email' => $this->email,
'total' => $this->total,
'order_date' => $this->order_date,
'shipping' => $this->shipping,
'tax' => $this->tax,
'store_id' => $this->store_id,
'store_name' => $this->store_name,
'items' => $this->getValidItems(),
];
return $order;
}
private function getCategoryName($id_category, $id_lang = null)
{
$id_lang = (isset($id_lang) ? $id_lang : pqnp_config('PS_LANG_DEFAULT'));
$sql = trim('
SELECT `name` FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl
ON (c.`id_category` = cl.`id_category`)
WHERE c.`id_category` = '.(int) $id_category.'
AND cl.`id_lang` = '.(int) $id_lang.'
');
if (isset($this->db_cache[$sql])) {
return $this->db_cache[$sql];
}
$name = trim(Db::getInstance()->getValue($sql));
$this->db_cache[$sql] = (empty($name) ? 'Unknown' : $name);
return $this->db_cache[$sql];
}
public function setId($value)
{
$this->id = (int) $value;
return $this;
}
public function setEmail($value)
{
$this->email = (string) $value;
return $this;
}
public function setTotal($value, $from_currency = null, $to_currency = null)
{
$this->total = (float) Tools::convertPrice($value, $from_currency, $to_currency);
return $this;
}
public function setOrderDate($value)
{
$this->order_date = (string) $value;
return $this;
}
public function setShipping($value, $from_currency = null, $to_currency = null)
{
$this->shipping = (float) Tools::convertPrice($value, $from_currency, $to_currency);
return $this;
}
public function setTax($value, $from_currency, $to_currency)
{
$this->tax = (float) (float) Tools::convertPrice($value, $from_currency, $to_currency);
return $this;
}
public function setStoreId($value)
{
$this->store_id = (string) $value;
return $this;
}
public function setStoreName($value)
{
$this->store_name = (string) $value;
return $this;
}
public function addItem($value)
{
$this->items[] = $value;
return $this;
}
public function getValidItems()
{
$items = [];
foreach ($this->items as $item) {
if ((int) $item['product_id'] && (int) $item['category_id']) {
$items[] = $item;
}
}
return $items;
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpResponse
{
private $info;
private $content;
private $http_code;
public function __construct(array $info)
{
$this->info = $info;
$this->http_code = (int) $this->info['http_code'];
$this->content = Tools::jsonDecode($info['content'], true);
if (!isset($this->content) && 204 !== $this->http_code) {
throw new Exception('Invalid Response.');
}
}
public function getContent($key = null)
{
if (isset($key)) {
return $this->content[$key];
}
return $this->content;
}
public function success()
{
return 200 === $this->http_code || 204 === $this->http_code;
}
public function getErrors($simple = false)
{
$detail = '';
$errors = [];
if (!$this->success()) {
$detail = '['.$this->content['status'].'] '.$this->content['title'].': '.$this->content['detail'];
if (array_key_exists('errors', $this->content)) {
$errors = $this->content['errors'];
}
}
switch ($this->http_code) {
case 400:
break;
case 401:
break;
case 403:
break;
case 404:
break;
case 405:
break;
case 414:
break;
case 422:
break;
case 429:
break;
case 500:
break;
case 503:
break;
}
if ($simple) {
return array_map(function ($error) {
return $error['detail'];
}, $errors);
}
return [
'http_code' => $this->http_code,
'detail' => $detail,
'errors' => $errors,
];
}
}

View File

@@ -0,0 +1,141 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpToken extends ObjectModel
{
public $token;
public $creation_date;
public $modified_date;
public $expiration_date;
public static $token_static;
public static $definition = [
'table' => 'newsletter_pro_mailchimp_token',
'primary' => 'id_newsletter_pro_mailchimp_token',
'fields' => [
'token' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true],
'creation_date' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'modified_date' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'expiration_date' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
],
];
public function __construct($id = null)
{
parent::__construct($id);
}
public static function newInstance($id = null)
{
return new self($id);
}
public static function getInstanceByToken($token)
{
$id = (int) Db::getInstance()->getValue('
SELECT `id_newsletter_pro_mailchimp_token`
FROM `'._DB_PREFIX_.'newsletter_pro_mailchimp_token`
WHERE `token` = "'.pSQL($token).'"
');
$instance = self::newInstance($id);
if (Validate::isLoadedObject($instance)) {
return $instance;
}
return false;
}
public static function generateToken()
{
return Tools::encrypt(uniqid() + time());
}
public static function generateDayToken()
{
return Tools::encrypt('mailchimp'.date('Y-m-d'));
}
public static function generateHourToken()
{
return Tools::encrypt('mailchimp'.date('Y-m-d H'));
}
public static function generateMinuteToken()
{
return Tools::encrypt('mailchimp'.date('Y-m-d H:i'));
}
public static function getToken()
{
if (!isset(self::$token_static)) {
self::$token_static = self::generateToken();
}
return self::$token_static;
}
public function add($auto_date = true, $null_values = false)
{
$this->updateDates();
return parent::add($auto_date, $null_values);
}
public function update($null_values = false)
{
$this->updateDates();
return parent::update($null_values);
}
private function updateDates()
{
if (isset($this->creation_date) || !$this->creation_date) {
$this->creation_date = date('Y-m-d H:i:s');
}
$this->modified_date = date('Y-m-d H:i:s');
$this->expiration_date = date('Y-m-d H:i:s', strtotime('+1 month'));
}
public function expired()
{
return strtotime($this->expiration_date) < time();
}
public static function validateToken($token_var = 'mc_token')
{
if (Tools::isSubmit($token_var)) {
$mc_token = NewsletterProMailChimpToken::getInstanceByToken(Tools::getValue($token_var));
if ($mc_token) {
if ($mc_token->expired()) {
$mc_token->delete();
} else {
return true;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,206 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpUserImport
{
public $email;
public $firstname;
public $lastname;
public $subscribed;
public $id_lang;
public $id_shop;
public $date_add;
public $ip;
public $birthday;
public $user_type;
public $user_object;
private $languages_iso = [];
private $shops_name = [];
public function __construct($email)
{
$this->email = $email;
$this->user_object = $this->getUserObject();
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
$this->languages_iso[$lang['iso_code']] = (int) $lang['id_lang'];
}
$shops = Shop::getShops(false);
foreach ($shops as $shop) {
$this->shops_name[Tools::strtolower($shop['name'])] = (int) $shop['id_shop'];
}
}
public static function newInstance($email)
{
return new self($email);
}
public function userExists()
{
return Validate::isLoadedObject($this->user_object);
}
public function set($chimp_data)
{
$this->email = $chimp_data['email'];
$this->firstname = $chimp_data['merges']['FNAME'];
$this->lastname = $chimp_data['merges']['LNAME'];
$this->subscribed = 'yes' == $chimp_data['merges']['SUBSCRIBED'] ? true : false;
$iso_code = Tools::strtolower($chimp_data['language']);
if (array_key_exists($iso_code, $this->languages_iso)) {
$this->id_lang = $this->languages_iso[$iso_code];
} else {
$this->id_lang = (int) pqnp_config('PS_LANG_DEFAULT');
}
$shop_name = Tools::strtolower($chimp_data['merges']['SHOP']);
if (array_key_exists($shop_name, $this->shops_name)) {
$this->id_shop = $this->shops_name[$shop_name];
} else {
$this->id_shop = (int) pqnp_config('PS_SHOP_DEFAULT');
}
$this->date_add = date('Y-m-d', strtotime($chimp_data['merges']['DATE_ADD']));
$this->ip = $chimp_data['ip_opt'];
$this->birthday = $chimp_data['merges']['birthday'];
$this->user_type = $chimp_data['merges']['USER_TYPE'];
// setup the user object
$this->user_object->email = $this->email;
if ($this->user_object instanceof Customer) {
$this->user_object->firstname = $this->firstname;
$this->user_object->lastname = $this->lastname;
$this->user_object->newsletter = $this->subscribed;
$this->user_object->id_lang = $this->id_lang;
$this->user_object->id_shop = $this->id_shop;
if (!Validate::isLoadedObject($this->user_object)) {
$this->user_object->date_add = $this->date_add;
}
$this->user_object->ip_registration_newsletter = $this->ip;
} elseif ($this->user_object instanceof NewsletterProSubscribers || $this->user_object instanceof NewsletterProEmail) {
$this->user_object->firstname = $this->firstname;
$this->user_object->lastname = $this->lastname;
$this->user_object->active = $this->subscribed;
$this->user_object->id_lang = $this->id_lang;
$this->user_object->id_shop = $this->id_shop;
if (!Validate::isLoadedObject($this->user_object)) {
$this->user_object->date_add = $this->date_add;
}
$this->user_object->ip_registration_newsletter = $this->ip;
} elseif ($this->user_object instanceof NewsletterProBlockNewsletter) {
$this->user_object->active = $this->subscribed;
$this->user_object->id_shop = $this->id_shop;
if (!Validate::isLoadedObject($this->user_object)) {
$this->user_object->newsletter_date_add = $this->date_add;
}
$this->user_object->ip_registration_newsletter = $this->ip;
} else {
throw new Exception(NewsletterPro::getInstance()->l('Invalid user_object type.'));
}
return $this;
}
public function save()
{
if (!isset($this->user_object)) {
throw new Exception(NewsletterPro::getInstance()->l('The user_object is not set.'));
}
return $this->user_object->save();
}
private function getUserObject()
{
$tables = [];
$tables_id = [];
$tables['customer'] = 'id_customer';
if (NewsletterProTools::blockNewsletterExists()) {
$tables['newsletter'] = 'id';
}
$tables['newsletter_pro_email'] = 'id_newsletter_pro_email';
$tables['newsletter_pro_subscribers'] = 'id_newsletter_pro_subscribers';
foreach ($tables as $table_name => $table_id) {
$id = (int) Db::getInstance()->getValue('
SELECT `'.pSQL($table_id).'`
FROM `'._DB_PREFIX_.pSQL($table_name).'`
WHERE `email` = "'.pSQL($this->email).'"
');
if ($id) {
$tables_id[$table_name] = $id;
}
}
$user_object = null;
if (isset($tables_id['customer'])) {
$user_object = new Customer((int) $tables_id['customer']);
} elseif (isset($tables_id['newsletter_pro_subscribers']) && pqnp_config('SUBSCRIPTION_ACTIVE')) {
$user_object = NewsletterProSubscribers::newInstance((int) $tables_id['newsletter_pro_subscribers']);
} elseif (isset($tables_id['newsletter']) && NewsletterProTools::blockNewsletterExists() && !pqnp_config('SUBSCRIPTION_ACTIVE')) {
$user_object = NewsletterProBlockNewsletter::newInstance((int) $tables_id['newsletter']);
} elseif (isset($tables_id['newsletter_pro_email'])) {
$user_object = NewsletterProEmail::newInstance((int) $tables_id['newsletter_pro_email']);
} else {
// if the email does not exists in database
if (pqnp_config('SUBSCRIPTION_ACTIVE')) {
$user_object = NewsletterProSubscribers::newInstance();
} elseif (NewsletterProTools::blockNewsletterExists()) {
$user_object = NewsletterProBlockNewsletter::newInstance();
} else {
$user_object = NewsletterProEmail::newInstance();
}
}
return $user_object;
}
}

View File

@@ -0,0 +1,403 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpUsers
{
public $user = null;
public $users = [];
public $errors = [];
public $input_user;
const ERROR_EMAIL_NOT_SET = 101;
const USER_TYPE_CUSTOMER = 'Customer';
const USER_TYPE_VISITOR = 'Visitor';
const USER_TYPE_ADDED = 'Added';
const EMAIL_TYPE_HTML = 'html';
const EMAIL_TYPE_TEXT = 'text';
const STATUS_SUBSCRIBED = 'subscribed';
const STATUS_UNSUBSCRIBED = 'unsubscribed';
const STATUS_CLEANED = 'cleaned';
const STATUS_PENDING = 'pending';
public function addUserVar($name, $value)
{
$this->user['merge_fields'][$name] = $value;
}
public function inputUserGet($name)
{
if (isset($this->input_user[$name])) {
return $this->input_user[$name];
}
return false;
}
public function inputUserExists($name)
{
if (isset($this->input_user[$name])) {
return true;
}
return false;
}
public function addUser($input_user = [])
{
$this->input_user = $input_user;
// Subscriber's current status. Possible values: "subscribed", "unsubscribed", "cleaned", or "pending".
$this->user = [
// 'email_address' => '', // OK
'email_type' => self::EMAIL_TYPE_HTML,
// 'status' => 'subscribed', // OK
'merge_fields' => [],
// FIXME: this causes problems if it's an empty array
'interests' => [],
// 'language' => 'en', // OK
// 'ip_signup' => '',
// 'timestamp_signup' => '',
// 'ip_opt' => '', // OK
// 'timestamp_opt' => '',
];
if ($this->inputUserExists('email')) {
$this->setEmail($this->inputUserGet('email'));
} else {
$this->addError('The field email is not set.', self::ERROR_EMAIL_NOT_SET);
return false;
}
if ($this->inputUserExists('firstname')) {
$this->setFName($this->inputUserGet('firstname'));
}
if ($this->inputUserExists('lastname')) {
$this->setLName($this->inputUserGet('lastname'));
}
if ($this->inputUserExists('shop')) {
$this->setShop($this->inputUserGet('shop'));
}
if ($this->inputUserExists('language')) {
$this->setLanguage($this->inputUserGet('language'));
}
if ($this->inputUserExists('user_type')) {
$this->setUserType($this->inputUserGet('user_type'));
}
if ($this->inputUserExists('ip')) {
$this->setIP($this->inputUserGet('ip'));
}
if ($this->inputUserExists('lang_iso')) {
$this->setLanguageISO($this->inputUserGet('lang_iso'));
}
if ($this->inputUserExists('phone')) {
$this->setPhone($this->inputUserGet('phone'));
}
if ($this->inputUserExists('birthday')) {
$this->setBirthday($this->inputUserGet('birthday'));
}
if ($this->inputUserExists('birthday')) {
$this->setBirthday($this->inputUserGet('birthday'));
}
if ($this->inputUserExists('last_order')) {
$this->setLastOrder($this->inputUserGet('last_order'));
}
if ($this->inputUserExists('date_add')) {
$this->setDateAdd($this->inputUserGet('date_add'));
}
if ($this->inputUserExists('date')) {
$this->setDate($this->inputUserGet('date'));
}
if ($this->inputUserExists('subscribed')) {
$this->setSubscribed($this->inputUserGet('subscribed'));
}
if ($this->inputUserExists('phone_mobile')) {
$this->setPhoneMobile($this->inputUserGet('phone_mobile'));
}
if ($this->inputUserExists('company')) {
$this->setCompany($this->inputUserGet('company'));
}
if ($this->inputUserExists('groups')) {
$this->setInterest($this->inputUserGet('groups'));
}
if ($this->inputUserExists('address')) {
$this->setAddress($this->inputUserGet('address'));
}
$this->users[] = $this->getUser();
}
public function getUser()
{
return $this->user;
}
public function getUsers()
{
return $this->users;
}
public function setEmail($email)
{
$this->user['email_address'] = $email;
$this->addUserVar('EMAIL', $email);
}
public function setFName($fname)
{
$this->addUserVar('FNAME', $fname);
}
public function setLName($lname)
{
$this->addUserVar('LNAME', $lname);
}
public function setInterest($groups = [])
{
$chimpGroups = pqnp_config('CHIMP.CUSTOMERS_GROUP_IDS');
$interests = [];
$groupsIds = [];
if (isset($groups['groups'])) {
$groupsIds = $groups['groups'];
}
if (count($groupsIds) > 0) {
foreach ($groupsIds as $groupId) {
if (array_key_exists($groupId, $chimpGroups) && !array_key_exists($groupId, $interests)) {
$interests[$chimpGroups[$groupId]] = true;
}
}
}
$this->user['interests'] = $interests;
}
public function setShop($shop)
{
$this->addUserVar('SHOP', $shop);
}
public function setLanguage($language)
{
$this->addUserVar('LANGUAGE', $language);
}
public function setUserType($user_type)
{
$this->addUserVar('USER_TYPE', $user_type);
}
public function setLastOrder($date)
{
$date_fromated = self::makeDate($date);
$this->addUserVar('LAST_ORDER', $date_fromated);
}
public function setSubscribed($subscribed)
{
$this->user['status'] = (bool) $subscribed ? self::STATUS_SUBSCRIBED : self::STATUS_UNSUBSCRIBED;
$value = 'yes';
switch ($subscribed) {
case true:
$value = 'yes';
break;
case false:
$value = 'no';
break;
default:
$value = 'yes';
break;
}
$this->addUserVar('SUBSCRIBED', $value);
}
public function setPhoneMobile($mobile)
{
if (isset($mobile) && $mobile) {
$mobile_formated = self::formatPhone($mobile);
$this->addUserVar('PHONE_MOB', $mobile_formated);
}
}
public function setCompany($company)
{
$this->addUserVar('COMPANY', $company);
}
public function setIP($ip)
{
$this->addUserVar('OPTIN_IP', $ip);
$this->user['ip_opt'] = $ip;
}
public function setBirthday($date)
{
$date_fromated = self::makeDate($date, 'm/d');
$this->addUserVar('BIRTHDAY', $date_fromated);
}
public function setLanguageISO($iso)
{
$iso = Tools::strtolower($iso);
$this->addUserVar('MC_LANGUAGE', $iso);
$this->user['language'] = $iso;
}
public function setAddress($address)
{
$newAddress = [];
if (isset($address['addr1'])) {
$newAddress['addr1'] = (string) $address['addr1'];
} else {
$newAddress['addr1'] = '';
}
if (isset($address['addr2'])) {
$newAddress['addr2'] = (string) $address['addr2'];
} else {
$newAddress['addr2'] = '';
}
if (isset($address['city'])) {
$newAddress['city'] = (string) $address['city'];
} else {
$newAddress['city'] = '';
}
if (isset($address['state'])) {
$newAddress['state'] = (string) $address['state'];
} else {
$newAddress['state'] = '';
}
if (isset($address['zip'])) {
$newAddress['zip'] = (string) $address['zip'];
} else {
$newAddress['zip'] = '';
}
if (isset($address['country'])) {
$newAddress['country'] = (string) Tools::strtoupper($address['country']);
} else {
$newAddress['country'] = '';
}
$this->addUserVar('ADDRESS', $newAddress);
}
public function setDateAdd($date)
{
$date_fromated = self::makeDate($date);
$this->addUserVar('DATE_ADD', $date_fromated);
}
public function setDate($date)
{
$date_fromated = self::makeDate($date);
$this->addUserVar('DATE', $date_fromated);
}
public function setPhone($phone)
{
if (isset($phone) && $phone) {
$phone_formated = self::formatPhone($phone);
$this->addUserVar('PHONE', $phone_formated);
}
}
public static function makeDate($date, $format = 'm/d/Y')
{
return NewsletterProMailChimpApi::makeDate($date, $format);
}
public static function formatPhone($phone)
{
return NewsletterProMailChimpApi::formatPhone($phone);
}
public function addError($error, $code = null)
{
$add_error = [
'code' => $code,
'error' => Tools::displayError($error),
];
$this->errors[] = $add_error;
}
public function hasErrors()
{
return !empty($this->errors);
}
public function getErrors($only_errors = false, $collapse_same_code = false)
{
$errors = $this->errors;
if ($collapse_same_code) {
$errors_collapse = [];
$errors_coldes = [];
foreach ($errors as $error) {
if (!in_array($error['code'], $errors_coldes)) {
$errors_collapse[] = $error;
$errors_coldes[] = $error['code'];
}
}
$errors = $errors_collapse;
}
$return_errors = [];
if ($only_errors) {
foreach ($errors as $error) {
$return_errors[] = $error['error'];
}
} else {
$return_errors = $errors;
}
return $return_errors;
}
}

View File

@@ -0,0 +1,139 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailChimpWebhooks
{
private $module;
public function __construct()
{
$this->module = NewsletterPro::getInstance();
}
public static function newInstance()
{
return new self();
}
public function process()
{
$type = Tools::getValue('type');
$data = Tools::getValue('data');
switch ($type) {
case 'subscribe':
return $this->subscribe($data);
case 'unsubscribe':
return $this->unsubscribe($data);
case 'cleaned':
return $this->cleaned($data);
case 'upemail':
return $this->upemail();
case 'profile':
return $this->profile();
default:
throw new Exception(sprintf($this->module->l('Invalid MailChimp webhook request type.'), $type));
}
return false;
}
private function subscribe($data)
{
$email = $data['email'];
$errors = $this->module->subscribe($email, Configuration::get('PS_LANG_DEFAULT'), Configuration::get('PS_SHOP_DEFAULT'));
if (!empty($errors)) {
$errors_msg = implode("\n", $errors);
NewsletterProLog::writeStrip($errors_msg, NewsletterProLog::ERROR_FILE);
return $errors_msg;
} else {
return sprintf($this->module->l('The email address "%s" has been subscribed at the newsletter.'), $email);
}
}
private function unsubscribe($data)
{
$email = $data['email'];
$action = $data['action'];
switch ($action) {
case 'delete':
if ($this->module->ini_config['mailchimp_allow_unsubscribe_delete']) {
return $this->deleteEmail($email);
} else {
return $this->unsubscribeEmail($email);
}
// no break
case 'unsub':
default:
return $this->unsubscribeEmail($email);
}
return false;
}
private function cleaned($data)
{
$email = $data['email'];
if ($this->module->ini_config['mailchimp_allow_cleaned_emails']) {
return $this->deleteEmail($email);
}
return $this->module->l('The mailchimp webhook "cleaned emails" feature is not activated.');
}
private function upemail()
{
return $this->featureUnavailableMessage();
}
private function profile()
{
return $this->featureUnavailableMessage();
}
private function deleteEmail($email)
{
if (NewsletterProBounce::execute($email, [], -1)) {
return sprintf($this->module->l('The email address "%s" has been removed from the newsletter.'), $email);
} else {
return sprintf($this->module->l('The email address "%s" has not been removed from the newsletter. Maybe the email does not exists into database.'), $email);
}
}
private function unsubscribeEmail($email)
{
if (NewsletterProBounce::execute($email, [], 0)) {
return sprintf($this->module->l('The email address "%s" has been unsubscribed from the newsletter.'), $email);
} else {
return sprintf($this->module->l('The email address "%s" has not been unsubscribed from the newsletter. Maybe the email does not exists into database.'), $email);
}
}
private function featureUnavailableMessage()
{
return $this->module->l('This webhook feature is unavailable.');
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
interface NewsletterProMailInterface
{
public static function newInstance($id = null);
public function setFromName($name);
public function addError($error);
public function getErrors();
public function hasErrors();
public function send($subject, $template, $to);
public function sendForward($data, $type, $from, $sleep = 1);
public function addSuccessFwd($email);
public function getSuccessFwdCount();
public function getTemplate($email, $data, $type);
public static function getEmailInfo($email);
public static function getInstance($connection = []);
public static function getDefaultSMTP();
public static function getDefaultMail();
}

View File

@@ -0,0 +1,295 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMailSwift extends ObjectModel
{
/* database variables */
public $method;
public $name;
public $from_name;
public $from_email;
public $reply_to;
public $domain;
public $server;
public $user;
public $passwd;
public $encryption;
public $port;
public $list_unsubscribe_active;
public $list_unsubscribe_email;
/* defined variables */
public $context;
public $errors = [];
public $fwd_success_emails = [];
const METHOD_MAIL = 1;
const METHOD_SMTP = 2;
public static $definition = [
'table' => 'newsletter_pro_smtp',
'primary' => 'id_newsletter_pro_smtp',
'fields' => [
'name' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true],
'from_email' => ['type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true],
'from_name' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'reply_to' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'domain' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'server' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'user' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'passwd' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'encryption' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'port' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
'method' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'list_unsubscribe_active' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'list_unsubscribe_email' => ['type' => self::TYPE_STRING, 'validate' => 'isString'],
],
];
public static function newInstance($id = null)
{
return new NewsletterProMail($id);
}
public function setFromName($name)
{
$this->from_name = $name;
}
public function addError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return $this->errors;
}
public function hasErrors()
{
return !empty($this->errors);
}
public function addSuccessFwd($email)
{
$this->fwd_success_emails[] = $email;
}
public function getSuccessFwdCount()
{
return count($this->fwd_success_emails);
}
public function getTemplate($email, $id_history, $type)
{
$template = false;
switch ($type) {
case 'history':
$template = NewsletterProTemplate::newHistory((int) $id_history, $email)->load();
break;
}
return $template;
}
/**
* Get an instance of the class.
*
* @param array $smtp Define de SMTP connection
*
* @return array SMTP connection
*/
public static function getInstance($connection = [])
{
$shop_email = Configuration::get('PS_SHOP_EMAIL');
$mail = NewsletterProMail::newInstance();
$mail->name = isset($connection['name']) ? $connection['name'] : uniqid();
$mail->from_name = isset($connection['from_name']) ? $connection['from_name'] : (string) $mail->context->shop->name;
$mail->from_email = isset($connection['from_email']) ? $connection['from_email'] : $shop_email;
$mail->reply_to = isset($connection['from_email']) ? $connection['from_email'] : $shop_email;
$mail->domain = isset($connection['domain']) ? $connection['domain'] : '';
$mail->server = isset($connection['server']) ? $connection['server'] : '';
$mail->user = isset($connection['user']) ? $connection['user'] : '';
$mail->passwd = isset($connection['passwd']) ? $connection['passwd'] : '';
$mail->encryption = isset($connection['encryption']) ? $connection['encryption'] : $mail->encryption;
$mail->port = isset($connection['port']) ? $connection['port'] : 'default';
$mail->method = isset($connection['method']) ? $connection['method'] : self::METHOD_MAIL;
$mail->list_unsubscribe_active = isset($connection['list_unsubscribe_active']) ? $connection['list_unsubscribe_active'] : 0;
$mail->list_unsubscribe_email = isset($connection['list_unsubscribe_email']) ? $connection['list_unsubscribe_email'] : '';
return $mail;
}
/**
* Get the prestashp default SMTP connection.
*
* @param array $smtp Override the default SMTP values
*
* @return array/boolean SMTP connection or false
*/
public static function getDefaultSMTP()
{
$context = Context::getContext();
$connection = Configuration::getMultiple([
'PS_SHOP_EMAIL',
'PS_MAIL_SERVER',
'PS_MAIL_USER',
'PS_MAIL_PASSWD',
'PS_MAIL_SMTP_ENCRYPTION',
'PS_MAIL_SMTP_PORT',
'PS_MAIL_DOMAIN',
]);
if ($connection) {
return [
'from_name' => (string) $context->shop->name,
'from_email' => $connection['PS_SHOP_EMAIL'],
'reply_to' => $connection['PS_SHOP_EMAIL'],
'domain' => $connection['PS_MAIL_DOMAIN'],
'server' => $connection['PS_MAIL_SERVER'],
'user' => $connection['PS_MAIL_USER'],
'passwd' => $connection['PS_MAIL_PASSWD'],
'encryption' => $connection['PS_MAIL_SMTP_ENCRYPTION'],
'port' => $connection['PS_MAIL_SMTP_PORT'],
'method' => self::METHOD_SMTP,
'list_unsubscribe_active' => 0,
'list_unsubscribe_email' => '',
];
}
return false;
}
/**
* Get the default mail() connection.
*
* @return array/boolean Mail connection or false
*/
public static function getDefaultMail()
{
$context = Context::getContext();
$connection = Configuration::getMultiple([
'PS_SHOP_EMAIL',
]);
if ($connection) {
return [
'from_name' => (string) $context->shop->name,
'from_email' => $connection['PS_SHOP_EMAIL'],
'reply_to' => $connection['PS_SHOP_EMAIL'],
'method' => self::METHOD_MAIL,
'list_unsubscribe_active' => 0,
'list_unsubscribe_email' => '',
];
}
return false;
}
/**
* Get default connection.
*
* @return array/boolean Return the default connection of false
*/
public static function getDefaultConnection()
{
$method = (int) Configuration::get('PS_MAIL_METHOD');
if (self::METHOD_MAIL == $method) {
return self::getDefaultMail();
} elseif (self::METHOD_SMTP == $method) {
return self::getDefaultSMTP();
}
return false;
}
/**
* Get the active instance [SMTP, function mail(), or the default prestashop method].
*
* @return object/false return an instance or false
*/
public static function getInstanceByContext()
{
if ((int) pqnp_config('SMTP_ACTIVE')) {
if (!(int) pqnp_config('SMTP')) {
throw new Exception(sprintf(NewsletterPro::getInstance()->l('You have actived the connection from the "%s" tab, but you forget to configure one.'), NewsletterPro::getInstance()->l('E-mail Configuration')));
}
$mail = NewsletterProMail::newInstance((int) pqnp_config('SMTP'));
if (Validate::isLoadedObject($mail)) {
return $mail;
}
} else {
return NewsletterProMail::getInstance(self::getDefaultConnection());
}
return false;
}
public static function getAllMails()
{
return Db::getInstance()->executeS(
'SELECT `id_newsletter_pro_smtp`,
`method`,
`name`,
`domain`,
`server`,
`user`,
`from_name`,
`from_email`,
`reply_to`,
`encryption`,
`port`,
`list_unsubscribe_active`,
`list_unsubscribe_email`,
CASE WHEN `passwd` = 0 THEN "" ELSE "" END AS `passwd`
FROM `'._DB_PREFIX_.'newsletter_pro_smtp`
WHERE 1;'
);
}
public function getEncryption()
{
$encryption = Tools::strtolower($this->encryption);
if (!in_array($encryption, ['tls', 'ssl'])) {
return false;
}
return $encryption;
}
}

View File

@@ -0,0 +1,232 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMedia
{
const CACHE_NAME = 'cache_name';
const FILES = 'files';
const FOLDER_NAME = 'cache';
private $controller;
private $css;
private $js;
public function __construct()
{
$this->css = [];
$this->js = [];
}
public static function newInstance()
{
return new self();
}
public function setController($controller)
{
$this->controller = $controller;
return $this;
}
public function addCSS($cache_name, $files)
{
$this->css[] = [
self::CACHE_NAME => $cache_name,
self::FILES => $files,
];
return $this;
}
public function addJS($cache_name, $files)
{
$this->js[] = [
self::CACHE_NAME => $cache_name,
self::FILES => $files,
];
return $this;
}
/**
* Load the media files.
*/
public function load($load_cache = false, $create_cache = false, $css = true, $js = true)
{
$module = NewsletterPro::getInstance();
$dir_css = $module->dir_location.'views/css';
$path_css = $module->uri_location.'views/css';
$dir_js = $module->dir_location.'views/js';
$path_js = $module->uri_location.'views/js';
if (!isset($this->controller)) {
throw new Exception('The media controller is not set.');
}
if ($create_cache) {
$this->cache(false);
}
// $this->loadFile($load_cache, $this->css, PQCRP_CSS.'/', PQCRP_CSS_PATH, 'addCSS');
// $this->loadFile($load_cache, $this->js, PQCRP_JS.'/', PQCRP_JS_PATH, 'addJS');
if ($css) {
$this->loadFile($load_cache, $this->css, $dir_css, $path_css, 'addCSS');
}
if ($js) {
$this->loadFile($load_cache, $this->js, $dir_js, $path_js, 'addJS');
}
return $this;
}
/**
* Create the cache files.
*/
public function cache($force = false, $css = true, $js = true)
{
$module = NewsletterPro::getInstance();
$dir_css = $module->dir_location.'views/css';
$path_css = $module->uri_location.'views/css';
$dir_js = $module->dir_location.'views/js';
$path_js = $module->uri_location.'views/js';
// $this->writeCache($this->css, PQCRP_CSS.'/', PQCRP_CSS_PATH, 'addCSS', $force);
// $this->writeCache($this->js, PQCRP_JS.'/', PQCRP_JS_PATH, 'addJS', $force);
if ($css) {
$this->writeCache($this->css, $dir_css, $path_css, 'addCSS', $force);
}
if ($js) {
$this->writeCache($this->js, $dir_js, $path_js, 'addJS', $force);
}
return $this;
}
private function writeCache($data, $dir, $path, $func_name, $force = false)
{
$base_name = $_SERVER['DOCUMENT_ROOT'];
foreach ($data as $data_value) {
$data_cache_content = [];
foreach ($data_value[self::FILES] as $file) {
$data_filename = $base_name.$file;
if (file_exists($data_filename)) {
$content = Tools::file_get_contents($data_filename);
if ('addCSS' == $func_name) {
$file_trim = ltrim(str_replace(['/', '//', '\\', '\\\\'], '/', $file), '/');
$depth = substr_count($file_trim, '/');
if (0 == $depth) {
$content = preg_replace('/(url\()((.*)?\))/', '$1../$2', $content);
} elseif ($depth >= 2) {
$content = preg_replace('/(url\()(\.\.\/)+(.*)?(\))/', '$1../../$3$4', $content);
}
}
$data_cache_content[] = $content;
}
}
$data_cache_content = implode("\n", $data_cache_content);
$cache_filename = $this->getCacheFilename($dir, $data_value[self::CACHE_NAME]);
$cache_path = $this->getCachePath($path, $data_value[self::CACHE_NAME]);
if (function_exists('mb_strlen')) {
if (!$this->cacheFileExists($cache_filename)) {
file_put_contents($cache_filename, $data_cache_content);
} elseif (mb_strlen($data_cache_content, '8bit') !== filesize($cache_filename)) {
file_put_contents($cache_filename, $data_cache_content);
} elseif ($force) {
file_put_contents($cache_filename, $data_cache_content);
}
} else {
if (!$this->cacheFileExists($cache_filename)) {
file_put_contents($cache_filename, $data_cache_content);
} elseif ($force) {
file_put_contents($cache_filename, $data_cache_content);
}
}
}
}
private function loadFile($load_cache, $data, $dir, $path, $func_name)
{
if ($load_cache) {
foreach ($data as $data_value) {
$cache_filename = $this->getCacheFilename($dir, $data_value[self::CACHE_NAME]);
$cache_path = $this->getCachePath($path, $data_value[self::CACHE_NAME]);
$file_exists = $this->cacheFileExists($cache_filename);
if ($file_exists && is_readable($cache_filename)) {
$info = pathinfo($cache_filename);
$min_name = $info['filename'].'.min.'.$info['extension'];
$min_filename = $info['dirname'].'/'.$min_name;
if (file_exists($min_filename) && is_readable($min_filename) && filemtime($min_filename) >= filemtime($cache_filename)) {
$min_cache_path = $this->getCachePath($path, $min_name);
$this->controller->{$func_name}($min_cache_path);
} else {
$this->controller->{$func_name}($cache_path);
}
} else {
foreach ($data_value[self::FILES] as $file) {
$this->controller->{$func_name}($file);
}
}
}
} else {
foreach ($data as $data_value) {
foreach ($data_value[self::FILES] as $file) {
$this->controller->{$func_name}($file);
}
}
}
}
private function cacheFileExists($filename)
{
return file_exists($filename);
}
private function getCacheFilename($dir, $cache_name)
{
return $dir.'/'.self::FOLDER_NAME.'/'.$cache_name;
}
private function getCachePath($path, $cache_name)
{
return $path.'/'.self::FOLDER_NAME.'/'.$cache_name;
}
}

View File

@@ -0,0 +1,166 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMySQLDump
{
public $tabels;
public $hex_value;
public $insert_ignore;
public $header;
public function __construct($hex_value = false, $insert_ignore = true)
{
$this->tables = [];
$this->hex_value = $hex_value;
$this->insert_ignore = $insert_ignore;
}
public function setHeader($header)
{
$this->header = $header;
}
public function addTable($table_name)
{
$this->tables[] = _DB_PREFIX_.$table_name;
}
public function saveTableData($table_name)
{
$success = [];
$data = "\n-- start statement\n\n";
$data .= "-- \n";
$data .= "-- Dumping data for table `{$table_name}` \n";
$data .= "-- \n\n";
$records = Db::getInstance()->executeS('SHOW FIELDS FROM `'.pSQL($table_name).'`');
if (!$records) {
return false;
}
$select_statement = 'SELECT ';
$insert_statement = 'INSERT '.($this->insert_ignore ? 'IGNORE' : '').' INTO `'.pSQL($table_name).'` (';
$hex_field = [];
$i = 0;
foreach ($records as $key => $record) {
if ($this->hex_value && $this->isTextValue($record['Type'])) {
$select_statement .= 'HEX(`'.$record['Field'].'`)';
$hex_field[$i] = true;
} else {
$select_statement .= '`'.$record['Field'].'`';
}
$insert_statement .= '`'.$record['Field'].'`';
$insert_statement .= ', ';
$select_statement .= ', ';
++$i;
}
$insert_statement = Tools::substr($insert_statement, 0, -2).') VALUES';
$select_statement = Tools::substr($select_statement, 0, -2).' FROM `'.pSQL($table_name).'`';
$records = Db::getInstance()->executeS($select_statement);
$num_rows = count($records);
if ($num_rows > 0) {
$data .= $insert_statement;
foreach ($records as $key => $record) {
$data .= ' (';
$j = 0;
foreach ($record as $value) {
if (isset($hex_field[$j]) && $hex_field[$j] && (Tools::strlen($value) > 0)) {
$data .= '0x'.$value;
} elseif (is_null($value)) {
$data .= 'NULL';
} else {
$data .= "'".str_replace('\"', '"', addcslashes($value, "\x00\n\r\\'\"\x1a"))."'";
}
$data .= ',';
++$j;
}
$data = Tools::substr($data, 0, -1).')';
$data .= ($key < ($num_rows - 1)) ? ',' : ';';
$data .= "\n";
if (Tools::strlen($data) > 1048576) {
$success[] = $this->saveToFile($data);
$data = '';
}
}
$data .= "\n-- end statement\n\n";
$success[] = $this->saveToFile($data);
}
return !in_array(false, $success);
}
public function save($filename)
{
$success = [];
$this->file = fopen($filename, 'w');
if (isset($this->header)) {
$success[] = $this->saveToFile($this->header);
}
foreach ($this->tables as $table_name) {
$success[] = $this->saveTableData($table_name);
}
fclose($this->file);
return !in_array(false, $success);
}
public function saveToFile($data)
{
return fwrite($this->file, $data);
}
public function isTextValue($field_type)
{
switch ($field_type) {
case 'tinytext':
case 'text':
case 'mediumtext':
case 'longtext':
case 'binary':
case 'varbinary':
case 'tinyblob':
case 'blob':
case 'mediumblob':
case 'longblob':
return true;
default:
return false;
}
}
}

View File

@@ -0,0 +1,317 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProMySQLDumpXml
{
public $tables;
public $hex_value;
public $insert_ignore;
public $headers;
public $xml;
public $filename;
public $prepend_string;
public function __construct($hex_value = false, $insert_ignore = true)
{
$this->headers = [];
$this->tables = [];
$this->prepend_string = [];
$this->hex_value = $hex_value;
$this->insert_ignore = $insert_ignore;
$this->xml = new NewsletterProCreateXML('database');
$this->xml->attribute($this->xml->root, 'name', _DB_NAME_);
}
/**
* Add header.
*
* @param string $name Header name
* @param string $value Header value
*/
public function addHeader($name, $value)
{
$this->headers[$name] = $value;
}
/**
* Get header by name.
*
* @param string $name Header name
*
* @return string/false Header value
*/
public function getHeaderByName($name)
{
if (isset($this->headers[$name])) {
return $this->headers[$name];
}
return false;
}
/**
* Add tables.
*
* @param array/string $table_name Table name
*/
public function addTables($table_name)
{
if (is_array($table_name)) {
foreach ($table_name as $table_n) {
$this->tables[] = _DB_PREFIX_.$table_n;
}
} else {
$this->tables[] = _DB_PREFIX_.$table_name;
}
}
/**
* Get all tables.
*
* @return array
*/
public function getTables()
{
return $this->tables;
}
public function setHeader(array $headers)
{
$this->headers = $headers;
}
public function prependString($string)
{
$this->prepend_string[] = $string;
}
public function save($filename)
{
$success = [];
$this->filename = $filename;
$this->xml->header = $this->xml->create($this->xml->root, 'header');
foreach ($this->headers as $name => $value) {
$this->xml->append($this->xml->header, $name, $value);
}
$this->xml->tables = $this->xml->create($this->xml->root, 'tables');
if ($this->file = fopen($filename, 'w')) {
$success[] = $this->saveToFile(implode('', $this->prepend_string));
foreach ($this->tables as $table_name) {
if ($this->tableExists($table_name)) {
$success[] = $this->createTable($table_name);
}
}
$success[] = $this->saveToFile($this->xml->getContent($this->xml->root));
@fclose($this->file);
} else {
throw new Exception($this->module->l('Cannot create the backup. Please check the CHMOD permissions.'));
}
return !in_array(false, $success);
}
public function tableExists($table_name)
{
return count(Db::getInstance()->executeS('SHOW TABLES LIKE "'.pSQL($table_name).'"'));
}
public function saveToFile($data)
{
return @fwrite($this->file, $data);
}
public function createTable($table_name)
{
$success = [];
$records = Db::getInstance()->executeS('SHOW FIELDS FROM `'.pSQL($table_name).'`');
if (!$records) {
return false;
}
$table = $this->xml->create($this->xml->tables, 'table', 'name', pSQL($table_name));
$fields = $this->xml->append($table, 'fields');
$select_statement = 'SELECT ';
$hex_field = [];
$i = 0;
foreach ($records as $record) {
$is_hex = ($this->hex_value && $this->isTextValue($record['Type']));
if ($is_hex) {
$select_statement .= 'HEX(`'.$record['Field'].'`) AS '.$record['Field'].'';
$hex_field[$i] = true;
} else {
$select_statement .= '`'.$record['Field'].'`';
}
$field = $this->xml->append($fields, 'field');
$this->xml->attribute($field, 'name', $record['Field']);
$type = $this->getFieldType($record['Type']);
$this->xml->attribute($field, 'datatype', $type['type']);
$this->xml->attribute($field, 'length_set', $type['size']);
$this->xml->attribute($field, 'unsigned', $type['unsigned']);
$this->xml->attribute($field, 'allow_null', $this->getFieldNull($record['Null']));
$this->xml->attribute($field, 'key', $this->getFieldKey($record['Key']));
$this->xml->attribute($field, 'default', $this->getFieldDefault($record['Default']));
$this->xml->attribute($field, 'default_is_null', $this->getFieldIsDefault($record['Default']));
$this->xml->attribute($field, 'extra', $this->getFieldExtra($record['Extra']));
$this->xml->attribute($field, 'is_hex', (int) $is_hex);
$select_statement .= ', ';
++$i;
}
$select_statement = Tools::substr($select_statement, 0, -2).' FROM `'.pSQL($table_name).'`';
$records = Db::getInstance()->executeS($select_statement);
$num_rows = count($records);
if ($num_rows > 0) {
$records_xml = $this->xml->append($table, 'records');
foreach ($records as $record) {
$record_xml = $this->xml->append($records_xml, 'record');
$j = 0;
foreach ($record as $field_name => $value) {
if (isset($hex_field[$j]) && $hex_field[$j] && (Tools::strlen($value) > 0)) {
$field_value = '0x'.$value;
} elseif (is_null($value)) {
$field_value = 'NULL';
} else {
$field_value = $value;
}
$this->xml->append($record_xml, $field_name, $field_value);
++$j;
}
}
}
return !in_array(false, $success);
}
public function isTextValue($field_type)
{
switch ($field_type) {
case 'tinytext':
case 'text':
case 'mediumtext':
case 'longtext':
case 'binary':
case 'varbinary':
case 'tinyblob':
case 'blob':
case 'mediumblob':
case 'longblob':
return true;
default:
return false;
}
}
public function getFieldType($value)
{
preg_match('/(?P<type>\w+)(\((?P<size>.*)\))?\s?(?P<unsigned>\w+)?/i', $value, $match);
return [
'type' => isset($match['type']) ? $match['type'] : false,
'size' => isset($match['size']) ? $match['size'] : 0,
'unsigned' => isset($match['unsigned']) ? $match['unsigned'] : 0,
];
}
public function getFieldNull($value)
{
switch (Tools::strtolower($value)) {
case 'yes':
return 1;
case 'no':
default:
return 0;
}
return 0;
}
public function getFieldKey($value)
{
switch (Tools::strtolower($value)) {
case 'pri':
return 'PRI';
case 'uni':
return 'UNI';
case 'mul':
return 'MUL';
default:
return '';
}
return '';
}
public function getFieldExtra($value)
{
switch (Tools::strtolower($value)) {
case 'auto_increment':
return 'auto_increment';
default:
return '';
}
return '';
}
public function getFieldDefault($value)
{
if (is_null($value)) {
return null;
} else {
return $value;
}
}
public function getFieldIsDefault($value)
{
return (int) is_null($value);
}
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
abstract class NewsletterProObjectClass
{
public function l($string)
{
return Translate::getModuleTranslation(NewsletterProTools::module(), $string, Tools::strtolower(get_class($this)));
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProOpenedEmail
{
public $id_newsletter;
public $email;
public $table;
public $id_table;
public static function newsletterExists($id_newsletter)
{
return Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter_pro_tpl_history`
WHERE `id_newsletter_pro_tpl_history` = '.(int) $id_newsletter.'
');
}
public static function emailExists($email)
{
if (!Validate::isEmail($email)) {
return false;
}
$query = [];
$query['customer'] = 'SELECT `id_customer` FROM `'._DB_PREFIX_.'customer` WHERE `email` = "'.pSQL($email).'"';
if (NewsletterProTools::tableExists('newsletter')) {
$query['newsletter'] = 'SELECT `id` FROM `'._DB_PREFIX_.'newsletter` WHERE `email` = "'.pSQL($email).'"';
}
if (NewsletterProTools::tableExists('emailsubscription')) {
$query['emailsubscription'] = 'SELECT `id` FROM `'._DB_PREFIX_.'emailsubscription` WHERE `email` = "'.pSQL($email).'"';
}
$query['newsletter_pro_email'] = 'SELECT `id_newsletter_pro_email` FROM `'._DB_PREFIX_.'newsletter_pro_email` WHERE `email` = "'.pSQL($email).'"';
foreach ($query as $table => $sql) {
if ($id_table = Db::getInstance()->getValue($sql)) {
return [
'table' => $table,
'id_table' => $id_table,
];
}
}
return false;
}
public function isValid($id_newsletter, $email)
{
$email_result = self::emailExists($email);
if (self::newsletterExists($id_newsletter) && $email_result) {
$this->id_newsletter = (int) $id_newsletter;
$this->email = (int) $email;
$this->table = $email_result['table'];
$this->id_table = $email_result['id_table'];
return true;
}
return false;
}
public function wasOpened()
{
$cookie = new NewsletterProCookie('opened_email', time() + 259200);
if (!$cookie->get('opened_email')) {
$cookie->set('opened_email', []);
}
$opened_email = $cookie->get('opened_email');
if (!in_array($this->id_newsletter, $opened_email)) {
$cookie->append('opened_email', (int) $this->id_newsletter);
return false;
}
return true;
}
public function update()
{
return Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'newsletter_pro_tpl_history`
SET `opened` = opened + 1
WHERE `id_newsletter_pro_tpl_history` = '.(int) $this->id_newsletter.';
');
}
}

View File

@@ -0,0 +1,265 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProOurModules
{
public $iso_code;
public $context;
public $module;
public $lang;
public static function newInstance()
{
return new self();
}
public function __construct()
{
$this->context = Context::getContext();
$this->module = NewsletterPro::getInstance();
$this->iso_code = $this->context->language->iso_code;
}
public function get()
{
$this->lang = (empty($this->iso_code)) ? 'en' : $this->iso_code;
$contents = $this->getDeveloperModules();
if ('no_connection' == $contents[0]) {
$links = 'Checkout the links below to see our high quality modules:<br>';
foreach ($contents[1] as $value) {
$links .= '<a href="'.$value.'" target="_blank">'.$value.'</a><br>';
}
return $links;
}
$xml = simplexml_load_string($contents);
$items = $xml->channel->item;
$count = 0;
foreach ($items as $item) {
if ((int) $item->displayNew) {
++$count;
}
}
$this->context->smarty->assign([
'items' => $items,
'display_version' => (int) $xml->channel->displayVersion,
'display_rating' => (int) $xml->channel->displayRating,
'display_details' => (int) $xml->channel->displayDetails,
'display_video' => (int) $xml->channel->displayVideo,
'display_demo' => (int) $xml->channel->displayDemo,
'display_price' => (int) $xml->channel->displayPrice,
'display_badge' => (int) $xml->channel->displayBadge,
'display_new' => (int) $xml->channel->displayNew,
'count_new' => $count,
]);
$output = $this->context->smarty->fetch(dirname(__FILE__).'/../views/templates/admin/our_modules_content.tpl');
return $output;
}
public function getDeveloperModules()
{
if ('en' != $this->lang && 'fr' != $this->lang && 'es' != $this->lang) {
$this->lang = 'en';
}
$links = [
'http://addons.prestashop.com/'.$this->lang.'/93_proquality',
];
$modules = '';
$count = 0;
foreach ($links as $value) {
$contents = @Tools::file_get_contents($value);
if (empty($contents)) {
return [
'no_connection',
$links,
];
}
preg_match_all('/(<div class="module ">)(.*)(<div class="module-hover">)/sU', $contents, $patterns);
foreach ($patterns[2] as $value2) {
$details_link = explode('"', $value2);
$details_link = $details_link[1];
$contents = @Tools::file_get_contents($details_link);
preg_match_all('/(<img itemprop="image").*data-original="([^"]+)/', $contents, $patterns);
$logo_img = explode('"', $patterns[2][0]);
$logo_img = $logo_img[0];
preg_match_all('/<img class="badge" src="(.*?)".*?>/i', $contents, $patterns);
$logo_badge = $patterns[1][1];
preg_match_all('/<img class="badge" src="(.*?)".*?>/i', $contents, $patterns);
$downloads = explode('title="', $patterns[0][1]);
$downloads = str_replace('" />', '', $downloads[1]);
preg_match_all('/(<meta itemprop="rating")(.*)(title=")/sU', $contents, $patterns);
$logo_rating = explode('"', $patterns[2][0]);
$logo_rating = $logo_rating[7];
$rating = explode('"', $patterns[2][0]);
$rating = $rating[1];
preg_match_all('/(<h3 >Vers)(.*)(<\/tr>)/sU', $contents, $patterns);
$version = strip_tags(trim($patterns[2][0]));
$version = preg_replace('/[^0-9,.]/', '', $version);
preg_match_all('/(<h1 class="title_product">)(.*)(<\/span>)/sU', $contents, $patterns);
$product_name = strip_tags(trim($patterns[2][0]));
$product_name = trim(str_replace('Module', '', trim($product_name)));
preg_match_all('/(<span id="pretaxe_price_display">)(.*)(\/span>)/sU', $contents, $patterns);
$product_price = strip_tags(trim($patterns[2][0]));
preg_match_all('/(id="video">)(.*)(<\/iframe>)/sU', $contents, $patterns);
$video_link = explode('"', $patterns[2][0]);
$video_link = $video_link[3];
preg_match_all('/(<h3 >Des)(.*)(<h3 >)/sU', $contents, $patterns);
$description = trim(str_replace('cription', '', $patterns[2][0]));
$description = trim(str_replace('cripci&oacute;n', '', $description));
$description = strip_tags(trim($description));
$description = mb_convert_encoding($description, 'UTF-8', 'auto');
if ('en' == $this->lang) {
preg_match_all('/(<td ><h3 >Updated<\/h3><\/td>)(.*)(<\/td>)/sU', $contents, $patterns);
} elseif ('fr' == $this->lang) {
preg_match_all('/(<td ><h3 >Mise &agrave; jour<\/h3><\/td>)(.*)(<\/td>)/sU', $contents, $patterns);
} elseif ('es' == $this->lang) {
preg_match_all('/(<td ><h3 >Actualizado<\/h3><\/td>)(.*)(<\/td>)/sU', $contents, $patterns);
}
$updated_date = strip_tags(trim($patterns[2][0]));
if ('en' != $this->lang) {
$updated_date = str_replace('/', '-', $updated_date);
}
preg_match_all('/(<div class="block_demo">)(.*)(<\/div>)/sU', $contents, $patterns);
$demo_link = explode('"', $patterns[2][0]);
if (strstr($demo_link[1], 'FO')) {
$demo_link_front_office = $demo_link[1];
if (strstr($demo_link[5], 'BO')) {
$demo_link_back_offile = $demo_link[5];
}
} else {
$demo_link_front_office = '';
if (strstr($demo_link[1], 'BO')) {
$demo_link_back_offile = $demo_link[1];
}
}
$begin_timestamp = strtotime('-1 month');
$updated_timestamp = strtotime($updated_date);
if ($updated_timestamp <= $begin_timestamp) {
$new = '0';
} else {
$new = '1';
}
$modules[$count]['logo_img'] = $logo_img;
$modules[$count]['logo_badge'] = $logo_badge;
$modules[$count]['downloads'] = $downloads;
$modules[$count]['logo_rating'] = $logo_rating;
$modules[$count]['rating'] = $rating;
$modules[$count]['version'] = $version;
$modules[$count]['product_name'] = $product_name;
$modules[$count]['product_price'] = $product_price;
$modules[$count]['video_link'] = $video_link;
$modules[$count]['details_link'] = $details_link;
$modules[$count]['description'] = $description;
$modules[$count]['updated_date'] = $updated_date;
$modules[$count]['new'] = $new;
$modules[$count]['demo_link_front_office'] = $demo_link_front_office;
$modules[$count]['demo_link_back_offile'] = $demo_link_back_offile;
++$count;
}
}
if (ob_get_level()) {
ob_end_clean();
}
$rss = new XMLWriter();
$rss->openMemory();
$rss->setIndent(true);
$rss->startElement('rss');
$rss->writeAttribute('version', '2.0');
$rss->startElement('channel');
foreach ($modules as $value) {
$display_rating_visibility = empty($value['logo_rating']) ? '0' : '1';
$display_badge_visibility = empty($value['logo_badge']) ? '0' : '1';
$display_video_visibility = empty($value['video_link']) ? '0' : '1';
$rss->writeElement('displayVersion', '1');
$rss->writeElement('displayRating', '1');
$rss->writeElement('displayDetails', '1');
$rss->writeElement('displayVideo', '1');
$rss->writeElement('displayDemo', '1');
$rss->writeElement('displayPrice', '1');
$rss->writeElement('displayNew', '1');
$rss->writeElement('displayBadge', '1');
$rss->startElement('item');
$rss->writeElement('displayRating', $display_rating_visibility);
$rss->writeElement('displayDetails', '1');
$rss->writeElement('displayVideo', $display_video_visibility);
$rss->writeElement('displayDemo', '1');
$rss->writeElement('displayNew', $value['new']);
$rss->writeElement('displayBadge', $display_badge_visibility);
$rss->writeElement('badge', $value['logo_badge']);
$rss->writeElement('downloads', $value['downloads']);
$rss->writeElement('version', $value['version']);
$rss->writeElement('name', $value['product_name']);
$rss->writeElement('rating', $value['logo_rating']);
$rss->writeElement('description', $value['description']);
$rss->writeElement('icon', $value['logo_img']);
$rss->writeElement('demo', $value['demo_link_back_offile']);
$rss->writeElement('video', $value['video_link']);
$rss->writeElement('details', $value['details_link']);
$rss->writeElement('price', $value['product_price']);
$rss->writeElement('detailsHTML', 'details');
$rss->writeElement('videoHTML', 'video');
$rss->writeElement('demoHTML', 'demo');
$rss->writeElement('newHTML', 'new');
$rss->endElement();
}
$rss->endElement();
$rss->endElement();
return $rss->flush();
}
}

View File

@@ -0,0 +1,46 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProOutput
{
private $data;
public function __construct()
{
$this->data = [];
}
public function append($str)
{
$this->data[] = $str;
}
public function render($textPlain = false)
{
if ($textPlain) {
header('Content-Type: text/plain');
}
return implode('', $this->data);
}
public function clear()
{
$this->data = [];
}
}

View File

@@ -0,0 +1,474 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProPopupAction extends NewsletterProAction
{
private $error_message;
private $translate;
public function __construct()
{
parent::__construct();
$this->translate = new NewsletterProTranslate(__CLASS__);
$this->error_message = $this->translate->l('Oops, an error has occurred.');
}
public static function newInstance()
{
return new self();
}
public function call($action)
{
try {
switch ($action) {
case 'subscribe':
return $this->subscribe();
case 'unsubscribe':
return $this->unsubscribe();
case 'destroy':
return $this->destroy();
}
} catch (Exception $e) {
NewsletterProLog::writeStrip($e->__toString(), NewsletterProLog::ERROR_FILE);
if (_PS_MODE_DEV_ && (bool) pqnp_config('DEBUG_MODE')) {
return $this->response->error($e->__toString())->output();
} else {
return $this->response->error($this->error_message)->output();
}
}
parent::call();
}
private function getTemplate()
{
$template = new NewsletterProSubscriptionTpl((int) $this->request->get('templateId', 0));
if (!Validate::isLoadedObject($template)) {
$load_file = (string) $this->request->get('loadFile', '');
if (0 == Tools::strlen($load_file)) {
return $this->response->error($this->translate->l('Unable to load the template file.'))->output();
}
// this is for development
$load_dirname = _NEWSLETTER_PRO_DIR_.'/install/tables/subscription_tpl/'.$load_file.'/';
$template = NewsletterProSubscriptionTpl::loadFile($load_dirname, true, true);
}
return $template;
}
private function subscribe()
{
$self = $this;
$errors = [];
$form_errors = [];
$context = Context::getContext();
$template = $this->getTemplate();
if (!$this->request->has('terms_and_conditions')) {
$this->request->set('terms_and_conditions', 0, NewsletterProRequest::TYPE_POST);
}
// validate the fields
$this->request->validate($errors, $form_errors, [
'email' => ['type' => ObjectModel::TYPE_STRING, 'modifier' => ['trim'], 'validate' => [
['func' => 'NewsletterProValidate::isFilled', 'message' => $this->translate->l('The Email Address is required.')],
['func' => 'isEmail', 'message' => $this->translate->l('The Email Address is not valid.')],
]],
'terms_and_conditions' => ['type' => ObjectModel::TYPE_BOOL, 'modifier' => ['intval'], 'validate' => [
['func' => function ($tac) use ($self) {
if (false == (bool) $tac) {
return $self->translate->l('You must agree with the terms and conditions.');
}
}],
]],
]);
if ((bool) $template->display_firstname && $this->request->has('firstname')) {
if ($template->isMandatory('firstname')) {
$this->request->validate($errors, $form_errors, [
'firstname' => ['type' => ObjectModel::TYPE_STRING, 'modifier' => ['trim'], 'validate' => [
['func' => 'NewsletterProValidate::isFilled', 'message' => $this->translate->l('The First Name is required.')],
['func' => 'isName', 'message' => $this->translate->l('The First Name is not valid.')],
]],
]);
} elseif ($this->request->has('firstname')) {
$this->request->validate($errors, $form_errors, [
'firstname' => ['type' => ObjectModel::TYPE_STRING, 'modifier' => ['trim'], 'validate' => [
['func' => 'isName', 'message' => $this->translate->l('The First Name is not valid.')],
]],
]);
}
}
if ((bool) $template->display_lastname && $this->request->has('lastname')) {
if ($template->isMandatory('lastname')) {
$this->request->validate($errors, $form_errors, [
'lastname' => ['type' => ObjectModel::TYPE_STRING, 'modifier' => ['trim'], 'validate' => [
['func' => 'NewsletterProValidate::isFilled', 'message' => $this->translate->l('The Last Name is required.')],
['func' => 'isName', 'message' => $this->translate->l('The Last Name is not valid.')],
]],
]);
} elseif ($this->request->has('lastname')) {
$this->request->validate($errors, $form_errors, [
'lastname' => ['type' => ObjectModel::TYPE_STRING, 'modifier' => ['trim'], 'validate' => [
['func' => 'isName', 'message' => $this->translate->l('The Last Name is not valid.')],
]],
]);
}
}
if ((bool) $template->display_gender && $this->request->has('gender')) {
$this->request->validate($errors, $form_errors, [
'gender' => ['type' => ObjectModel::TYPE_INT, 'modifier' => ['intval'], 'validate' => [
['func' => function ($gender_id) use ($self) {
if (0 !== (int) $gender_id) {
if (!Validate::isLoadedObject(new Gender((int) $gender_id))) {
return $self->translate->l('The Gender is not valid.');
}
}
}],
]],
]);
}
if ((bool) $template->display_birthday && $this->request->has('birthday')) {
$this->request->validate($errors, $form_errors, [
'birthday' => ['type' => ObjectModel::TYPE_DATE, 'modifier' => ['trim'], 'validate' => [
['func' => function ($birthday) use ($self) {
$message = $self->translate->l('The Birthday is not valid.');
if (Tools::strlen($birthday) > 0) {
if (!Validate::isDate($birthday)) {
return $message;
}
$date = explode('-', $birthday);
if (!array_key_exists(0, $date)) {
return $message;
}
$year = (int) $date[0];
if ($year < 1900 || $year > ((int) date('Y') - 14)) {
return $message;
}
}
}],
]],
]);
}
if ((bool) $template->display_birthday && $this->request->has('birthday_day') && $this->request->has('birthday_month') && $this->request->has('birthday_year')) {
$birthday_year = $this->request->get('birthday_year', '0');
$birthday_month = $this->request->get('birthday_month', '0');
$birthday_day = $this->request->get('birthday_day', '0');
$birthday = trim($this->request->get('birthday_year', '').'-'.$this->request->get('birthday_month').'-'.$this->request->get('birthday_day'));
$message = $self->translate->l('The Birthday is not valid.');
if ('0' !== $birthday_year || '0' !== $birthday_month || '0' !== $birthday_day) {
$date = explode('-', $birthday);
$year = (int) $date[0];
if (!Validate::isDate($birthday)) {
$errors[] = $message;
} elseif (!array_key_exists(0, $date)) {
$errors[] = $message;
} elseif ($year < 1900 || $year > ((int) date('Y') - 14)) {
$errors[] = $message;
}
}
}
if ((bool) $template->display_list_of_interest && $this->request->has('list_of_interest')) {
$list_of_interest = [];
$loi = $this->request->get('list_of_interest', []);
foreach ($loi as $loi_id) {
if (NewsletterProListOfInterest::isAvaliable((int) $loi_id)) {
$list_of_interest[(int) $loi_id] = true;
}
}
$list_of_interest = array_keys($list_of_interest);
$this->request->set('list_of_interest', $list_of_interest, NewsletterProRequest::TYPE_POST);
}
// validate the custom fields
$custom_variables = NewsletterProSubscribersCustomField::getVariablesDetails();
$custom_fields = [];
foreach ($custom_variables as $variable_name => $variable) {
if ($this->request->has($variable_name)) {
$variable_name_display = trim(implode(' ', array_map(function ($word) {
return Tools::ucfirst(trim($word));
}, explode('_', preg_replace('/^np_/', '', $variable_name)))));
switch ((int) $variable['type']) {
case NewsletterProSubscribersCustomField::TYPE_SELECT:
case NewsletterProSubscribersCustomField::TYPE_INPUT_TEXT:
case NewsletterProSubscribersCustomField::TYPE_RADIO:
case NewsletterProSubscribersCustomField::TYPE_TEXTAREA:
$variable_value = trim($this->request->get($variable_name, ''));
if ((bool) $variable['required'] && 0 == Tools::strlen($variable_value)) {
$errors[] = sprintf($this->translate->l('The field %s is required.'), $variable_name_display);
}
$custom_fields[$variable_name] = $variable_value;
break;
case NewsletterProSubscribersCustomField::TYPE_CHECKBOX:
$variable_value = $this->request->get($variable_name, []);
if ((bool) $variable['required'] && 0 == count($variable_value)) {
$errors[] = sprintf($this->translate->l('The field [%s] is required.'), $variable_name_display);
}
$custom_fields[$variable_name] = Tools::jsonEncode($variable_value);
break;
}
}
}
if (!$template->allow_multiple_time_subscription) {
$result = NewsletterProListManager::parse(function ($table_name, $fields) use ($self, $context) {
return (bool) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.pSQL($table_name).'`
WHERE `'.pSQL($fields['email']).'` = "'.$self->request->get('email', '').'"
AND `'.pSQL($fields['active']).'` = 1
AND `id_shop` = '.(int) $context->shop->id.'
');
return true;
});
if (in_array(true, $result)) {
$errors[] = $this->translate->l('The email address is already subscribed at our newsletter.');
}
}
if (!empty($errors)) {
return $this->response->error($errors)->output();
}
$email = $this->request->get('email');
$subscriber = NewsletterProSubscribers::getInstanceByEmail($email, (int) $context->shop->id);
$subscriber->email = $email;
$subscriber->id_gender = $this->request->get('gender', 0);
$subscriber->firstname = $this->request->get('firstname', '');
$subscriber->lastname = $this->request->get('lastname', '');
if ($this->request->has('birthday')) {
$subscriber->birthday = $this->request->get('birthday', '');
} elseif ($this->request->has('birthday_day') &&
$this->request->has('birthday_month') &&
$this->request->has('birthday_year')) {
$birthday_date = trim($this->request->get('birthday_year', '').'-'.$this->request->get('birthday_month', '').'-'.$this->request->get('birthday_day', ''));
if (Validate::isDate($birthday_date)) {
$subscriber->birthday = $birthday_date;
}
}
$subscriber->list_of_interest = $subscriber->buildListOfInterest($this->request->get('list_of_interest', []));
$subscriber->id_shop = (int) $context->shop->id;
$subscriber->id_shop_group = (int) $context->shop->id_shop_group;
$subscriber->id_lang = (int) $context->language->id;
$subscriber->ip_registration_newsletter = Tools::getRemoteAddr();
$subscriber->date_add = date('Y-m-d H:i:s');
$subscriber->active = true;
foreach ($custom_fields as $field_name => $value) {
$subscriber->{$field_name} = $value;
}
// secure subscription section
if ((bool) pqnp_config('SUBSCRIPTION_SECURE_SUBSCRIBE')) {
$subscriber_temp = new NewsletterProSubscribersTemp();
$subscriber_temp->id_newsletter_pro_subscription_tpl = (int) $template->id;
$subscriber_temp->load_file = $template->getLoadFileBasename();
if (!$subscriber_temp->saveTemp($subscriber)) {
return $this->response->error($this->error_message)->output();
}
$template->extendVars([
'firstname' => htmlentities($subscriber->firstname),
'lastname' => htmlentities($subscriber->lastname),
'email_confirmation_link' => $subscriber_temp->getConfirmationLink(),
'email_confirmation' => '<a href="'.$subscriber_temp->getConfirmationLink().'" style="color: blue;">'.$this->translate->l('here').'</a>',
]);
$message = trim($template->renderEmailSubscribeConfirmationMessage((int) $context->language->id));
$subject = NewsletterProHTMLRender::getTitle($message);
if ((bool) pqnp_config('DEBUG_MODE')) {
$send = NewsletterProSendManager::getInstance()->sendNewsletter($subject, $message, $subscriber->email, [], [], false);
} else {
$send = @NewsletterProSendManager::getInstance()->sendNewsletter($subject, $message, $subscriber->email, [], [], false);
}
if (is_array($send)) {
return $this->response->error($this->translate->l('Oops, an error has occurred, we are unable to send the confirmation email.'))->output();
}
$message = sprintf($this->translate->l('A confirmation email has been sent to the email address "%s". To subscribe please click on the link from your email address.'), $subscriber->email);
return $this->response->setData([
'newWindow' => (bool) $template->display_subscribe_message ? true : false,
'message' => (bool) $template->display_subscribe_message ? '<p>'.htmlentities(html_entity_decode($message), ENT_NOQUOTES).'</p>' : $message,
'closeTimeout' => 8000,
])->output();
}
// no secure subscribe section
if (!$subscriber->save()) {
return $this->response->error($this->error_message)->output();
}
$consent = NewsletterProSubscriptionConsent::newInstance()->set($subscriber->email, (bool) $subscriber->active, $context->customer->isLogged());
NewsletterProSubscriptionManager::newInstance()->subscribe($subscriber->email, (int) $context->shop->id, $consent);
// copy the categoreis into the customer my account
$customer_loi = NewsletterProCustomerListOfInterests::getInstanceByCustomerId((int) $context->customer->id);
if (Validate::isLoadedObject($customer_loi)) {
$customer_loi->setCategories($subscriber->getListOfInterest());
$customer_loi->update();
}
$unsubscribe_link = urldecode($context->link->getModuleLink(NewsletterProTools::module()->name, 'unsubscribe', [
'email' => $subscriber->email,
'u_token' => Tools::encrypt($subscriber->email),
'msg' => true,
], null, $context->language->id, $context->shop->id));
$template->extendVars([
'unsubscribe_link' => $unsubscribe_link,
'unsubscribe' => '<a href="'.$unsubscribe_link.'" target="_blank">'.NewsletterProTools::module()->l('unsubscribe').'</a>',
]);
if ($template->hasValidVoucher()) {
// send the voucher to the subscriber email
$message = trim($template->renderEmailSubscribeVoucherMessage((int) $context->language->id));
$subject = NewsletterProHTMLRender::getTitle($message);
if ((bool) pqnp_config('DEBUG_MODE')) {
$send = NewsletterProSendManager::getInstance()->sendNewsletter($subject, $message, $subscriber->email, [], [], false);
} else {
$send = @NewsletterProSendManager::getInstance()->sendNewsletter($subject, $message, $subscriber->email, [], [], false);
}
// show the voucher to the customer
$message = trim($template->renderSubscribeMessage((int) $context->language->id));
$message_strip = trim(strip_tags($message));
if ((bool) $template->display_subscribe_message) {
return $this->response->setData([
'newWindow' => true,
'message' => $message,
])->output();
}
return $this->response->setData([
'newWindow' => false,
'message' => $message_strip,
'closeTimeout' => 10000,
])->output();
}
return $this->response->setData([
'newWindow' => false,
'message' => $this->translate->l('You have been subscribed to our newsletter.'),
])->output();
}
private function unsubscribe()
{
$errors = [];
$form_errors = [];
$context = Context::getContext();
$template = $this->getTemplate();
$this->request->validate($errors, $form_errors, [
'email' => ['type' => ObjectModel::TYPE_STRING, 'modifier' => ['trim'], 'validate' => [
['func' => 'NewsletterProValidate::isFilled', 'message' => $this->translate->l('The Email Address is required.')],
['func' => 'isEmail', 'message' => $this->translate->l('The Email Address is not valid.')],
]],
]);
if (!empty($errors)) {
return $this->response->error($errors)->output();
}
$email = $this->request->get('email');
$unsubscribe_link = urldecode($context->link->getModuleLink('newsletterpro', 'unsubscribe', [
'email' => $email,
'u_token' => Tools::encrypt($email),
'msg' => true,
], null, (int) $context->language->id, $context->shop->id));
$template->extendVars([
'unsubscribe_link' => $unsubscribe_link,
'unsubscribe' => '<a href="'.$unsubscribe_link.'" style="color: blue;">'.$this->translate->l('here').'</a>',
]);
$message = trim($template->renderEmailUnsubscribeConfirmationMessage((int) $context->language->id));
$subject = NewsletterProHTMLRender::getTitle($message);
if ((bool) pqnp_config('DEBUG_MODE')) {
$send = NewsletterProSendManager::getInstance()->sendNewsletter($subject, $message, $email, [], [], false);
} else {
$send = @NewsletterProSendManager::getInstance()->sendNewsletter($subject, $message, $email, [], [], false);
}
if (is_array($send)) {
return $this->response->error($this->translate->l('Oops, an error has occurred, we are unable to send the confirmation email.'))->output();
}
$message = sprintf($this->translate->l('A confirmation email has been sent to the email address "%s". To unsubscribe please click on the link from your email address.'), $email);
return $this->response->setData([
'newWindow' => (bool) $template->display_subscribe_message ? true : false,
'message' => (bool) $template->display_subscribe_message ? '<p>'.htmlentities(html_entity_decode($message), ENT_NOQUOTES).'</p>' : $message,
'closeTimeout' => 8000,
])->output();
}
private function destroy()
{
$template = $this->getTemplate();
$life_time_days = round((60 * 60 * 24) * (float) $template->cookie_lifetime);
$cookie = new NewsletterProCookie('subscription_template_front', time() + $life_time_days);
$cookie->set('popup_show', '0');
if (true == (bool) $cookie->get('popup_show')) {
return $this->response->error($this->error_message)->output();
}
return $this->response->setData([])->output();
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProPostman
{
public function __construct($action)
{
switch ($action) {
case 'test':
exit($this->test());
break;
default:
exit('Invalid Request');
break;
}
}
public function test()
{
exit('test');
}
}

View File

@@ -0,0 +1,153 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProPrepareNewsletter
{
public $emails;
private $template;
private $set_template_called;
private $id_newsletter_pro_send;
public function __construct()
{
$this->set_template_called = false;
}
public static function newInstance()
{
return new self();
}
public function setTemplate($template)
{
$this->set_template_called = true;
$this->template = $template;
return $this;
}
public function setEmails($emails)
{
$this->emails = $this->sanitizeEmails($emails);
return $this;
}
public function add()
{
if (!isset($this->set_template_called) || (isset($this->set_template_called) && !$this->set_template_called)) {
throw new Exception('The function "setTemplate" must be called before the "add" function.');
}
if (!isset($this->emails)) {
throw new Exception('The function "setEmails" must be called before the "add" function.');
}
$history = NewsletterProTplHistory::newFromTemplate($this->template);
$history->add();
$this->id_newsletter_pro_send = 0;
if (Db::getInstance()->insert('newsletter_pro_send', [
'id_newsletter_pro_tpl_history' => (int) $history->id,
'active' => 1,
'template' => pSQL(pqnp_config('NEWSLETTER_TEMPLATE')),
'date' => date('Y-m-d H:i:s'),
'emails_count' => (int) count($this->emails),
])) {
$this->id_newsletter_pro_send = Db::getInstance()->Insert_ID();
} else {
throw new Exception(sprintf($this->l('Fail to insert the records into "%s" table!'), 'newsletter_pro_send'));
}
$emails_break_step = $this->breakEmailsStep();
$connections = [];
if ($this->hasConnections()) {
$connections = NewsletterProSendConnection::getConnections();
}
$index = 0;
$step = 1;
foreach ($emails_break_step as $emails) {
$id_newsletter_pro_send_connection = 0;
if (!empty($connections)) {
$id_newsletter_pro_send_connection = $connections[$index % count($connections)]['id_newsletter_pro_send_connection'];
}
if (!Db::getInstance()->insert('newsletter_pro_send_step', [
'emails_to_send' => NewsletterProTools::dbSerialize($emails),
'id_newsletter_pro_send' => (int) $this->id_newsletter_pro_send,
'id_newsletter_pro_send_connection' => $id_newsletter_pro_send_connection,
'step' => (int) $step++,
'step_active' => 1,
'date' => date('Y-m-d H:i:s'),
'emails_sent' => NewsletterProTools::dbSerialize([]),
])) {
throw new Exception(sprintf(NewsletterPro::getInstance()->l('Fail to insert the records into "%s" table!'), 'newsletter_pro_send_step'));
}
++$index;
}
return true;
}
private function sanitizeEmails($emails)
{
$valid_emails = [];
foreach ($emails as $email) {
$email = trim($email);
if (!in_array($email, $valid_emails) && Validate::isEmail($email)) {
$valid_emails[] = $email;
}
}
return $valid_emails;
}
private function breakEmailsStep($break_limit = null)
{
if (!isset($break_limit)) {
$break_limit = NewsletterPro::getInstance()->step;
}
// If there are connections and the send booster plugin is activated the break limit will take another value
if ($this->hasConnections()) {
$divide = ceil(count($this->emails) / NewsletterProSendConnection::countConnections());
if ($divide < $break_limit) {
$break_limit = $divide;
}
}
return array_chunk($this->emails, $break_limit, true);
}
private function hasConnections()
{
return NewsletterProSendConnection::countConnections();
}
}

View File

@@ -0,0 +1,540 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProPrivacyData
{
public static $anonymous_email = 'anonymous@anonymous.com';
public static $log_files = [
'errors.log',
'info.log',
'send.log',
'task.log',
];
public function __construct()
{
}
public function search($email)
{
$results = [
'info' => [
'db_prefix' => _DB_PREFIX_,
'is_email' => Validate::isEmail($email),
],
'tables' => NewsletterProPrivacyDataResponse::collectionToArray($this->serachTables($email)),
'logs' => NewsletterProPrivacyDataResponse::collectionToArray($this->searchLogs($email)),
'csv' => NewsletterProPrivacyDataResponse::collectionToArray($this->searchCSV($email)),
];
return $results;
}
public function clear($email)
{
$results = [
'info' => [
'db_prefix' => _DB_PREFIX_,
'is_email' => Validate::isEmail($email),
],
'tables' => NewsletterProPrivacyDataResponse::collectionToArray($this->clearTables($email)),
'logs' => NewsletterProPrivacyDataResponse::collectionToArray($this->clearLogs($email)),
'csv' => NewsletterProPrivacyDataResponse::collectionToArray($this->clearCSV($email)),
];
return $results;
}
public function export($email)
{
$responses = [
NewsletterProEmail::exportPrivacy($email),
NewsletterProEmailExclusion::exportPrivacy($email),
NewsletterProForward::exportPrivacy($email),
NewsletterProFwdUnsubscribed::exportPrivacy($email),
NewsletterProSend::exportPrivacy($email),
NewsletterProSendStep::exportPrivacy($email),
NewsletterProSubscribers::exportPrivacy($email),
NewsletterProSubscribersTemp::exportPrivacy($email),
NewsletterProSubscriptionConsent::exportPrivacy($email),
NewsletterProTask::exportPrivacy($email),
NewsletterProTaskStep::exportPrivacy($email),
NewsletterProUnsubscribed::exportPrivacy($email),
NewsletterProCustomerCategory::exportPrivacy($email),
NewsletterProCustomerListOfInterests::exportPrivacy($email),
$this->emailsubscriptionExportPrivacy($email),
$this->newsletterExportPrivacy($email),
$this->customerExportPrivacy($email),
];
$export = [];
$errors = [];
foreach ($responses as $response) {
$data = $response->toArray();
if (!empty($data['export'])) {
foreach ($data['export'] as $value) {
$export[] = $value;
}
}
if ($response->hasErrors()) {
$response->appendErrors($errors);
}
}
return [
'data' => $export,
'errors' => $errors,
];
}
public function hookActionDelete($email)
{
$response = [];
foreach ($this->clearTables($email) as $response_obj) {
if ($response_obj->hasErrors()) {
$response_obj->appendErrors($response);
}
}
foreach ($this->clearLogs($email) as $response_obj) {
if ($response_obj->hasErrors()) {
$response_obj->appendErrors($response);
}
}
foreach ($this->clearCSV($email) as $response_obj) {
if ($response_obj->hasErrors()) {
$response_obj->appendErrors($response);
}
}
if (empty($response)) {
return true;
}
return $response;
}
private function clearTables($email)
{
return [
NewsletterProEmail::clearPrivacy($email),
NewsletterProEmailExclusion::clearPrivacy($email),
NewsletterProForward::clearPrivacy($email),
NewsletterProFwdUnsubscribed::clearPrivacy($email),
NewsletterProSend::clearPrivacy($email),
NewsletterProSendStep::clearPrivacy($email),
NewsletterProSubscribers::clearPrivacy($email),
NewsletterProSubscribersTemp::clearPrivacy($email),
NewsletterProSubscriptionConsent::clearPrivacy($email),
NewsletterProTask::clearPrivacy($email),
NewsletterProTaskStep::clearPrivacy($email),
NewsletterProUnsubscribed::clearPrivacy($email),
NewsletterProCustomerCategory::clearPrivacy($email),
NewsletterProCustomerListOfInterests::clearPrivacy($email),
$this->emailsubscriptionClearPrivacy($email),
$this->newsletterClearPrivacy($email),
$this->customerClearPrivacy($email),
];
}
private function clearLogs($email)
{
$responses = [];
$logs_dir = _NEWSLETTER_PRO_DIR_.'/logs/';
foreach (self::$log_files as $name) {
$filename = $logs_dir.$name;
if (file_exists($filename) && is_readable($filename)) {
$content = Tools::file_get_contents($filename);
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, $name, $email);
if (preg_match_all('/'.preg_quote($email).'[^\w]/', $content, $match)) {
if (count($match) > 0) {
$new_content = preg_replace('/'.preg_quote($email).'([^\w])/', self::$anonymous_email.'${1}', $content);
if (false !== file_put_contents($filename, $new_content)) {
$response->addToCount(count($match[0]));
} else {
$response->addError(sprintf(NewsletterPro::getInstance()->l('Unable to write the file [%s].'), $filename));
}
}
}
$responses[] = $response;
}
}
return $responses;
}
private function clearCSV($email)
{
$responses = [];
$csv_filename = _NEWSLETTER_PRO_DIR_.'/csv/import/';
$files = NewsletterProTools::getDirectoryIterator($csv_filename, '/.csv$/i');
foreach ($files as $file) {
$name = $file->getFilename();
$filename = $file->getPathname();
if (!$file->isDot() && 'sample.csv' !== $name) {
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, $name, $email);
if ($file->isReadable()) {
$content = Tools::file_get_contents($filename);
if (preg_match_all('/'.preg_quote($email).'[^\w]/', $content, $match)) {
if (count($match) > 0) {
$new_content = preg_replace('/.*'.preg_quote($email).'([^\w]).*(\s+)?/', '', $content);
if (false !== file_put_contents($filename, $new_content)) {
$response->addToCount(count($match[0]));
} else {
$response->addError(sprintf(NewsletterPro::getInstance()->l('Unable to write the file [%s].'), $filename));
}
}
}
}
$responses[] = $response;
}
}
return $responses;
}
private function serachTables($email)
{
return [
NewsletterProEmail::privacySerach($email),
NewsletterProEmailExclusion::privacySerach($email),
NewsletterProForward::privacySerach($email),
NewsletterProFwdUnsubscribed::privacySerach($email),
NewsletterProSend::privacySerach($email),
NewsletterProSendStep::privacySerach($email),
NewsletterProSubscribers::privacySerach($email),
NewsletterProSubscribersTemp::privacySerach($email),
NewsletterProSubscriptionConsent::privacySerach($email),
NewsletterProTask::privacySerach($email),
NewsletterProTaskStep::privacySerach($email),
NewsletterProUnsubscribed::privacySerach($email),
NewsletterProCustomerCategory::privacySerach($email),
NewsletterProCustomerListOfInterests::privacySerach($email),
$this->emailsubscriptionPrivacySerach($email),
$this->newsletterPrivacySerach($email),
$this->customerPrivacySerach($email),
];
}
private function searchLogs($email)
{
$responses = [];
$logs_dir = _NEWSLETTER_PRO_DIR_.'/logs/';
foreach (self::$log_files as $name) {
$filename = $logs_dir.$name;
if (file_exists($filename) && is_readable($filename)) {
$content = Tools::file_get_contents($filename);
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, $name, $email);
if (preg_match_all('/'.preg_quote($email).'[^\w]/', $content, $match)) {
if (count($match) > 0) {
$response->addToCount(count($match[0]));
}
}
$responses[] = $response;
}
}
return $responses;
}
private function searchCSV($email)
{
$responses = [];
$csv_filename = _NEWSLETTER_PRO_DIR_.'/csv/import/';
$files = NewsletterProTools::getDirectoryIterator($csv_filename, '/.csv$/i');
foreach ($files as $file) {
$name = $file->getFilename();
$filename = $file->getPathname();
if (!$file->isDot() && 'sample.csv' !== $name) {
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, $name, $email);
if ($file->isReadable()) {
$content = Tools::file_get_contents($file->getPathname());
if (preg_match_all('/'.preg_quote($email).'[^\w]/', $content, $match)) {
if (count($match) > 0) {
$response->addToCount(count($match[0]));
}
}
}
$responses[] = $response;
}
}
return $responses;
}
private function emailsubscriptionPrivacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'emailsubscription', $email);
if (!NewsletterProTools::tableExists('emailsubscription')) {
return $response;
}
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'emailsubscription` WHERE `email` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function emailsubscriptionExportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'emailsubscription', $email);
if (!NewsletterProTools::tableExists('emailsubscription')) {
return $response;
}
try {
$results = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'emailsubscription` WHERE `email` = "'.pSQL($email).'"
');
if (count($results) > 0) {
$data = null;
foreach ($results as $row) {
if (true == (bool) $row['active']) {
$data = $row;
break;
}
}
if (!isset($data)) {
$data = $row;
}
$response->addToExport([
NewsletterPro::getInstance()->l('Subscription list') => '',
NewsletterPro::getInstance()->l('Subscribed') => ((int) $data['active'] ? NewsletterPro::getInstance()->l('Yes') : NewsletterPro::getInstance()->l('No')),
NewsletterPro::getInstance()->l('Email') => (string) $data['email'],
NewsletterPro::getInstance()->l('IP address') => (string) $data['ip_registration_newsletter'],
NewsletterPro::getInstance()->l('Date add') => (string) $data['newsletter_date_add'],
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function newsletterPrivacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'newsletter', $email);
if (!NewsletterProTools::tableExists('newsletter')) {
return $response;
}
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'newsletter` WHERE `email` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function newsletterExportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'newsletter', $email);
if (!NewsletterProTools::tableExists('newsletter')) {
return $response;
}
try {
$results = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'newsletter` WHERE `email` = "'.pSQL($email).'"
');
if (count($results) > 0) {
$data = null;
foreach ($results as $row) {
if (true == (bool) $row['active']) {
$data = $row;
break;
}
}
if (!isset($data)) {
$data = $row;
}
$response->addToExport([
NewsletterPro::getInstance()->l('Newsletter list') => '',
NewsletterPro::getInstance()->l('Subscribed') => ((int) $data['active'] ? NewsletterPro::getInstance()->l('Yes') : NewsletterPro::getInstance()->l('No')),
NewsletterPro::getInstance()->l('Email') => (string) $data['email'],
NewsletterPro::getInstance()->l('IP address') => (string) $data['ip_registration_newsletter'],
NewsletterPro::getInstance()->l('Date add') => (string) $data['newsletter_date_add'],
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function customerPrivacySerach($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_SEARCH, 'customer', $email);
try {
$count = (int) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'customer` WHERE `email` = "'.pSQL($email).'"
');
$response->addToCount($count);
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function customerExportPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_EXPORT, 'customer', $email);
try {
$results = Db::getInstance()->executeS('
SELECT * FROM `'._DB_PREFIX_.'customer` WHERE `email` = "'.pSQL($email).'"
');
if (count($results) > 0) {
$data = null;
foreach ($results as $row) {
if (true == (bool) $row['active']) {
$data = $row;
break;
}
}
if (!isset($data)) {
$data = $row;
}
$response->addToExport([
NewsletterPro::getInstance()->l('Customers list') => '',
NewsletterPro::getInstance()->l('Subscribed') => ((int) $data['newsletter'] ? NewsletterPro::getInstance()->l('Yes') : NewsletterPro::getInstance()->l('No')),
NewsletterPro::getInstance()->l('Firstname') => (string) $data['firstname'],
NewsletterPro::getInstance()->l('Lastname') => (string) $data['lastname'],
NewsletterPro::getInstance()->l('Email') => (string) $data['email'],
NewsletterPro::getInstance()->l('IP address') => (string) $data['ip_registration_newsletter'],
NewsletterPro::getInstance()->l('Date add') => (string) $data['date_add'],
]);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function emailsubscriptionClearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'emailsubscription', $email);
if (!NewsletterProTools::tableExists('emailsubscription')) {
return $response;
}
try {
if (Db::getInstance()->delete('emailsubscription', '`email` = "'.pSQL($email).'"')) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function newsletterClearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'newsletter', $email);
if (!NewsletterProTools::tableExists('newsletter')) {
return $response;
}
try {
if (Db::getInstance()->delete('newsletter', '`email` = "'.pSQL($email).'"')) {
$response->addToCount(Db::getInstance()->Affected_Rows());
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
private function customerClearPrivacy($email)
{
$response = new NewsletterProPrivacyDataResponse(NewsletterProPrivacyDataResponse::TYPE_CLEAR, 'customer', $email);
try {
if (Db::getInstance()->update('customer', [
'newsletter' => 0,
], '`email` = "'.pSQL($email).'"')) {
$res = $this->customerPrivacySerach($email);
$data = $res->toArray();
$response->addToCount((int) $data['count']);
}
} catch (Exception $e) {
$response->addException($e);
}
return $response;
}
}

View File

@@ -0,0 +1,169 @@
<?php
/**
* Since 2013 Ovidiu Cimpean.
*
* Ovidiu Cimpean - Newsletter Pro © All rights reserved.
*
* DISCLAIMER
*
* Do not edit, modify or copy this file.
* If you wish to customize it, contact us at addons4prestashop@gmail.com.
*
* @author Ovidiu Cimpean <addons4prestashop@gmail.com>
* @copyright Since 2013 Ovidiu Cimpean
* @license Do not edit, modify or copy this file
*
* @version Release: 4
*/
class NewsletterProPrivacyDataResponse
{
const TYPE_CLEAR = 1;
const TYPE_SEARCH = 2;
const TYPE_EXPORT = 3;
private $type;
private $name;
private $email;
private $count;
private $export;
private $errors;
private $errors_trace;
public function __construct($type, $name, $email)
{
$this->type = $type;
$this->name = $name;
$this->email = $email;
$this->count = 0;
$this->export = [];
$this->errors = [];
$this->errors_trace = [];
}
public function setCount($count)
{
$this->count = (int) $count;
return $this;
}
public function addToCount($number)
{
$this->count += (int) $number;
return $this;
}
public function addError($error)
{
if (is_string($error)) {
$this->errors[] = $error;
} else {
foreach ($error as $err) {
$this->errors[] = $err;
}
}
return $this;
}
public function addErrorTrace($error)
{
if (is_string($error)) {
$this->errors_trace[] = $error;
} else {
foreach ($error as $err) {
$this->errors_trace[] = $err;
}
}
return $this;
}
public function addException(Exception $e)
{
$this->errors[] = $e->getMessage();
$this->errors_trace[] = $e->__toString();
return $this;
}
public function getName()
{
return $this->name;
}
public function hasErrors()
{
return count($this->errors) > 0;
}
public function getErrors()
{
return $this->errors;
}
public function appendErrors(array &$obj)
{
foreach ($this->errors as $error) {
$obj[] = $error;
}
}
public function setExport(array $export)
{
$this->export = [$export];
}
public function addToExport(array $data)
{
$this->export[] = $data;
}
public function getExport()
{
return $this->export;
}
public function hasExport()
{
return $this->export;
}
public function toArray()
{
if (self::TYPE_EXPORT === $this->type) {
return [
'type' => $this->type,
'name' => $this->name,
'export' => $this->export,
'errors' => $this->errors,
'errors_trace' => $this->errors_trace,
];
}
return [
'type' => $this->type,
'name' => $this->name,
'count' => $this->count,
'errors' => $this->errors,
'errors_trace' => $this->errors_trace,
];
}
public static function collectionToArray($collection)
{
return array_map(function (NewsletterProPrivacyDataResponse $response) {
return $response->toArray();
}, $collection);
}
}

Some files were not shown because too many files have changed in this diff Show More