-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmailjet.php
2357 lines (2089 loc) · 86 KB
/
mailjet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <[email protected]>
* @copyright 2007-2017 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/* Security */
if (!defined('_PS_VERSION_')) {
exit;
}
require_once _PS_MODULE_DIR_ . 'mailjet/classes/MailJetTranslate.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/MailJetTemplate.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/MailJetPages.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/MailJetEvents.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/MailJetLog.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/Segmentation.php';
if (version_compare(_PS_VERSION_, '1.7', '<')) {
if (version_compare(_PS_VERSION_, '1.6.1.5', '>=')) {
include_once _PS_CORE_DIR_ . '/tools/swift/swift_required.php';
} else {
include_once _PS_SWIFT_DIR_ . 'Swift.php';
include_once _PS_SWIFT_DIR_ . 'Swift/Connection/SMTP.php';
}
}
require_once _PS_MODULE_DIR_ . 'mailjet/classes/hooks/synchronization/SynchronizationAbstract.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/hooks/synchronization/Initial.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/hooks/synchronization/SingleUser.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/hooks/synchronization/Segment.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/hooks/synchronization/ContactProperties.php';
require_once _PS_MODULE_DIR_ . 'mailjet/classes/hooks/Events.php';
class Mailjet extends Module
{
private const DEFAULT_MAIL_OPTION = 1;
public $errors_list = [];
public $page_name;
public $module_access = [];
public $mj_template = null;
public $mj_pages = null;
public $segmentation = null;
public $mj_mail_server = 'in-v3.mailjet.com';
public $mj_mail_port = 587;
/**
* @return mixed|string
*/
public static function setMjMailServer()
{
return (new Mailjet())->mj_mail_server;
}
/**
* @return int|mixed
*/
public static function setMjMailPort()
{
return (new Mailjet())->mj_mail_port;
}
/* Default account settings */
public $account = [
'TOKEN' => '', /* Used for ajax security */
/* 'TOKEN_{id_customer}' The one used to display iframe */
'API_KEY' => '',
'SECRET_KEY' => '',
/* 'IP' => '', IP_{id_employee} */
/* LAST_TIMESTAMP => LAST_TIMESTAMP_{id_employee} */
'EMAIL' => '',
'PASSWD' => '',
'ACTIVATION' => 0,
'AUTHENTICATION' => 0,
'MASTER_LIST_SYNCHRONIZED' => 0,
'MASTER_LIST_ID' => 0,
];
/* Triggers parameters */
public $triggers = [
'active' => 0,
'trigger' => [
1 => ['active' => 0],
2 => ['active' => 0],
3 => ['active' => 0],
4 => ['active' => 0],
5 => ['active' => 0],
6 => ['active' => 0],
7 => ['active' => 0],
8 => ['active' => 0],
9 => ['active' => 0]
]
];
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function __construct()
{
$this->account = json_decode(json_encode($this->account));
// Default module variable
$this->name = 'mailjet';
$this->displayName = 'Mailjet';
$this->description = $this->l('Create contact lists and client segment groups, drag-n-drop newsletters, define client re-engagement triggers, follow and analyze all email user interaction, minimize negative user engagement events(blocked, unsubs and spam) and optimise deliverability and revenue generation. Get started today with 6000 free emails per month.');
$this->author = 'PrestaShop';
$this->version = '3.6.1';
$this->module_key = 'c81a68225f14a65239de29ee6b78d87b';
$this->tab = 'advertising_marketing';
// Parent constructor
parent::__construct();
// Backward compatibility
if (version_compare(_PS_VERSION_, '1.5', '<')) {
include _PS_MODULE_DIR_ . $this->name . '/backward_compatibility/backward.php';
}
if ($this->active) {
$this->module_access['uri'] = __PS_BASE_URI__ . 'modules/' . $this->name . '/';
$this->module_access['dir'] = _PS_MODULE_DIR_ . $this->name . '/';
$this->initAccountSettings();
MailJetLog::init();
$this->initTriggers();
}
$this->mj_pages = $this->getMjPages($this->account->AUTHENTICATION);
$this->initContext();
}
/**
* @return void
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
private function initContext()
{
if (version_compare(_PS_VERSION_, '1.4', '>=') && class_exists('Context')) {
$this->context = Context::getContext();
} else {
$this->context = new StdClass();
$this->context->smarty = $GLOBALS['smarty'];
$this->context->cookie = $GLOBALS['cookie'];
$this->context->language = new Language($this->context->cookie->id_lang);
$this->context->currency = new Currency($this->context->cookie->id_lang);
$this->context->link = new Link();
$this->context->shop = new Shop();
}
if (!isset($this->context->shop->domain)) {
$this->context->shop->domain = Configuration::get('PS_SHOP_DOMAIN');
}
}
/*
* * Install / Uninstall Methods
*/
/**
* @return bool
* @throws PrestaShopException
*/
public function install()
{
$this->account = ($account = json_decode(Configuration::get('MAILJET'))) ? $account : $this->account;
$this->account->TOKEN = Tools::getValue('token');
$this->updateAccountSettings();
// Install SQL
$sql = [];
include _PS_MODULE_DIR_ . 'mailjet/sql/install.php';
foreach ($sql as $s) {
if (!Db::getInstance()->execute($s)) {
return false;
}
}
// Install Tab
if (version_compare(_PS_VERSION_, '1.7', '>=')) {
$tabMain = new Tab();
$tabMain->name = [];
foreach (Language::getLanguages() as $lang) {
$tabMain->name[$lang['id_lang']] = $this->l('Mailjet');
}
if ($fr = Language::getIdByIso('fr')) {
$tabMain->name[$fr] = $this->l('Mailjet');
}
$tabMain->class_name = 'AdminMailjetMain';
$tabMain->id_parent = 0;
$tabMain->module = $this->name;
$tabMain->active = 1;
$tabMain->add();
$tab = new Tab();
$tab->class_name = 'AdminMailjet';
$tab->name = [];
foreach (Language::getLanguages() as $lang) {
$tab->name[$lang['id_lang']] = $this->l('Configure');
}
if ($fr = Language::getIdByIso('fr')) {
$tab->name[$fr] = $this->l('Configure');
}
$tab->id_parent = $tabMain->id;
$tab->module = $this->name;
$tab->active = 1;
$tab->add();
} else {
$tab = new Tab();
$tab->class_name = 'AdminMailjet';
$tab->name = [];
foreach (Language::getLanguages() as $lang) {
$tab->name[$lang['id_lang']] = $this->l('Mailjet');
}
if ($fr = Language::getIdByIso('fr')) {
$tab->name[$fr] = $this->l('Mailjet');
}
$tab->id_parent = (int)Tab::getIdFromClassName('AdminTools');
$tab->module = $this->name;
$tab->active = 1;
$tab->add();
}
$this->createTriggers();
Configuration::updateValue('MJ_ALLEMAILS', 1);
$updateOrderHook = 'updateOrderStatus';
if (version_compare(_PS_VERSION_, '8', '>=')) {
$updateOrderHook = 'actionOrderStatusUpdate';
}
return (
parent::install()
&& $this->loadConfiguration()
&& $this->registerHook('actionAdminCustomersControllerSaveBefore')
&& $this->registerHook('actionAdminCustomersControllerSaveAfter')
&& $this->registerHook('actionAdminCustomersControllerStatusAfter')
&& $this->registerHook('actionAdminCustomersControllerDeleteBefore')
&& $this->registerHook('actionExportGDPRData')
&& $this->registerHook('actionObjectCustomerDeleteBefore')
&& $this->registerHook('actionObjectCustomerUpdateAfter')
&& $this->registerHook('adminCustomers')
&& $this->registerHook('authentication')
&& $this->registerHook('displaybackOfficeHeader')
&& $this->registerHook('cancelProduct')
&& $this->registerHook('cart')
&& $this->registerHook('createAccount')
&& $this->registerHook('header')
&& $this->registerHook('invoice')
&& $this->registerHook('newOrder')
&& $this->registerHook('orderConfirmation')
&& $this->registerHook('orderReturn')
&& $this->registerHook('orderSlip')
&& $this->registerHook('registerGDPRConsent')
&& $this->registerHook($updateOrderHook)
&& $this->registerHook('updateQuantity')
&& $this->registerHook('actionNewsletterRegistrationAfter')
&& $this->registerHook('actionNewsletterRegistrationBefore')
&& $this->registerHook('actionControllerInitBefore')
);
}
// Export customer gdpr data
/**
* @param $customer
* @return false|string
* @throws Mailjet_ApiException
*/
public function hookActionExportGDPRData($customer)
{
$email = $customer['email'];
if (empty($email)) {
return json_encode($this->l('Invalid email format.'));
}
$api = MailjetTemplate::getApi();
$contactData = $api->getContactData($email);
try {
$contactByEmail = $api->getContactByEmail($email);
$creationDate = !empty($contactByEmail->Data[0] && $contactByEmail->Data[0]->CreatedAt) ? new DateTime($contactByEmail->Data[0]->CreatedAt) : '';
$lastCampaignSent = !empty($contactByEmail->Data[0] && $contactByEmail->Data[0]->CreatedAt) ? new DateTime($contactByEmail->Data[0]->CreatedAt) : '';
} catch (Mailjet_ApiException $e) {
return json_encode($this->l('No data'));
}
$data = [];
$firstname = '';
$lastname = '';
if (is_object($contactData) && $contactData->Count > 0 && isset($contactData->Data[0]) && isset($contactData->Data[0]->Data)) {
$contactDataProperties = $contactData->Data[0]->Data;
foreach ($contactDataProperties as $propertyData) {
if ($propertyData->Name === 'firstname') {
$firstname = $propertyData->Value;
continue;
}
if ($propertyData->Name === 'lastname') {
$lastname = $propertyData->Value;
continue;
}
}
$data[] = [
'Email' => $email,
'Firstname' => $firstname,
'Lastname' => $lastname,
'Last campaign sent' => $lastCampaignSent->format('Y-m-d H:i:s'),
'Creation date' => $creationDate->format('Y-m-d H:i:s')
];
return json_encode($data);
}
return json_encode($this->l('No data'));
}
/**
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function uninstall()
{
$fileTranslationCache = $this->_path . '/translations/translation_cache.txt';
if (file_exists($fileTranslationCache)) {
unlink($fileTranslationCache);
}
// Uninstall SQL
$sql = [];
include _PS_MODULE_DIR_ . 'mailjet/sql/uninstall.php';
foreach ($sql as $s) {
if (!Db::getInstance()->execute($s)) {
return false;
}
}
// Uninstall Tab
$tab = new Tab((int)Tab::getIdFromClassName('AdminMailjet'));
$tab->delete();
if (version_compare(_PS_VERSION_, '1.7', '>=')) {
$tabMain = new Tab((int)Tab::getIdFromClassName('AdminMailjetMain'));
$tabMain->delete();
}
// Deletes and unsets all Mailjet module related settings
Configuration::deleteByName('MAILJET');
Configuration::deleteByName('MJ_TRIGGERS');
Configuration::deleteByName('MJ_ALLEMAILS');
$this->configToDefault();
unset($this->account);
unset($this->triggers);
return parent::uninstall();
}
/**
* @return void
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function hookHeader()
{
if (Tools::getIsset('tokp')) {
if (!$this->context->cart->id) {
$this->context->cart->add();
$this->context->cookie->id_cart = $this->context->cart->id;
}
Db::getInstance()->execute(
'REPLACE INTO `' . _DB_PREFIX_ . 'mj_roi_cart`(id_cart, token_presta)
VALUES(' . $this->context->cart->id . ', \'' . pSQL(Tools::getValue('tokp')) . '\')'
);
}
/*
* RM: 29680 - add prestashop newsletter sunscribers to Mailjet master contact list
*/
if (Tools::isSubmit('submitNewsletter')) {
try {
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
$masterListId = $initialSynchronization->getAlreadyCreatedMasterListId();
// UnSubscribe
if (Tools::getValue('action') == '1') {
// Remove customer from all lists(and segment lists)
$initialSynchronization->remove(Tools::getValue('email'), $masterListId);
} elseif (Tools::getValue('action') == '0') { // Subscribe - to the Mailjet master list
$initialSynchronization->subscribe(Tools::getValue('email'), $masterListId);
}
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
}
/**
* @param $params
* @return string|void
*/
public function hookNewOrder($params)
{
if (empty($params['customer']->id)) {
return '';
}
$this->checkAutoAssignment((int)$params['customer']->id);
if (empty($params['order']->id_cart)) {
return '';
}
$sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'mj_roi_cart`
WHERE id_cart = ' . (int)$params['order']->id_cart;
if ($tokp = Db::getInstance()->getRow($sql)) {
// On enregistre le ROI
$sql = 'SELECT campaign_id FROM ' . _DB_PREFIX_ . 'mj_campaign WHERE token_presta = \'' .
pSQL($tokp['token_presta']) . "'";
$campaign = Db::GetInstance()->GetRow($sql);
if (!empty($campaign)) {
$sql = 'REPLACE INTO ' . _DB_PREFIX_ . 'mj_roi (campaign_id, id_order, total_paid, date_add)
VALUES (' . (int)$campaign['campaign_id'] . ', ' . (int)$params['order']->id . ', ' .
(float)$params['order']->total_paid . ', NOW())';
Db::GetInstance()->Execute($sql);
}
}
}
/**
* @param $params
* @return void
*/
public function hookOrderConfirmation($params)
{
//TODO implement hook in new version
}
/**
* @return void
*/
public function hookActionControllerInitBefore()
{
if (Tools::isSubmit('subscribedmerged') && $this->isAccountSet()) {
$id = Tools::getValue('id');
if (preg_match('/(^N)/', $id)) {
$id = (int) Tools::substr($id, 1);
if (version_compare(_PS_VERSION_, '1.7', '<')) {
$sql = 'SELECT `email` FROM ' . _DB_PREFIX_ . 'newsletter WHERE `id` = \'' . pSQL($id) . '\'';
} else {
$sql = 'SELECT `email` FROM ' . _DB_PREFIX_ . 'emailsubscription WHERE `id` = \'' . pSQL($id) . '\'';
}
if ($subscriber = Db::getInstance()->getRow($sql)) {
if (!empty($subscriber['email'])) {
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
$masterListId = $initialSynchronization->getAlreadyCreatedMasterListId();
$initialSynchronization->unsubscribe($subscriber['email'], $masterListId);
}
}
}
}
}
/**
* @return false|string
* @throws HooksSynchronizationException
*/
public function hookDisplayBackOfficeHeader()
{
if (Tools::getIsset('sync_list')) {
$sync = new HooksSynchronizationInitial(MailjetTemplate::getApi());
$listId = $sync->getAlreadyCreatedMasterListId();
$sync->synchronizeSubscribers($listId);
$synchronizationSegment = new HooksSynchronizationSegment(MailjetTemplate::getApi());
$synchronizationSegment->createPredefinedSegmentList();
}
// Process subscribers changed by Admin through the BackOffice
if (Tools::isSubmit('subscribedmerged') && $this->isAccountSet()) {
$id = Tools::getValue('id');
if (preg_match('/(^N)/', $id)) {
$id = (int) Tools::substr($id, 1);
if (version_compare(_PS_VERSION_, '1.7', '<')) {
$sql = 'SELECT `email` FROM ' . _DB_PREFIX_ . 'newsletter WHERE `id` = \'' . pSQL($id) . '\'';
} else {
$sql = 'SELECT `email` FROM ' . _DB_PREFIX_ . 'emailsubscription WHERE `id` = \'' . pSQL($id) . '\'';
}
if ($subscriber = Db::getInstance()->getRow($sql)) {
if (!empty($subscriber['email'])) {
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
$masterListId = $initialSynchronization->getAlreadyCreatedMasterListId();
$initialSynchronization->remove($subscriber['email'], $masterListId);
}
}
}
} // End Subscribers processing
$controller = Tools::getValue('tab');
if (empty($controller)) {
$controller = Tools::getValue('controller');
}
if (!in_array($controller, ['AdminModules', 'adminmodules', 'AdminCustomers'])) {
return '';
}
if (Tools::getValue('configure') != $this->name) {
return '';
}
$smarty_page = [];
$nobug = [];
foreach ($this->mj_pages->getPages() as $name => $value) {
$smarty_page['MJ_' . $name] = $name;
$nobug = $value;
}
$this->context->controller->addCss($this->_path . '/views/css/style.css');
$this->context->controller->addCSS($this->_path . '/views/css/bo.css');
$this->context->controller->addCSS($this->_path . '/views/css/bundlejs_prestashop.css');
if (version_compare(_PS_VERSION_, '8', '<')) {
$this->context->controller->addJquery();
}
$this->context->controller->addJs($this->_path . '/views/js/jquery.timer.js');
$this->context->controller->addJs($this->_path . '/views/js/bo.js');
$this->context->controller->addJs($this->_path . '/views/js/events.js');
$this->context->controller->addJs($this->_path . '/views/js/functions.js');
$this->context->controller->addJs($this->_path . '/views/js/main.js');
$this->context->controller->addJs($this->_path . '/views/js/bundlejs_prestashop.js');
$api = MailjetTemplate::getApi();
$infos = $api->getUser();
$mjSenders = $api->getSenders(null, $infos);
$currentSender = Configuration::get('PS_SHOP_EMAIL');
$this->context->smarty->assign(
[
'MJ_base_dir' => $this->module_access['uri'],
'MJ_local_path' => $this->module_access['dir'],
'MJ_REQUEST_PAGE_TYPE' => MailJetPages::REQUEST_PAGE_TYPE,
'MJ_ADMINMODULES_TOKEN' => Tools::getAdminTokenLite('AdminModules'),
'MJ_available_pages' => $smarty_page,
'MJ_tab_page' => $this->mj_pages->getPages(MailJetPages::REQUIRE_PAGE),
'MJ_adminmodules_link' => $this->getAdminModuleLink([]),
'MJ_allemails_active' => Configuration::get('MJ_ALLEMAILS'),
'MJ_TOKEN' => $this->account->TOKEN,
'nobug' => $nobug,
'mjSenders' => $this->getOnlyEmailSenders($mjSenders),
'currentSender' => $currentSender
]
);
if ($this->isAccountSet()) {
$this->context->smarty->assign(
[
'MJ_tab_page' => $this->mj_pages->getPages(MailJetPages::REQUIRE_PAGE)
]
);
}
return $this->fetchTemplate('/views/templates/admin/', 'bo-header');
}
/**
* @param $sendersFromApi
* @return array
*/
private function getOnlyEmailSenders($sendersFromApi)
{
$emailSenders = [];
foreach ($sendersFromApi as $sender) {
if (strpos($sender->Email->Email, '*') === false) {
$emailSenders[] = $sender;
}
}
return $emailSenders;
}
/**
* New customer is created via Administration Panel
*
* @author atanas
* @param array $params
*/
public function hookActionAdminCustomersControllerSaveBefore()
{
$customer = new Customer(Tools::getValue('id_customer'));
Configuration::updateValue('PREVIOUS_MJ_USER_MAIL', $customer->email);
}
/**
* Just after new customer is created via Administration Panel
*
* @param array $params
*/
public function hookActionAdminCustomersControllerSaveAfter($params)
{
$customer = $params['return'];
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
if ($customer->active == 0) {
// Remove customer from all lists(and segment lists)
$initialSynchronization->removeFromAllLists($customer->email);
} else {
// Manage customer in his segment lists
$filter_ids = $this->newCheckAutoAssignment($customer->id);
foreach ($filter_ids as $filter_id => $result) {
$obj = new Segmentation();
$mailjetListID = $obj->getMailjetContactListId($filter_id);
if ($result) {
$initialSynchronization->addToList($customer, $mailjetListID);
} else {
// Remove customer from a list
$initialSynchronization->remove($customer->email, $mailjetListID);
}
}
// Add to the master list
if ($customer->newsletter == 1) {
$masterListId = $initialSynchronization->getAlreadyCreatedMasterListId();
$initialSynchronization->subscribe($customer->email, $masterListId);
}
}
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
/**
* Retrieve active segments
*/
private function getAutoAssigmentSegments()
{
$sql = 'SELECT *
FROM ' . _DB_PREFIX_ . 'mj_filter f
LEFT JOIN ' . _DB_PREFIX_ . 'mj_condition c ON c.id_filter = f.id_filter
WHERE f.assignment_auto = 1';
$rows = DB::getInstance()->executeS($sql);
if (!is_array($rows)) {
return $this;
}
$formatRows = [];
foreach ($rows as $row) {
$id_filter = (int) $row['id_filter'];
$formatRows[$id_filter]['mode'] = 0;
$formatRows[$id_filter]['replace_customer'] = (bool) $row['replace_customer'];
$formatRows[$id_filter]['name'] = $row['name'];
$formatRows[$id_filter]['description'] = $row['description'];
$formatRows[$id_filter]['idfilter'] = $id_filter;
$formatRows[$id_filter]['idgroup'] = $row['id_group'];
$formatRows[$id_filter]['rule_a'][] = $row['rule_a'];
$formatRows[$id_filter]['rule_action'][] = $row['rule_action'];
$formatRows[$id_filter]['baseSelect'][] = $row['id_basecondition'];
$formatRows[$id_filter]['sourceSelect'][] = $row['id_sourcecondition'];
$formatRows[$id_filter]['fieldSelect'][] = $row['id_fieldcondition'];
$formatRows[$id_filter]['data'][] = $row['data'];
$formatRows[$id_filter]['value1'][] = $row['value1'];
$formatRows[$id_filter]['value2'][] = $row['value2'];
}
return $formatRows;
}
/**
* Hook which is triggered right after customer account is changed - either by the customer himself via Frontend
* or by admin via Customers listing - click on 'Newsletter' checkbox in the listing
* (note that the Hook for customer profile edition by Admin is different -
* it is hookActionAdminCustomersControllerSaveAfter)
*
* @param array $params
*/
public function hookActionAdminCustomersControllerStatusAfter($params)
{
$customer = $params['return'];
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
$this->checkAutoAssignment($customer->id);
if ($customer->active == 0) {
$initialSynchronization->removeFromAllLists($customer->email);
} elseif ($customer->active == 1 && $customer->newsletter == 0) {
// Get all lists where customer is subscribed
$subsSegmentListsIds = $initialSynchronization->getSubscribedSegmentLists($customer->email);
// Unsubscribe user from all lists where he is subscribed
foreach ($subsSegmentListsIds as $listId) {
$initialSynchronization->unsubscribe($customer->email, $listId);
}
} elseif ($customer->active == 1 && $customer->newsletter == 1) {
$initialSynchronization->subscribe($customer);
}
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
/**
* User profile action
*
* @param array $params
*/
public function hookActionObjectCustomerUpdateAfter($params)
{
$customer = $params['object'];
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
$this->checkAutoAssignment($customer->id);
if ($customer->deleted == 1) {
$initialSynchronization->removeFromAllLists($customer->email);
} elseif ($customer->newsletter == 0) {
$initialSynchronization->unsubscribe($customer->email);
} elseif ($customer->active == 1 && $customer->newsletter == 1) {
$initialSynchronization->subscribe($customer);
}
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
/**
* @param $params
* @return void
*/
public function hookAdminCustomers($params)
{
//TODO implement in the future
}
public function hookActionObjectCustomerDeleteBefore($params)
{
$customer = $params['object'];
if (!$customer->id) {
return;
}
$singleUserSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
$singleUserSynchronization->remove($customer->email);
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
/**
*
* @author atanas
* @param array $params
*/
public function hookActionAdminCustomersControllerDeleteBefore()
{
$customer = new Customer(Tools::getValue('id_customer'));
if (!$customer->id) {
return;
}
$singleUserSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
$singleUserSynchronization->removeFromAllLists($customer->email);
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
/**
*
* @author atanas
* @param array $params
* @return boolean
*/
public function hookCreateAccount($params)
{
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
if ($params['newCustomer']->active == 1 && $params['newCustomer']->newsletter == 1) {
$initialSynchronization->subscribe($params['newCustomer']);
}
$this->checkAutoAssignment($params['newCustomer']->id);
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
return false;
}
}
/**
* @param array $params
* @return void
*/
public function hookActionNewsletterRegistrationAfter(array $params)
{
if (empty($params['error']) && $params['action'] == '0') {
try {
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
$masterListId = $initialSynchronization->getAlreadyCreatedMasterListId();
$initialSynchronization->subscribe($params['email'], $masterListId);
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
}
/**
* @param array $params
* @return void
*/
public function hookActionNewsletterRegistrationBefore(array $params)
{
if (empty($params['error']) && $params['action'] == '1') {
try {
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
$masterListId = $initialSynchronization->getAlreadyCreatedMasterListId();
$initialSynchronization->remove($params['email'], $masterListId);
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
}
}
}
/**
*
* @author atanas
* @param array $params
* @return boolean
*/
public function hookCustomerAccount($params)
{
$initialSynchronization = new HooksSynchronizationSingleUser(MailjetTemplate::getApi());
try {
if ($params['newCustomer']->active == 1 && $params['newCustomer']->newsletter == 1) {
$initialSynchronization->subscribe($params['newCustomer']);
}
} catch (Exception $e) {
$this->errors_list[] = $this->l($e->getMessage());
return false;
}
}
public function hookUpdateQuantity($params)
{
return $this->hookUpdateOrderStatus($params);
}
public function hookCart($params)
{
if (!empty($params['cart'])) {
$this->checkAutoAssignment((int)$params['cart']->id_customer);
}
return '';
}
public function hookAuthentication($params)
{
return $this->hookNewOrder($params);
}
public function hookInvoice($params)
{
return $this->hookUpdateOrderStatus($params);
}
public function hookUpdateOrderStatus($params)
{
if (isset($params['id_order'])) {
$sql = 'SELECT id_customer
FROM ' . _DB_PREFIX_ . 'orders
WHERE id_order = ' . (int)$params['id_order'];
if (($id_customer = (int)Db::getInstance()->getValue($sql)) > 0) {
$this->checkAutoAssignment($id_customer);
}
} elseif (isset($params['cart'])) {
$cart = $params['cart'];
if ($cart instanceof Cart && isset($cart->id_customer)) {
$this->checkAutoAssignment((int)$cart->id_customer);
}
}
return '';
}
/**
* @param $params
* @return string
*/
public function hookActionOrderStatusUpdate($params)
{
if (isset($params['id_order'])) {
$sql = 'SELECT id_customer
FROM ' . _DB_PREFIX_ . 'orders
WHERE id_order = ' . (int)$params['id_order'];
if (($id_customer = (int)Db::getInstance()->getValue($sql)) > 0) {
$this->checkAutoAssignment($id_customer);
}
} elseif (isset($params['cart'])) {
$cart = $params['cart'];
if ($cart instanceof Cart && isset($cart->id_customer)) {
$this->checkAutoAssignment((int)$cart->id_customer);
}
}
return '';
}
public function hookOrderSlip($params)
{
return $this->hookUpdateOrderStatus($params);
}
public function hookRegisterGDPRConsent($params)
{
//TODO Implement this later
}
public function hookOrderReturn($params)
{
return $this->hookUpdateOrderStatus($params);
}
public function hookCancelProduct($params)
{
return $this->hookUpdateOrderStatus($params);
}
public function newCheckAutoAssignment($id_customer)
{
$formatRows = $this->getAutoAssigmentSegments();
$filterIds = [];
foreach ($formatRows as $filterId => $formatRow) {
$obj = new Segmentation();
$sql = $obj->getQuery($formatRow, true, false, ' c.id_customer = ' . (int)$id_customer);
$result = DB::getInstance()->executeS($sql);
if ($result && !$obj->belongsToGroup($formatRow['idgroup'], $id_customer)) {
if ($formatRow['replace_customer']) {
$sql = 'DELETE FROM ' . _DB_PREFIX_ . 'customer_group WHERE id_customer = ' . (int)$id_customer;
Db::getInstance()->execute($sql);
}
Db::getInstance()->execute(
'INSERT INTO `' . _DB_PREFIX_ . 'customer_group` (`id_customer`, `id_group`)
VALUES ("' . ((int) $id_customer) . '", "' . (int) $formatRow['idgroup'] . '")'
);
} elseif (!$result && $obj->belongsToGroup($formatRow['idgroup'], $id_customer)) {
$sql = 'DELETE FROM ' . _DB_PREFIX_ . 'customer_group
WHERE id_group = ' . (int)$formatRow['idgroup'] . ' AND id_customer = ' . (int)$id_customer;
DB::getInstance()->execute($sql);
}
$filterIds[$filterId] = $result ? $filterId : false;
}
return $filterIds;
}
public function checkAutoAssignment($id_customer = 0)
{
$formatRows = $this->getAutoAssigmentSegments();
foreach ($formatRows as $filterId => $formatRow) {
$obj = new Segmentation();
$sql = $obj->getQuery($formatRow, true, false, ' c.id_customer = ' . (int)$id_customer);
$result = DB::getInstance()->executeS($sql);
if ($result && !$obj->belongsToGroup($formatRow['idgroup'], $id_customer)) {
if ($formatRow['replace_customer']) {
$sql = 'DELETE FROM ' . _DB_PREFIX_ . 'customer_group WHERE id_customer = ' . (int)$id_customer;
Db::getInstance()->execute($sql);
}
Db::getInstance()->execute(
'INSERT INTO `' . _DB_PREFIX_ . 'customer_group` (`id_customer`, `id_group`)