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

View File

@@ -0,0 +1,171 @@
<?php
require_once __DIR__.'/AdminFreshmailBase.php';
class AdminFreshmailAbandonedCartConfigController extends AdminFreshmailBaseController
{
const TPL_DIR = 'PrestaShop';
const TPL_CATEGORY = 3;
private $cart_config;
public function __construct()
{
$this->bootstrap = true;
parent::__construct();
$this->template = 'cart_config.tpl';
$this->override_folder = '/';
$this->cart_config = (new \FreshMail\Repository\FreshmailAbandonCartSettings(Db::getInstance()))->findForShop($this->context->shop->id);
}
public function run()
{
if(Tools::getIsset('ajax')){
return $this->ajax();
}
return parent::run();
}
private function ajax(){
$action = Tools::getValue('action');
$availableActions = ['set', 'getTpl', 'test'];
$result = [
'success' => false,
'message' => sprintf('Action %s nof found', $action)
];
if(in_array($action, $availableActions) && method_exists($this, $action)) {
$result = $this->$action();
}
die(json_encode($result));
}
public function getTpl()
{
parent::init();
$tplList = [];
if(!empty($this->freshmail) && $this->freshmail->check()){
$tplList = $this->freshmail->getEmailsTemplates(self::TPL_DIR);
\FreshMail\Tools::filterTplByCategory($tplList, self::TPL_CATEGORY);
}
die(
json_encode([
'template' => json_decode($this->cart_config->template),
'tpl_list' => $tplList
])
);
}
public function init(){
parent::init();
$idShop = $this->context->shop->id;
if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_.Configuration::get('PS_LOGO_MAIL', null, null, $idShop))) {
$logo = _PS_IMG_.Configuration::get('PS_LOGO_MAIL', null, null, $idShop);
} else {
if (file_exists(_PS_IMG_DIR_.Configuration::get('PS_LOGO', null, null, $idShop))) {
$logo = _PS_IMG_.Configuration::get('PS_LOGO', null, null, $idShop);
} else {
$logo = '';
}
}
$logo = $this->context->shop->getBaseURL(true).ltrim($logo, '/');
if(!Validate::isLoadedObject($this->cart_config)){
$idLang = Configuration::get('PS_LANG_DEFAULT');
$this->cart_config->email_preheader[$idLang] = $this->module->l('🛒 Complete your purchases!');
$this->cart_config->email_subject[$idLang] = $this->module->l('You have unfinished purchases in your cart.');
}
$this->context->smarty->assign([
'cart_config' => $this->cart_config,
'links' => $this->getLinks(),
'logo' => $logo,
'is_logged' => !empty($this->freshmail) && $this->freshmail->check(),
'id_lang' => Configuration::get('PS_LANG_DEFAULT')
]);
}
private function getLinks()
{
return [
'base_url' => $this->context->link->getBaseLink(null, true),
'cron_url' => $this->context->link->getBaseLink(null, true).'modules/freshmail/cron/abandoned_cart.php?token='.$this->module->getCronToken(),
'cron_cli' => _PS_MODULE_DIR_ . 'freshmail/cron/abandoned_cart.php'
];
}
private function set(){
$config = json_decode(Tools::getValue('config'));
$this->cart_config->enabled = $config->emails == 'true' ? 1 : 0;
$this->cart_config->id_shop = $this->context->shop->id;
$this->cart_config->template = Tools::getValue('template');
$this->cart_config->discount_percent = (int)$config->discount_percent_value;
$this->cart_config->discount_code = pSQL($config->discount_custom_value);
$this->cart_config->discount_type = pSQL($config->discount);
$this->cart_config->template_id_hash = pSQL($config->template_id_hash);
$this->cart_config->send_after = (int)$config->send_after;
$this->cart_config->discount_lifetime = (int)$config->discount_percent_livetime;
$this->cart_config->email_subject = pSQL($config->email_subject);
$this->cart_config->email_preheader = pSQL($config->email_preheader);
$this->cart_config->save();
try {
foreach (Language::getIsoIds() as $lang) {
\FreshMail\Tools::writeEmailTpl(rawurldecode(Tools::getValue('html')), $lang['iso_code']);
}
} catch (Exception $e){
return [
'success' => false,
'message' => $this->module->l('Unable to write file: '.$e->getMessage())
];
}
return [
'success' => true,
'message' => $this->module->l('Configuration saved')
];
}
private function test(){
$testEmail = Tools::getValue('email');
if(!Validate::isEmail($testEmail)){
return [
'success' => false,
'message' => sprintf('Email %s is not valid', $testEmail)
];
}
$abandonRepository = new \FreshMail\Repository\FreshmailAbandonCartSettings(Db::getInstance());
$activeAbandon = $abandonRepository->getActive();
$cartsRepository = new \FreshMail\Repository\Carts(Db::getInstance());
$settingsRepository = new \FreshMail\Repository\FreshmailSettings(Db::getInstance());
$cartService = new \FreshMail\Service\AbandonCartService($cartsRepository, $settingsRepository, $abandonRepository);
foreach ($activeAbandon as $abandon) {
$settings = new \Freshmail\Entity\AbandonedCartSettings($abandon['id_freshmail_cart_setting']);
$cart = new Cart();
$cart->id_shop = $this->context->shop->id;
$cart->id_lang = $this->context->language->id;
$cart->id_currency = Configuration::get('PS_CURRENCY_DEFAULT');
$fmCart = new \FreshMail\Entity\Cart();
$email = new \FreshMail\Sender\Email($testEmail);
$cartService->sendNotifications($cart, $fmCart, $email, new \FreshMail\Sender\Service\MockCartData());
}
return [
'success' => true,
'message' => $this->module->l('Test e-mail was sent')
];
}
}

