This repository has been archived by the owner on Apr 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
roihunter.php
635 lines (553 loc) · 21.7 KB
/
roihunter.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
<?php
/**
* Main class of module ROI Hunter
*
* LICENSE: The buyer can free use/edit/modify this software in anyway
* The buyer is NOT allowed to redistribute this module in anyway or resell it
* or redistribute it to third party
*
* @author ROI Hunter Easy
* @copyright 2019 ROI Hunter
* @license EULA
* @version 1.0
* @link https://easy.roihunter.com/
*/
if (!defined('_PS_VERSION_')) {
exit;
}
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/storage/storage.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/cookie/RhEasyCookieManager.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyProductDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyCategoryDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyCartDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyCartItemDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyOrderDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/dtos/RhEasyPageDto.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/classes/requests/ROIHunterRequestsManager.php');
require_once(_PS_MODULE_DIR_ . 'roihunter/enums/EPageType.php');
class Roihunter extends Module
{
const ROI_HUNTER_MODULE_NAME = 'roihunter';
const ROI_HUNTER_TAB_CLASS_NAME = 'AdminRoihunter';
const ROI_HUNTER_TAB_NAME = 'ROI Hunter Easy';
protected $config_form = false;
private $roiHunterStorage;
private $rhEasyCookieManager;
private $rhRequestsManager;
public function __construct()
{
$this->name = 'roihunter';
$this->tab = 'advertising_marketing';
$this->version = '1.2.1';
$this->author = 'ROI Hunter';
$this->need_instance = 1;
$this->bootstrap = true;
$this->module_key = '9e27146b6c90536cfb3e60a6adb4a054';
parent::__construct();
$this->displayName = $this->l('ROI Hunter Easy');
$this->description = $this->l('Re-engage your past visitors and gain new conversions with
dynamic remarketing ads on Google and dynamic product ads i.e. dynamic retargeting ads on Facebook.');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall ROI Hunter Easy module?');
$this->ps_versions_compliancy = ['min' => '1.6', 'max' => _PS_VERSION_];
$this->roiHunterStorage = ROIHunterStorage::getInstance();
$this->rhEasyCookieManager = RhEasyCookieManager::getInstance();
$this->rhRequestsManager = ROIHunterRequestsManager::getInstance();
}
public function install()
{
$retval = parent::install() &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('displayFooter') &&
$this->registerHook('actionCartSave') &&
$this->registerHook('displayBackOfficeHeader');
if (Tools::version_compare(_PS_VERSION_, '1.7.1', '>=')) {
$retval &= $this->registerHook('displayProductAdditionalInfo');
}
if ($retval) {
$this->installModuleTab();
$this->roiHunterStorage->setClientToken($this->getSecureToken());
}
return $retval;
}
public function uninstall()
{
$this->roiHunterStorage->setClientToken(null);
$this->uninstallModuleTab();
$this->roiHunterStorage->clearStorage();
$this->rhRequestsManager->onAppUninstall();
return parent::uninstall();
}
/************************** hooks start ******************************/
/**
* This hook we need for tracking product preview event
* Note that it works only for prestashop >1.7.1
*/
public function hookDisplayProductAdditionalInfo()
{
if (Tools::getValue('action') != 'refresh') {
return '';
}
$smarty = new Smarty();
$smarty->assign('rhEasyProductDto', $this->createRhEasyProductDto(true));
$smarty->assign('activeProfile', $this->roiHunterStorage->getActiveBeProfile());
return $smarty->fetch($this->local_path . 'views/templates/front/product_preview.tpl') .
$smarty->fetch($this->local_path . 'views/templates/front/rheasy_events_tracking.tpl');
}
public function hookDisplayFooter()
{
if (!$this->roiHunterStorage->trackingParamsAreInitialized()) {
return '';
}
$smarty = new Smarty();
$pageType = EPageType::fromPrestaShopController(Tools::getValue('controller'));
$smarty->assign(
'rhEasyDto',
new RhEasyDto(
"PRESTA_SHOP",
$this->roiHunterStorage->getGoogleConversionId(),
$this->roiHunterStorage->getGoogleConversionLabel(),
$this->roiHunterStorage->getFbPixelId()
)
);
$smarty->assign('rhEasyPageDto', new RhEasyPageDto($pageType));
if ($pageType == EPageType::PRODUCT) {
$smarty->assign('rhEasyProductDto', $this->createRhEasyProductDto(false));
}
if ($pageType == EPageType::CATEGORY) {
$smarty->assign('rhEasyCategoryDto', $this->createRhEasyCategoryDto());
}
if ($pageType == EPageType::ORDER_CONFIRMATION) {
$smarty->assign('rhEasyOrderDto', $this->createRhEasyOrderDto());
}
if (isset(Context::getContext()->cookie->roihunter)) { // add to cart event from previous web page
$cartDto = $this->getRhEasyCartDtoFromCookie();
if (!empty($cartDto->getCartItems())) {
$smarty->assign('rhEasyCartDto', $cartDto);
}
}
$smarty->assign('activeProfile', $this->roiHunterStorage->getActiveBeProfile());
$rheasyInit = $smarty->fetch($this->local_path . 'views/templates/front/rheasy_initialize.tpl');
$rheasyTracking = $smarty->fetch($this->local_path . 'views/templates/front/rheasy_events_tracking.tpl');
return $rheasyInit . $rheasyTracking;
}
public function hookActionCartSave($params)
{
if ((int)Tools::getValue("id_product") && Tools::getValue('add')) {
$rhEasyCookieDto = $this->rhEasyCookieManager->loadRhEasyCookieDto(); //store new item into storage
$newRhCartItemDto = $this->createRhEasyCartItemDto(); //get cart item from hook
$rhEasyCookieDto->getRhEasyCartDto()->addItemToCart($newRhCartItemDto);
$this->rhEasyCookieManager->saveRhEasyCookieDto($rhEasyCookieDto);
}
}
private function roundPrice($price, $currency = null)
{
if (is_null($currency)) {
$currency = Context::getContext()->currency;
}
$decimals = (int)$currency->decimals * _PS_PRICE_DISPLAY_PRECISION_;
return Tools::ps_round($price, (int)$decimals);
}
public function hookBackOfficeHeader()
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
$this->context->controller->addCSS($this->_path . 'views/css/back-for-1.6.css');
} else {
$this->context->controller->addCSS($this->_path . 'views/css/back-for-1.7.css');
$this->context->controller->addJS($this->_path . 'views/js/back.js');
}
}
public function hookDisplayBackOfficeHeader()
{
return $this->hookBackOfficeHeader();
}
private function useTax()
{
return true;
}
/************************** hooks end ******************************/
/************************** controller start ******************************/
public function getPluginType()
{
return 'rh-easy-prestashop-initial-message';
}
public function getStoreUrl($id_shop)
{
$shopUrl = new ShopUrl($id_shop);
if (Configuration::get('PS_SSL_ENABLED')) {
return 'https://'.$shopUrl->domain_ssl.$shopUrl->physical_uri;
} else {
return 'http://'.$shopUrl->domain.$shopUrl->physical_uri;
}
}
/**
* konkretni endpointy jsou
* check.php
* products.php
* state.php
* ... s paramatrem id_shop
*/
public function getRhStateApiBaseUrl($id_shop)
{
return $this->getStoreUrl($id_shop) . 'modules/roihunter/';
}
public function getStoreName($id_shop)
{
$shop = new Shop($id_shop);
return $shop->name;
}
public function getStoreCurrency($id_shop)
{
$id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT', null, null, $id_shop);
$currency = new Currency($id_currency);
if ($currency->active && !$currency->deleted) {
return $currency->iso_code;
}
}
public function getStoreLanguage($id_shop)
{
$id_language = (int)Configuration::get('PS_LANG_DEFAULT', null, null, $id_shop);
$language = new Language($id_language);
if ($language->active) {
return $language->iso_code;
}
}
public function getStoreCountry($id_shop)
{
$id_country = (int)Configuration::get('PS_COUNTRY_DEFAULT', null, null, $id_shop);
$country = new Country($id_country);
return $country->iso_code;
}
public function getPluginVersion()
{
return 'prestashop_' . $this->version;
}
public function getIframeUrl()
{
if ($this->roiHunterStorage->isActiveBeProfileProduction()) {
return ROIHunterStorage::RH_FE_PRODUCTION_URL;
} elseif ($this->roiHunterStorage->isActiveBeProfileStaging()) {
return ROIHunterStorage::RH_FE_STAGING_URL;
} else {
throw new PrestaShopException("Cannot get iframe URL because active profile is not staging or production");
}
}
/************************** controller end ******************************/
public function getShopFromUrl($url)
{
$field = Configuration::get("PS_USE_SSL") ? 'domain_ssl' : 'domain';
$sql = 'SELECT id_shop FROM ' . _DB_PREFIX_ . 'shop_url WHERE ' . $field . '="' . $url . '" AND active = 1';
$id_shop = (int)Db::getInstance()->getValue($sql);
if (!$id_shop && $field == 'domain_ssl') {
$sql = 'SELECT id_shop FROM ' . _DB_PREFIX_ . 'shop_url WHERE ' . $field . '="' . $url . '" AND active = 1';
$id_shop = (int)Db::getInstance()->getValue($sql);
}
if (!$id_shop && !Shop::isFeatureActive()) {
$sql = 'SELECT MIN(id_shop) FROM ' . _DB_PREFIX_ . 'shop_url WHERE active = 1';
$id_shop = (int)Db::getInstance()->getValue($sql);
}
return $id_shop;
}
/**
* Load the configuration form
*/
public function getContent()
{
$shop_content = self::getAdminShopContext();
$id_shop = (int)$shop_content['id_shop'];
$this->context->smarty->assign('shopContent', $shop_content);
$this->context->smarty->assign('base', $this->getRhStateApiBaseUrl($id_shop));
$this->context->smarty->assign('activeBeProfile', $this->roiHunterStorage->getActiveBeProfile());
$this->context->smarty->assign('storageItems', $this->roiHunterStorage->getStorageWithoutTokens());
return $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
}
private function installModuleTab()
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
$this->v16InstallModuleTab();
} else {
$this->v17InstallModuleTab();
}
}
private function v17InstallModuleTab()
{
$this->tabs = array(
array(
'name' => self::ROI_HUNTER_TAB_NAME,
'class_name' => self::ROI_HUNTER_TAB_CLASS_NAME,
'visible' => true,
'parent_class_name' => 'IMPROVE'
)
);
}
private function v16InstallModuleTab()
{
$sql = 'SELECT id_tab FROM ' .
_DB_PREFIX_ .
'tab WHERE class_name ="' .
pSQL(self::ROI_HUNTER_TAB_CLASS_NAME) .
'"';
$id_tab = Db::getInstance()->getValue($sql);
if ((int)$id_tab) {
$tab = new Tab($id_tab);
} else {
$tab = new Tab();
}
@copy(
_PS_MODULE_DIR_ . $this->module->name . '/logo.gif',
_PS_IMG_DIR_ . 't/' . self::ROI_HUNTER_TAB_CLASS_NAME . '.gif'
);
$tabNames = [];
foreach (Language::getLanguages(false) as $language) {
$tabNames[$language['id_lang']] = self::ROI_HUNTER_TAB_NAME;
}
$tab->name = $tabNames;
$tab->class_name = self::ROI_HUNTER_TAB_CLASS_NAME;
$tab->module = $this->name;
$tab->id_parent = 0;
if (!$tab->save()) {
$this->messages[] = 'Failed save Tab ' . implode(',', $tabNames);
return false;
}
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
if (!Tab::initAccess($tab->id)) {
$this->messages[] = 'Failed save init access ' . implode(',', $tabNames);
return false;
}
}
return true;
}
public function uninstallModuleTab()
{
$idTab = Tab::getIdFromClassName(self::ROI_HUNTER_TAB_CLASS_NAME);
if ($idTab != 0) {
$tab = new Tab($idTab);
$tab->delete();
return true;
}
return true; // true even on failed
}
public function getImageType()
{
return Configuration::get('ROIHUNTER_IMAGE_TYPE') ? Configuration::get('ROIHUNTER_IMAGE_TYPE') : '';
}
public static function getAdminShopContext()
{
$retval = [];
if (Shop::isFeatureActive()) {
$retval['multishop'] = true;
switch (Shop::getContext()) {
case Shop::CONTEXT_GROUP:
$retval['context'] = 'group';
break;
case Shop::CONTEXT_SHOP:
$retval['context'] = 'shop';
break;
case Shop::CONTEXT_ALL:
$retval['context'] = 'all';
break;
}
$retval['id_shop_group'] = (int)Shop::getContextShopGroupID();
} else {
$retval['multishop'] = false;
}
$retval['id_shop'] = (int)Context::getContext()->shop->id;
return $retval;
}
private function getSecureToken()
{
if (function_exists('openssl_random_pseudo_bytes')) {
$token = openssl_random_pseudo_bytes(32);
return Tools::substr(bin2hex($token), 0, 32);
} else {
$token = sha1(mt_rand(1, 90000) . _COOKIE_KEY_);
return $token;
}
}
/**
* Get module instance
* @return Roihunter
*/
public static function getModuleInstance()
{
$roihunterModule = parent::getInstanceByName(self::ROI_HUNTER_MODULE_NAME);
if ($roihunterModule instanceof Roihunter) {
return $roihunterModule;
} else {
throw new Error("Uninitialized prestashop module " . self::ROI_HUNTER_MODULE_NAME);
}
}
/**
* true if presta returned module instance
* @return bool
*/
public static function isModuleLoaded()
{
$roihunterModule = parent::getInstanceByName(self::ROI_HUNTER_MODULE_NAME);
if ($roihunterModule instanceof Roihunter) {
return true;
} else {
return false;
}
}
/**
* Get viewed product from DB based on ID in from $_POST
* @param $refresh
* @return RhEasyProductDto|null
*/
private function createRhEasyProductDto($refresh)
{
$id_product = (int)Tools::getValue('id_product');
if ($id_product) {
$sql = 'SELECT name FROM ' .
_DB_PREFIX_ .
'product_lang WHERE id_product =' .
(int)$id_product .
' AND id_lang =' .
Context::getContext()->language->id;
$name = Db::getInstance()->getValue($sql);
$price = Product::getPriceStatic($id_product, $this->useTax());
$currency = Context::getContext()->currency->iso_code;
$variantId = $this->getProductVariantId($id_product, $refresh);
return new RhEasyProductDto($id_product, $variantId, $name, $this->roundPrice($price), $currency);
} else {
return null;
}
}
private function getProductVariantId($productId, $refresh)
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
return $this->v16GetProductVariantId($productId);
} else {
if ($refresh) {
return $this->v17GetVariantId($productId);
} else {
return Tools::getValue('id_product_attribute');
}
}
}
private function v16GetProductVariantId($idProduct)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_product_attribute');
$dbQuery->from('product_attribute');
$dbQuery->where('id_product = '.$idProduct);
return Db::getInstance()->getValue($dbQuery);
}
private function createRhEasyCategoryDto()
{
$id_category = (int)Tools::getValue('id_category');
if ($id_category) {
$ref = new ReflectionObject(Context::getContext()->controller);
if ($ref->hasProperty('cat_products')) {
$prop = $ref->getProperty('cat_products');
$prop->setAccessible(true);
$products = $prop->getValue(Context::getContext()->controller);
return RhEasyCategoryDto::fromPrestaShopCategoryProducts($id_category, $products);
}
}
return null;
}
private function createRhEasyOrderDto()
{
$orderId = (int)Tools::getValue('id_order');
if ($orderId) {
$order = new Order($orderId);
$currency = new Currency($order->id_currency);
if ($this->useTax()) {
$total_price = $order->total_products_wt; // $order->total_paid_tax_incl;
} else {
$total_price = $order->total_products; // $order->total_paid_tax_excl;
}
return RhEasyOrderDto::fromPrestaShopOrderProducts(
$orderId,
$currency->iso_code,
$order->getProducts(),
$this->roundPrice($total_price)
);
}
return null;
}
private function createRhEasyCartItemDto()
{
$productId = (int)Tools::getValue("id_product");
$variantId = $this->getAddToCartVariantId($productId);
$quantity = (int)Tools::getValue('qty');
$price = Product::getPriceStatic($productId, $this->useTax(), $variantId);
$compute_precision = defined('_PS_PRICE_COMPUTE_PRECISION_') ? _PS_PRICE_COMPUTE_PRECISION_ : 2;
$roundedPrice = Tools::ps_round($price, $compute_precision);
$id_currency = Context::getContext()->cart->id_currency;
$currency = new Currency($id_currency);
return new RhEasyCartItemDto(
new RhEasyProductDto(
$productId,
$variantId,
Product::getProductName($productId),
$roundedPrice,
$currency->iso_code
),
$quantity
);
}
private function getAddToCartVariantId($productId)
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
return $this->v16GetAddToCartVariantId();
} else {
return $this->v17GetVariantId($productId);
}
}
private function v17GetVariantId($productId)
{
if (!Tools::getValue("group")) {
return null;
}
$allProductVariantsIds = $this->fetchAllVariantsIds($productId);
// values of group array are attribute ids (not product attribute ids)
// we need to find product attribute id of this product which is variant id in our case
foreach (Tools::getValue("group") as $attributeId) {
$productAttributeVariantIds = $this->fetchAllProductVariantIdsConnectedWithAttribute($attributeId);
// on each iteration we exclude all product variants are not related with our product using intersect
// and as the result of all iterations $allProductVariantsIds will contain only one variant we want to find
$allProductVariantsIds = array_intersect($allProductVariantsIds, $productAttributeVariantIds);
}
if (count($allProductVariantsIds) == 1) {
// array_intersect returns a map we need to get only value
return array_values($allProductVariantsIds)[0];
} else {
return null;
}
}
private function fetchAllProductVariantIdsConnectedWithAttribute($attributeId)
{
$dbQuery = new DbQuery();
$column_name = 'id_product_attribute';
$dbQuery->select($column_name);
$dbQuery->from('product_attribute_combination');
$dbQuery->where('id_attribute = '.$attributeId);
return array_column(Db::getInstance()->executeS($dbQuery), $column_name);
}
private function fetchAllVariantsIds($productId)
{
$dbQuery = new DbQuery();
$column_name = 'id_product_attribute';
$dbQuery->select($column_name);
$dbQuery->from('product_attribute');
$dbQuery->where('id_product = '.$productId);
return array_column(Db::getInstance()->executeS($dbQuery), $column_name);
}
private function v16GetAddToCartVariantId()
{
if (Tools::getValue("ipa")) {
return (int)Tools::getValue("ipa");
} else {
return null;
}
}
private function getRhEasyCartDtoFromCookie()
{
$rhEasyCookieDto = $this->rhEasyCookieManager->loadRhEasyCookieDto();
$this->rhEasyCookieManager->clearStorage();
return $rhEasyCookieDto->getRhEasyCartDto();
}
}