View File

@@ -0,0 +1,167 @@
<?php
use FreshMail\ApiV2\UnauthorizedException;
use FreshMail\Repository\FreshmailSettings;
class AdminFreshmailAjaxController extends ModuleAdminController
{
private $settingRepository;
const NEW_LIST_KEY = 'create_new';
public function __construct()
{
$this->bootstrap = true;
parent::__construct();
$this->templateFile = _PS_MODULE_DIR_ . $this->module->name . '/views/templates/admin/wizard.tpl';
$this->settingRepository = new FreshmailSettings();
}
public function run()
{
if ($step = Tools::getValue('step')) {
if (method_exists($this, $step)) {
echo json_encode($this->$step());
}
}
$this->context->smarty->assign([
'is_wizard_available' => $this->isWizardAvailable(),
'links' => $this->getLinks(),
'specific_price_rules' => \FreshMail\Tools::getSpecificPriceRules($this->context->shop->id)
]);
return $this->context->smarty->fetch($this->templateFile);
}
private function getLinks()
{
return [
'settings' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'settings']),
'connect' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'connect']),
'save' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'save']),
'lists' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'getLists']),
'register_url' => 'https://app.freshmail.com/pl/auth/login',
];
}
private function isWizardAvailable()
{
return true;
}
private function settings()
{
$settings = $this->settingRepository->findForShop($this->context->shop->id);
$this->module->loadFreshmailApi();
$freshailApi = new \FreshMail\ApiV2\Client($settings->api_token);
$isLogged = false;
try {
$status = $freshailApi->doRequest('ping');
$isLogged = true;
} catch (UnauthorizedException $unauthorizedException) {
}
return [
'logged_in' => $isLogged,
'api_token' => $settings->api_token,
'smtp' => (bool)$settings->smtp,
'synchronize' => (bool)$settings->synchronize,
'id_specific_price_rule' => ((int)$settings->id_specific_price_rule > 0) ? (int)$settings->id_specific_price_rule : ''
];
}
private function connect()
{
$this->module->loadFreshmailApi();
$freshailApi = new \FreshMail\ApiV2\Client(Tools::getValue('api_token'));
try {
$freshailApi->doRequest('ping');
} catch (UnauthorizedException $unauthorizedException) {
header("HTTP/1.1 401 Unauthorized");
return [
'success' => false,
'message' => $this->l('Please provide a valid token')
];
}
$fs = $this->settingRepository->findForShop($this->context->shop->id);
$fs->api_token = Tools::getValue('api_token');
$fs->id_shop = $this->context->shop->id;
$fs->save();
return [
'success' => true,
'message' => $this->l('Correctly connected to the freshmail account')
];
}
private function getLists()
{
$fs = $this->settingRepository->findForShop($this->context->shop->id);
$freshmail = new \FreshMail\Freshmail($fs->api_token);
try {
$list = array_merge(
[[
'subscriberListHash' => self::NEW_LIST_KEY,
'name' => 'Prestashop - ' . $this->context->shop->name
]],
$freshmail->getLists()
);
return [
'success' => true,
'data' => $list
];
} catch (Exception $e) {
return [
'success' => false,
'message' => $this->l('Please provide a valid token')
];
}
// /rest/
}
private function save()
{
$fs = $this->settingRepository->findForShop($this->context->shop->id);
$fs->smtp = (Tools::getValue('smtp') == 'true') ? 1 : 0;
if (1 == $fs->smtp) {
\FreshMail\Tools::setShopSmtp($fs->api_token);
}
$fs->synchronize = (Tools::getValue('synchronize') == 'true') ? 1 : 0;
$listHash = '';
if (1 == $fs->synchronize) {
$listHash = Tools::getValue('synchronize_list');
if (self::NEW_LIST_KEY == Tools::getValue('synchronize_list', '')) {
$name = 'Prestashop - ' . $this->context->shop->name;
$description = \Context::getContext()->getTranslator()->trans('List from ', [], 'Modules.freshmail').$this->context->shop->name;
$listHash = (new \FreshMail\Freshmail($fs->api_token))->addList($name, $description);
}
}
$fs->subscriber_list_hash = $listHash;
$fs->wizard_completed = 1;
$fs->id_specific_price_rule = (int)Tools::getValue('id_specific_price_rule');
$fs->save();
return [
'success' => true,
'message' => $this->module->l('Configuration saved')
];
}
}

View File

@@ -0,0 +1,33 @@
<?php
use FreshMail\ApiV2\UnauthorizedException;
use FreshMail\Repository\FreshmailSettings;
class AdminFreshmailBaseController extends ModuleAdminController
{
protected $freshmail;
protected $freshmailSettings;
public function init()
{
$this->freshmailSettings = (new FreshmailSettings())->findForShop($this->context->shop->id);
if (!Validate::isLoadedObject(($this->freshmailSettings)) || 0 == $this->freshmailSettings->wizard_completed) {
$link = $this->context->link->getAdminLink('AdminModules', true, [], ['configure' => $this->module->name]);
Tools::redirectAdmin($link);
}
if(!empty($this->freshmailSettings->api_token)) {
$this->freshmail = new \FreshMail\Freshmail($this->freshmailSettings->api_token);
$response = $this->freshmail->check();
if (!$response['status']) {
$link = $this->context->link->getAdminLink('AdminFreshmailConfig', true, [], ['configure' => $this->module->name]);
Tools::redirectAdmin($link);
}
}
return parent::init(); // TODO: Change the autogenerated stub
}
}

View File

@@ -0,0 +1,196 @@
<?php
require_once __DIR__.'/AdminFreshmailBase.php';
class AdminFreshmailBirthdayController extends AdminFreshmailBaseController
{
const TPL_DIR = 'PrestaShop';
const TPL_CATEGORY = 4;
private $freshmailBirthday;
public function __construct()
{
$this->bootstrap = true;
$this->display = 'edit';
parent::__construct();
/*$this->template = 'cart_config.tpl';
$this->override_folder = '/';*/
$this->freshmailBirthday = (new \FreshMail\Repository\Birthdays(Db::getInstance()))->findForShop($this->context->shop->id);
}
public function init()
{
parent::init();
if(Tools::getIsset('send')){
require_once __DIR__.'/../../cron/birthday.php';
Tools::redirectAdmin($this->context->link->getAdminLink('AdminFreshmailBirthday').'&sent');
}
if(Tools::getIsset('sent')){
$this->confirmations[] = $this->module->l('Emails sent');
}
}
public function renderForm()
{
$this->submit_action = $this->display . $this->identifier;
$this->show_form_cancel_button = false;
$this->fields_form = [
'legend' => [
'title' => $this->module->l('Birthday e-mails'),
],
'input' => [
[
'type' => 'switch',
'label' => $this->module->l('Enable'),
'name' => 'birthday',
'required' => true,
'class' => 'switch prestashop-switch',
'is_bool' => true,
'values' => [
[
'id' => 'active_on',
'value' => 1,
'label' => $this->module->l('Enabled')
],
[
'id' => 'active_off',
'value' => 0,
'label' => $this->module->l('Disabled')
]
],
],
],
'submit' => [
'name' => 'submitFreshmailBirthday',
'title' => $this->module->l('Save'),
'class' => 'btn btn-default pull-right'
],
];
$this->fields_value['birthday'] = $this->freshmailBirthday->enable && Validate::isLoadedObject($this->freshmailBirthday);
if($this->fields_value['birthday']){
$this->extendForm();
}
return parent::renderForm() . $this->extendedInfo();
}
public function postProcess()
{
if(isset($_POST['submitFreshmailBirthday'])){
$this->freshmailBirthday->enable = (bool)Tools::getValue('birthday');
if(isset($_POST['birthday_tpl'])){
$this->freshmailBirthday->tpl = Tools::getValue('birthday_tpl');
}
foreach (Language::getIDs(false) as $id_lang) {
if (isset($_POST['content_'.$id_lang])) {
$this->freshmailBirthday->content[$id_lang] = $_POST['content_'.$id_lang];
}
if (isset($_POST['email_subject_'.$id_lang])) {
$this->freshmailBirthday->email_subject[$id_lang] = $_POST['email_subject_'.$id_lang];
}
}
if(!Validate::isLoadedObject($this->freshmailBirthday)){
$this->freshmailBirthday->id_shop = $this->context->shop->id;
}
$this->freshmailBirthday->save();
}
return parent::postProcess(); // TODO: Change the autogenerated stub
}
public function run()
{
if(Tools::getIsset('ajax')){
return $this->ajax();
}
return parent::run();
}
private function extendForm(){
$this->warnings[] = $this->module->l('Full functionality requires setting a periodic task: ').' '
. $this->context->link->getBaseLink().'modules/freshmail/cron/birthday.php?token='.$this->module->getCronToken()
. '<br>' .$this->module->l('or use cli').': '. _PS_MODULE_DIR_ . 'freshmail/cron/birthday.php'
;
$this->fields_form['input'][] = [
'type' => 'select',
'label' => $this->module->l('Template'),
'desc' => $this->module->l('Lists of templates defined in the Freshmail application'),
'name' => 'birthday_tpl',
'multiple' => false,
'required' => true,
'options' => [
'query' => $this->getTpl(), //$lists,
'id' => 'id_hash',
'name' => 'name'
]
];
$this->fields_form['input'][] = [
'type' => 'text',
'label' => $this->module->l('Email subject'),
'name' => 'email_subject',
//'autoload_rte' => true,
'lang' => true,
];
$this->fields_form['input'][] = [
'type' => 'textarea',
'label' => $this->module->l('Description'),
'name' => 'content',
'autoload_rte' => true,
'lang' => true,
'hint' => $this->module->l('{content}')
];
$this->fields_form['buttons'] = [
[
'href' => AdminController::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminFreshmailBirthday').'&send',
'title' => $this->module->l("Send to today's birthday people"),
'icon' => 'process-icon-refresh'
]
];
$this->fields_value['birthday_tpl'] = $this->freshmailBirthday->tpl;
$this->fields_value['content'] = $this->freshmailBirthday->content;
$this->fields_value['email_subject'] = $this->freshmailBirthday->email_subject;
}
private function extendedInfo()
{
$templateFile = _PS_MODULE_DIR_ . $this->module->name . '/views/templates/admin/birthday.tpl';
return $this->context->smarty->fetch($templateFile);
}
public function getTpl()
{
parent::init();
$tplList = [
['id_hash' => '', 'name' => $this->module->l('Choose')]
];
if(!empty($this->freshmail) && $this->freshmail->check()){
$this->freshmail->getEmailsTemplates(self::TPL_DIR);
$tpls = $this->freshmail->getEmailsTemplates(self::TPL_DIR);
\FreshMail\Tools::filterTplByCategory($tpls, self::TPL_CATEGORY);
$tplList = array_merge($tplList, $tpls );
}
return $tplList;
}
}

View File

@@ -0,0 +1,203 @@
<?php
use FreshMail\Repository\FreshmailSettings;
require_once __DIR__ . '/AdminFreshmailBase.php';
class AdminFreshmailConfigController extends AdminFreshmailBaseController
{
const INTEGRATION_CREATED = 'FreshMail integration for Prestashop created successfully!';
const SUCCESS_UPDATE_API_KEYS = 'API keys update successfully!';
const FRESHMAIL_URL = 'http://freshmail.com';
public function __construct()
{
$this->bootstrap = true;
$this->lang = true;
$this->deleted = false;
$this->colorOnBackground = false;
$this->context = Context::getContext();
parent::__construct();
}
public function initContent()
{
parent::initContent();
if (Tools::isSubmit('resetSettings')) {
$this->resetSettings();
}
$freshmailSettings = (new FreshmailSettings())->findForShop($this->context->shop->id);
if(empty($freshmailSettings->api_token)){
$this->viewPreWizard();
return;
}
$this->viewConfig();
}
public function createTemplate($tpl_name)
{
$path = __DIR__ . '/../../views/templates/admin/';
return $this->context->smarty->createTemplate($path . $tpl_name, $this->context->smarty);
}
public function checkAccess($disable = false)
{
return true;
}
public function viewAccess($disable = false)
{
return true;
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJS(
array(
_PS_MODULE_DIR_ . 'freshmail/views/js/submitNewsletter.js?'.$this->module->version
)
);
}
public function displayAjaxSubmitNewsletter()
{
$this->ajax = true;
Configuration::updateValue('FRESHMAIL_NEWSLETTER_EMAIL', Tools::getValue('email'));
$result = array(
'link' => $this->context->link->getAdminLink('AdminFreshmailConfig') . '&conf=4',
'status' => 'OK'
);
echo json_encode($result);
}
private function submitEnterApiKeys(Freshmail\Entity\FreshmailSetting $fs, \FreshMail\Freshmail $fm){
$api_key = Tools::getValue('api_key');
if (empty($api_key)) {
$this->errors[] = $this->l('An error occurred while updating.');
return;
}
$listHash = Tools::getValue('subscriber_list_hash');
if(empty($listHash) || !in_array($listHash, $this->freshmail->getAllHashList())) {
$this->errors[] = $this->l('Please choose a subscribers list');
return;
}
$changeSMTP = !($fs->smtp == Tools::getValue('smtp'));
$changedList = !($fs->subscriber_list_hash == Tools::getValue('subscriber_list_hash'));
//$fs->api_token = $api_key;
$fs->id_specific_price_rule = (int)Tools::getValue('id_specific_price_rule');
$fs->smtp = (int)Tools::getValue('smtp');
$fs->synchronize = (int)Tools::getValue('synchronize');
$fs->send_confirmation = (int)Tools::getValue('send_confirmation');
$fs->subscriber_list_hash = Tools::getValue('subscriber_list_hash');
$fs->save();
if($changeSMTP){
\FreshMail\Tools::setShopSmtp($api_key);
}
if($changedList){
// check list has tag imie
if(!$fm->hasFieldWithTag($fs->subscriber_list_hash, Freshmail::NAME_TAG)){
$name = \Context::getContext()->getTranslator()->trans('First name', [],'Admin.Global');
$fm->addFieldToList($fs->subscriber_list_hash, Freshmail::NAME_TAG, $name) ;
}
\FreshMail\Tools::triggerSynchronization($fs->subscriber_list_hash);
}
$link = $this->context->link->getAdminLink('AdminFreshmailConfig') . '&conf=6';
Tools::redirectAdmin($link);
}
private function submitConnectToApi(\Freshmail\Entity\FreshmailSetting $fs){
$api = new \FreshMail\Freshmail($fs->api_token);
$response = $api->check();
if ($response && $response['status'] == 'OK') {
return true;
}
else {
$this->errors[] = $this->module->l('Error while connecting to FreshMail API');
}
}
private function resetSettings()
{
\FreshMail\Tools::clearShopSettings($this->context->shop->id);
$link = $this->context->link->getAdminLink('AdminModules', true, [], ['configure' => $this->module->name]);
Tools::redirectAdmin($link);
}
private function viewPreWizard(){
$links = [
'reset' => $this->context->link->getAdminLink('AdminFreshmailConfig', true, [], ['resetSettings' => 1]),
'base_url' => $this->context->link->getBaseLink(null, true),
];
$this->context->smarty->assign([
'links' => $links,
]);
$this->setTemplate('wizard_preview.tpl');
}
private function viewConfig(){
$this->initTabModuleList();
$this->initToolbar();
$this->initPageHeaderToolbar();
$this->addToolBarModulesListButton();
if(!\FreshMail\Tools::checkDirPermission(FreshMail::TMP_DIR)){
$this->errors[] = $this->l('Set temporary dir as writeable').' ('.FreshMail::TMP_DIR.')';
}
unset($this->toolbar_btn['save']);
$back = $this->context->link->getAdminLink('AdminDashboard');
$this->toolbar_btn['back'] = array(
'href' => $back,
'desc' => $this->l('Back to the dashboard'),
);
$freshmailSettings = (new FreshmailSettings())->findForShop($this->context->shop->id);
$fm = new FreshMail\Freshmail($freshmailSettings->api_token);
$helpArray = array(
'url_post' => self::$currentIndex . '&token=' . $this->token,
'module_templates' => _PS_MODULE_DIR_ . $this->module->name . '/views/templates/admin/',
'show_page_header_toolbar' => $this->show_page_header_toolbar,
'page_header_toolbar_title' => $this->page_header_toolbar_title,
'page_header_toolbar_btn' => $this->page_header_toolbar_btn,
'response' => null,
'specific_price_rules' => \FreshMail\Tools::getSpecificPriceRules($this->context->shop->id),
'subscribers_list' => $fm->getAllList(),
'freshmail_settings' => $freshmailSettings
);
if (Tools::isSubmit('submitEnterApiKeys')) {
$this->submitEnterApiKeys($freshmailSettings, $fm);
} elseif (Tools::isSubmit('submitConnectToApi')) {
if($this->submitConnectToApi($freshmailSettings)) {
$helpArray['success'] = $this->module->l(self::INTEGRATION_CREATED);
}
}
if (!empty($freshmailSettings->api_token)) {
$helpArray['showCheck'] = true;
} else {
$helpArray['showCheck'] = false;
}
$helpArray['FRESHMAIL_NEWSLETTER_EMAIL'] = Configuration::get('FRESHMAIL_NEWSLETTER_EMAIL');
$helpArray['FRESHMAIL_API_KEY'] = $freshmailSettings->api_token;
$this->context->smarty->assign($helpArray);
$this->setTemplate('api.tpl');
}
}

View File

@@ -0,0 +1,22 @@
<?php
class AdminFreshmailDashboardController extends ModuleAdminController
{
public function __construct()
{
$this->bootstrap = true;
$this->context = Context::getContext();
$this->className = 'AdminQpAllegroApi';
parent::__construct();
}
public function run()
{
return 'xxxxxx';
}
}

View File

@@ -0,0 +1,435 @@
<?php
use FreshMail\ApiV2\Client;
use FreshMail\Entity\Form;
use FreshMail\FreshmailApiV3;
use FreshMail\Service\FieldService;
use FreshMail\Service\FormService;
require_once __DIR__ . '/AdminFreshmailBase.php';
class AdminFreshmailFormConfigController extends AdminFreshmailBaseController
{
public static $UPDATE_SUCCESS = "Success!";
public static $ERROR = "Error!";
private $fmForms = [];
public function __construct()
{
$this->bootstrap = true;
$this->tpl_folder = 'freshmail_controller';
$this->lang = false;
$this->explicitSelect = true;
$this->context = Context::getContext();
$this->show_cancel_button = false;
$this->table = 'freshmail_form';
$this->identifier = 'id_freshmail_form';
$this->className = Form::class;
parent::__construct();
}
public function init()
{
parent::init();
if(Tools::getIsset('refresh')){
$this->module->clearFormCache();
}
$this->fmForms = $this->freshmail->getForms($this->freshmailSettings->subscriber_list_hash);
}
public function initContent()
{
$this->initTabModuleList();
$this->initToolbar();
parent::initContent();
}
public function initPageHeaderToolbar()
{
if (empty($this->display)) {
$this->page_header_toolbar_btn['refresh'] = array(
'href' => self::$currentIndex . '&refresh=1&token=' . $this->token,
'desc' => $this->module->l('Refresh cache'),
'icon' => 'process-icon-refresh'
);
$this->page_header_toolbar_btn['new_product'] = array(
'href' => self::$currentIndex . '&add' . $this->table . '=1&token=' . $this->token,
'desc' => $this->module->l('Add new form'),
'icon' => 'process-icon-new'
);
}
parent::initPageHeaderToolbar();
}
public function initToolbar()
{
switch ($this->display) {
default: // list
$this->toolbar_btn['new'] = array(
'href' => self::$currentIndex . '&add' . $this->table . '=1&token=' . $this->token,
'desc' => $this->module->l('Add New Form')
);
}
unset($this->toolbar_btn['back']);
}
public function renderList()
{
if(empty($this->freshmailSettings->api_token)){
$this->errors[] = $this->module->l('To use this feature You have to enable synchronization with FreshMail');
return;
}
$this->fields_list = array(
'id_freshmail_form' => array(
'title' => 'ID',
'align' => 'center',
'width' => 25
),
'form_hash' => array(
'title' => $this->module->l('Name'),
'width' => 'auto',
'callback' => 'getName'
),
'hook' => array(
'title' => $this->module->l('Hook'),
'width' => 'auto'
),
'active' => array(
'title' => $this->module->l('Active'),
'width' => 'auto'
),
);
// Adds an Edit button for each result
$this->addRowAction('edit');
// Adds a Delete button for each result
$this->addRowAction('delete');
$this->specificConfirmDelete = $this->l('Delete selected items?', array(), 'Admin.Notifications.Warning');
if (!($this->fields_list && is_array($this->fields_list))) {
return false;
}
$this->getList($this->context->language->id);
foreach ($this->_list as $k => $v) {
if (isset($v['active'])) {
if ((int)$this->_list[$k]['active'] == 0) {
$this->_list[$k]['active'] = $this->module->l('Disabled');
} else {
$this->_list[$k]['active'] = $this->module->l('Enabled');
}
if (isset($v['position']) && isset(self::$POSITION[$this->_list[$k]['position']])) {
$this->_list[$k]['position'] = $this->module->l(self::$POSITION[$this->_list[$k]['position']]);
}
}
}
// If list has 'active' field, we automatically create bulk action
if (isset($this->fields_list) && is_array($this->fields_list) && array_key_exists('active', $this->fields_list)
&& !empty($this->fields_list['active'])) {
if (!is_array($this->bulk_actions)) {
$this->bulk_actions = array();
}
}
$helper = new HelperList();
// Empty list is ok
if (!is_array($this->_list)) {
$this->displayWarning($this->module->l('Bad SQL query', 'Helper') . '<br />' . htmlspecialchars($this->_list_error));
return false;
}
$this->setHelperDisplay($helper);
$helper->simple_header = true;
$helper->_default_pagination = $this->_default_pagination;
$helper->_pagination = $this->_pagination;
$helper->tpl_vars = $this->getTemplateListVars();
// For compatibility reasons, we have to check standard actions in class attributes
foreach ($this->actions_available as $action) {
if (!in_array($action, $this->actions) && isset($this->$action) && $this->$action) {
$this->actions[] = $action;
}
}
$helper->has_value = false;
$helper->is_cms = $this->is_cms;
$helper->sql = $this->_listsql;
$list = $helper->generateList($this->_list, $this->fields_list);
return $list . $this->context->smarty->fetch(_PS_MODULE_DIR_ . $this->module->name . '/views/templates/admin/forms.tpl');
}
private function valid($action = 'add')
{
$this->requiredFields = array('name', 'position');
foreach ($this->requiredFields as $k => $v) {
if (!empty($v)) {
$value = Tools::getValue($v);
if (empty($value)) {
$title = ucfirst($this->fields_list[$v]['title']);
$label = $title . $this->module->l(' is required!') . ' -> ' . $v;
$this->errors[] = Tools::displayError($label);
}
}
}
if (is_array($this->errors) && count($this->errors)) {
$this->action = $action;
return false;
}
return true;
}
// This method generates the Add/Edit form
public function renderForm()
{
$hooks = [
[
'hook' => 'displayFooterProduct',
'title' => $this->module->l('Product footer'),
'description' => $this->module->l('This hook adds new blocks under the product\'s description')
],
[
'hook' => 'displayHeader',
'title' => $this->module->l('Added in the header of every page'),
'description' => $this->module->l('This hook adds new blocks in header')
],
[
'hook' => 'displayHome',
'title' => $this->module->l('Homepage content'),
'description' => $this->module->l('This hook displays new elements on the homepage')
],
[
'hook' => 'displayRightColumnProduct',
'title' => $this->module->l('New elements on the product page (right column)'),
'description' => $this->module->l('This hook displays new elements in the right-hand column of the product page')
],
[
'hook' => 'displayLeftColumnProduct',
'title' => $this->module->l('New elements on the product page (left column)'),
'description' => $this->module->l('This hook displays new elements in the left-hand column of the product page')
],
[
'hook' => 'displayTop',
'title' => $this->module->l('Top of pages'),
'description' => $this->module->l('This hook displays additional elements at the top of your pages')
],
[
'hook' => 'freshmailForm',
'title' => $this->module->l('Custom hook'),
'description' => $this->module->l('You can add this hook in every place You want')
]
];
foreach ($hooks as &$hook){
$hook['title'] = $hook['hook'] . ' | '.$hook['title'];
}
$this->fields_form = [
'legend' => [
'title' => $this->module->l('Forms and additional fields'),
],
'input' => [
[
'type' => 'select',
'label' => $this->module->l('Hook'),
'name' => 'hook',
'required' => true,
'desc' => $this->module->l('Used hook'),
'class' => 'fixed-width-xxl',
'options' => [
'query' => $hooks,
'id' => 'hook',
'name' => 'title'
],
],
[
'type' => 'select',
'label' => $this->module->l('Form in Freshmail'),
'name' => 'form_hash',
'required' => true,
'desc' => $this->module->l(''),
'class' => 'fixed-width-xxl',
'options' => [
'query' => $this->fmForms,
'id' => 'id_hash',
'name' => 'name'
],
],
[
'type' => 'switch',
'label' => $this->module->l('Enable form'),
'name' => 'active',
'required' => true,
'class' => 'switch prestashop-switch',
'is_bool' => true,
'values' => [
[
'id' => 'active_on',
'value' => 1,
'label' => $this->module->l('Enabled')
],
[
'id' => 'active_off',
'value' => 0,
'label' => $this->module->l('Disabled')
]
],
],
],
'submit' => [
'title' => $this->module->l('Save'),
'class' => 'btn btn-default pull-right'
],
'buttons' => [
[
'href' => AdminController::$currentIndex . '&token=' . Tools::getAdminTokenLite('AdminFreshmailFormConfig'),
'title' => $this->module->l('Back to list'),
'icon' => 'process-icon-back'
]
]
];
return parent::renderForm();
}
public function displayEditLink($token = null, $id, $name = null)
{
$tpl = $this->createTemplate('helpers/list/list_action_edit.tpl');
if (!array_key_exists('Edit', self::$cache_lang)) {
self::$cache_lang['Edit'] = $this->module->l('Edit', 'Helper');
}
$href = self::$currentIndex . '&' . $this->identifier . '=' . $id . '&update' . $this->table . '&token=' . ($token != null ? $token : $this->token);
if ($this->display == 'view') {
$href = Context::getContext()->link->getAdminLink('AdminCustomers') . '&id_customer=' . (int)$id . '&updatecustomer';
}
$tpl->assign(array(
'href' => $href,
'action' => self::$cache_lang['Edit'],
'id' => $id
));
return $tpl->fetch();
}
public function checkAccess($disable = false)
{
return true;
}
public function viewAccess($disable = false)
{
return true;
}
public function displayAjax()
{
$return = array(
'hasError' => true,
'errors' => 'Error'
);
die(Tools::jsonEncode($return));
}
public function displayAjaxUpdateFieldsForm()
{
$this->ajax = true;
$hash = Tools::getValue('hash');
$fieldService = new FieldService(new \FreshMail\Repository\FieldRepository());
$fieldsApiArray = $this->freshmail->getAllFieldsByIdHashList($hash);
$idForm = Tools::getValue('id_form');
$fieldsDbArray = !empty($idForm) ? $fieldService->getFieldsByIdForm($idForm) : [];
$fields = [];
foreach ($fieldsDbArray as $key => $value) {
$fields[$value['hash']] = [
'id' => $value['id'],
'displayname' => $value['displayname'],
'hash' => $value['hash'],
'name' => $value['name'],
'tag' => $value['tag'],
'require_field' => $value['require_field'],
'include_field' => $value['include_field']
];
}
foreach ($fieldsApiArray as $key => $value) {
if (!isset($fields[$value['hash']])) {
$fields[$value['hash']] = $fieldsApiArray[$key];
}
}
if (!$this->checkExistField('email', $fields)) {
$fields[] = array(
'displayname' => "E-mail",
'hash' => $hash,
'name' => "E-mail",
'tag' => "email",
'require_field' => 1,
'include_field' => 1
);
}
$result = array(
'status' => 'OK',
'fields' => $fields
);
echo Tools::jsonEncode($result);
}
private function checkExistField($fieldName, $fields)
{
foreach ($fields as $key => $value) {
if ($fieldName == $value['tag']) {
return true;
}
}
return false;
}
public function beforeAdd($form)
{
$form->id_shop = $this->context->shop->id;
}
public function processDelete()
{
$id = (int)Tools::getValue('id_freshmail_form');
$form = new FreshMail\Entity\Form($id);
$form->delete();
Tools::redirectAdmin($this->context->link->getAdminLink('AdminFreshmailFormConfig') . '&conf=1');
}
public function getName($value, $row){
return isset($this->fmForms[$value]) ? $this->fmForms[$value]['name'] : '';
}
}

View File

@@ -0,0 +1,112 @@
<?php
use FreshMail\Repository\FreshmailSettings;
require_once __DIR__ . '/AdminFreshmailBase.php';
class AdminFreshmailSubscribersController extends AdminFreshmailBaseController
{
public function __construct()
{
$this->bootstrap = true;
$this->table = 'freshmail_list_email';
$this->className = 'FreshMail\Entity\Email';
$this->lang = false;
$this->deleted = false;
$this->colorOnBackground = false;
$this->multishop_context = Shop::CONTEXT_ALL;
$this->imageType = 'gif';
$this->fieldImageSettings = [
'name' => 'icon',
'dir' => 'os',
];
$this->display = 'list';
parent::__construct();
$this->fields_list = [
'email' => [
'title' => $this->module->l('Email'),
'maxlength' => 30,
'remove_onclick' => true
],
'add_date' => [
'title' => $this->module->l('Date add'),
],
'status' => [
'title' => $this->module->l('Subscriber status'),
'remove_onclick' => true
]
];
$hash = (new FreshmailSettings)->findForShop($this->context->shop->id)->subscriber_list_hash;
$this->_where = ' AND hash_list = "' . pSQL($hash) . '"';
}
public function init()
{
parent::init();
$freshmailSettings = (new FreshmailSettings())->findForShop($this->context->shop->id);
if(empty($freshmailSettings->api_token)){
$this->errors[] = $this->module->l('To use this feature You have to enable synchronization with FreshMail');
return;
}
if(!in_array($freshmailSettings->subscriber_list_hash, $this->freshmail->getAllHashList() )){
Tools::redirectAdmin(
$this->context->link->getAdminLink('AdminFreshmailConfig')
);
}
$ajr = new \FreshMail\Repository\AsyncJobs(Db::getInstance());
if(!empty($ajr->getRunningJobs($freshmailSettings->api_token))){
$this->warnings[] = $this->module->l('Synchronization is already pending');
}
if(Tools::getIsset('trigger_sync')){
if(empty($ajr->getRunningJobs($freshmailSettings->api_token))){
\FreshMail\Tools::triggerSynchronization($freshmailSettings->subscriber_list_hash);
$this->confirmations[] = $this->module->l('Synchronization has started');
}
}
}
public function renderList()
{
$freshmailSettings = (new FreshmailSettings())->findForShop($this->context->shop->id);
$this->context->smarty->assign([
'synchronization_url' => $this->context->link->getBaseLink(null, true).'modules/freshmail/cron/synchronize.php?hash='.$freshmailSettings->subscriber_list_hash . '&token='.Freshmail::getCronToken(),
'synchronization_cron' => _PS_MODULE_DIR_.'freshmail/cron/synchronize.php'
]);
return $this->context->smarty->fetch(_PS_MODULE_DIR_.$this->module->name. '/views/templates/admin/manage.tpl')
. parent::renderList()
. $this->context->smarty->fetch(_PS_MODULE_DIR_.$this->module->name. '/views/templates/admin/subscriber_list.tpl')
;
}
public function initPageHeaderToolbar()
{
if (!empty($this->display) && 'list' == $this->display) {
$this->page_header_toolbar_btn['trigger_sync'] = array(
'href' => self::$currentIndex . '&trigger_sync&token=' . $this->token,
'desc' => $this->module->l('Start synchronization'),
'icon' => 'process-icon-refresh',
);
}
parent::initPageHeaderToolbar();
}
public function initToolbar()
{
parent::initToolbar();
unset($this->toolbar_btn['new']);
}
}

View File

@@ -0,0 +1,222 @@
<?php
use FreshMail\ApiV2\UnauthorizedException;
use FreshMail\FreshmailApiV3;
use FreshMail\Repository\FreshmailSettings;
class AdminFreshmailWizardController extends ModuleAdminController
{
private $settingRepository;
const NEW_LIST_KEY = 'create_new';
public function __construct()
{
$this->bootstrap = true;
parent::__construct();
$this->templateFile = _PS_MODULE_DIR_ . $this->module->name . '/views/templates/admin/wizard.tpl';
$this->settingRepository = new FreshmailSettings();
}
public function run()
{
if ($step = Tools::getValue('step')) {
if (method_exists($this, $step)) {
echo json_encode($this->$step());
}
}
$this->context->smarty->assign([
'is_wizard_available' => $this->isWizardAvailable(),
'links' => $this->getLinks(),
'module_version' => $this->module->version,
'specific_price_rules' => \FreshMail\Tools::getSpecificPriceRules($this->context->shop->id)
]);
return $this->context->smarty->fetch($this->templateFile);
}
private function getLinks()
{
return [
'settings' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'settings']),
'connect' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'connect']),
'save' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'save']),
'lists' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'getLists']),
'register' => 'https://app.freshmail.com/pl/auth/login',
'help' => 'https://freshmail.pl/podrecznik-uzytkownika/',
'success_redirect' => $this->context->link->getAdminLink('AdminFreshmailConfig', true, [], ['step' => 'getLists']),
'abandon_carts_redirect' => $this->context->link->getAdminLink('AdminFreshmailAbandonedCartConfig', true, []),
'synchronize_link' => $this->context->link->getBaseLink(null, true).'modules/'.$this->module->name.'/cron/synchronize.php?token='.$this->module->getCronToken().'&hash=',
'activate_package' => $this->context->link->getAdminLink('AdminFreshmailWizard', true, [], ['step' => 'success']),
'base_url' => $this->context->link->getBaseLink(null, true),
];
}
private function isWizardAvailable()
{
return true;
}
private function settings()
{
$settings = $this->settingRepository->findForShop($this->context->shop->id);
$this->module->loadFreshmailApi();
$freshailApi = new \FreshMail\ApiV2\Client($settings->api_token);
$isLogged = false;
try {
$status = $freshailApi->doRequest('ping');
$isLogged = true;
} catch (UnauthorizedException $unauthorizedException) {
}
return [
'logged_in' => $isLogged,
'api_token' => $settings->api_token,
'smtp' => (bool)$settings->smtp,
'synchronize' => (bool)$settings->synchronize,
'id_specific_price_rule' => ((int)$settings->id_specific_price_rule > 0) ? (int)$settings->id_specific_price_rule : '',
'synchronize_list' => 'create_new'
];
}
private function connect()
{
$this->module->loadFreshmailApi();
$apiV2 = new \FreshMail\ApiV2\Client(Tools::getValue('api_token'));
try {
$apiV2->doRequest('ping');
} catch (UnauthorizedException $unauthorizedException) {
header("HTTP/1.1 401 Unauthorized");
return [
'success' => false,
'message' => $this->module->l('Please provide a valid token')
];
}
$fs = $this->settingRepository->findForShop($this->context->shop->id);
$fs->api_token = Tools::getValue('api_token');
$fs->id_shop = $this->context->shop->id;
$fs->save();
return [
'success' => true,
'message' => $this->module->l('Correctly connected to the freshmail account')
];
}
private function getLists()
{
$fs = $this->settingRepository->findForShop($this->context->shop->id);
$freshmail = new \FreshMail\Freshmail($fs->api_token);
try {
$list = array_merge(
[[
'subscriberListHash' => self::NEW_LIST_KEY,
'name' => 'Prestashop - ' . $this->context->shop->name
]],
$freshmail->getLists()
);
return [
'success' => true,
'data' => $list
];
} catch (Exception $e) {
return [
'success' => false,
'message' => $this->module->l('Please provide a valid token')
];
}
// /rest/
}
private function save()
{
$fs = $this->settingRepository->findForShop($this->context->shop->id);
if(empty($fs->api_token)){
\FreshMail\Installer\Tabs::install($this->module);
return $this->saveWithoutToken($fs);
}
\FreshMail\Installer\Tabs::install($this->module, 'extended');
return $this->saveWithToken($fs);
}
private function saveWithoutToken(\Freshmail\Entity\FreshmailSetting $fs)
{
$fs->wizard_completed = 1;
$fs->id_shop = $this->context->shop->id;
$fs->save();
return [
'success' => true,
'message' => $this->module->l('Configuration saved'),
'synchronize' => 0,
];
}
private function saveWithToken(\Freshmail\Entity\FreshmailSetting $fs)
{
$fs->smtp = (Tools::getValue('smtp') == 'true') ? 1 : 0;
if (1 == $fs->smtp) {
\FreshMail\Tools::setShopSmtp($fs->api_token);
}
$fs->synchronize = (Tools::getValue('synchronize') == 'true') ? 1 : 0;
$listHash = Tools::getValue('synchronize_list');
$fm = new \FreshMail\Freshmail($fs->api_token);
if (self::NEW_LIST_KEY == Tools::getValue('synchronize_list', '')) {
$name = 'Prestashop - ' . $this->context->shop->name;
$description = \Context::getContext()->getTranslator()->trans('List from ', [], 'Modules.freshmail').$this->context->shop->name;
$listHash = $fm->addList($name, $description);
}
if(!$fm->hasFieldWithTag($listHash, Freshmail::NAME_TAG)) {
$fm->addFieldToList($listHash, Freshmail::NAME_TAG, $this->trans('First name', [],'Admin.Global'));
}
if (1 == $fs->synchronize) {
}
$fs->subscriber_list_hash = $listHash;
$fs->wizard_completed = 1;
$fs->id_specific_price_rule = (int)Tools::getValue('id_specific_price_rule');
$fs->save();
$apiV3 = new FreshmailApiV3($fs->api_token);
try {
$apiV3->sendIntegrationInfo();
} catch (Exception $e) {
return [
'success' => false,
'message' => $e->getMessage()
];
}
// \FreshMail\Tools::sendWizardSuccessMail();
return [
'success' => true,
'message' => $this->module->l('Configuration saved'),
'synchronize' => (int)$fs->synchronize,
];
}
}