-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBootstrap.php
1637 lines (1542 loc) · 57.3 KB
/
Bootstrap.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 /**
* Copyright (c) 2020, Nosto Solutions Ltd
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @author Nosto Solutions Ltd <[email protected]>
* @copyright Copyright (c) 2020 Nosto Solutions Ltd (http://www.nosto.com)
* @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause
*/ // @codingStandardsIgnoreLine
require_once __DIR__ . '/vendor/autoload.php';
use Shopware\Components\Logger;
use Shopware_Plugins_Frontend_NostoTagging_Components_Order_Confirmation as NostoOrderConfirmation;
use Shopware_Plugins_Frontend_NostoTagging_Components_Operation_Settings as NostoSettingsOperation;
use Shopware_Plugins_Frontend_NostoTagging_Components_Operation_Product as NostoOperationProduct;
use Shopware_Plugins_Frontend_NostoTagging_Components_Operation_ExchangeRates as NostoExchangeRatesOp;
use Shopware_Plugins_Frontend_NostoTagging_Components_Model_Category as NostoCategoryModel;
use Shopware_Plugins_Frontend_NostoTagging_Components_Model_Customer as NostoCustomerModel;
use Shopware_Plugins_Frontend_NostoTagging_Components_Model_Product as NostoProductModel;
use Shopware_Plugins_Frontend_NostoTagging_Components_Customer as NostoComponentCustomer;
use Shopware_Plugins_Frontend_NostoTagging_Components_Account as NostoComponentAccount;
use Shopware_Plugins_Frontend_NostoTagging_Components_Model_Order as NostoOrderModel;
use Shopware_Plugins_Frontend_NostoTagging_Components_Model_Cart as NostoCartModel;
use Shopware_Plugins_Frontend_NostoTagging_Components_Helper_Currency as CurrencyHelper;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Shopware\Bundle\AttributeBundle\Service\CrudService;
use Shopware\Models\Customer\Customer as CustomerModel;
use Nosto\Request\Http\HttpRequest as NostoHttpRequest;
use Shopware\Models\Attribute\Order as OrderAttribute;
use Shopware\CustomModels\Nosto\Setting\Setting;
use Nosto\Object\Signup\Account as NostoAccount;
use phpseclib\Crypt\Random as NostoCryptRandom;
use Shopware\Components\Model\ModelManager;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\OptimisticLockException;
use Shopware\Models\Category\Category;
use Doctrine\ORM\Tools\ToolsException;
use Shopware\Components\CacheManager;
use Shopware\Models\Article\Detail;
use Shopware\Models\Article\Article;
use Shopware\Models\Config\Element;
use Nosto\Object\MarkupableString;
use Shopware\Models\Order\Order;
use Shopware\Models\Shop\Shop;
use Doctrine\ORM\ORMException;
use Nosto\Object\SearchTerm;
use Nosto\Object\PageType;
use Nosto\NostoException;
use Nosto\Nosto;
/**
* The plugin bootstrap class.
*
* Extends Shopware_Components_Plugin_Bootstrap.
*
* @package Shopware
* @subpackage Plugins_Frontend
* @noinspection PhpIllegalPsrClassPathInspection
*/
class Shopware_Plugins_Frontend_NostoTagging_Bootstrap extends Shopware_Components_Plugin_Bootstrap
{
const PLATFORM_NAME = 'shopware';
const PLUGIN_VERSION = '2.5.2';
const MENU_PARENT_ID = 23; // Configuration
const NEW_ATTRIBUTE_MANAGER_VERSION = '5.2.0';
const SUPPORT_SHOW_REVIEW_SUB_SHOP_ONLY_VERSION = '5.3.0';
const PLATFORM_UI_VERSION = '1';
const PAGE_TYPE_FRONT_PAGE = 'front';
const PAGE_TYPE_CART = 'cart';
const PAGE_TYPE_PRODUCT = 'product';
const PAGE_TYPE_CATEGORY = 'category';
const PAGE_TYPE_SEARCH = 'search';
const PAGE_TYPE_NOTFOUND = 'notfound';
const PAGE_TYPE_ORDER = 'order';
const SERVICE_ATTRIBUTE_CRUD = 'shopware_attribute.crud_service';
const NOSTO_CUSTOM_ATTRIBUTE_PREFIX = 'nosto';
const NOSTO_CUSTOMER_REFERENCE_FIELD = 'customer_reference';
const CONFIG_SEND_CUSTOMER_DATA = 'send_customer_data';
const CONFIG_SKU_TAGGING= 'sku_tagging';
const CONFIG_PRODUCT_STREAMS = 'product_streams';
const CONFIG_CUSTOM_FIELD_TAGGING = 'custom_field_tagging';
const CONFIG_MULTI_CURRENCY = 'multi_currency';
const CONFIG_MULTI_CURRENCY_DISABLED = 'multi_currency_disabled';
const CONFIG_MULTI_CURRENCY_EXCHANGE_RATES = 'multi_currency_exchange_rates';
const MYSQL_TABLE_ALREADY_EXISTS_ERROR = 'SQLSTATE[42S01]';
private static $productUpdated = false;
/**
* A list of custom database attributes
* @var array
*/
private static $customAttributes = array(
'0.1.0' => array(
's_order_attributes' => array(
'table' => 's_order_attributes',
'prefix' => self::NOSTO_CUSTOM_ATTRIBUTE_PREFIX,
'field' => 'customerID',
'type' => 'string',
'oldType' => 'VARCHAR(255)',
'keepOnUninstall' => false
),
),
'1.1.7' => array(
's_user_attributes' => array(
'table' => 's_user_attributes',
'prefix' => self::NOSTO_CUSTOM_ATTRIBUTE_PREFIX,
'field' => self::NOSTO_CUSTOMER_REFERENCE_FIELD,
'type' => 'string',
'oldType' => 'VARCHAR(32)',
'keepOnUninstall' => true
),
)
);
/**
* @inheritdoc
* @suppress PhanTypeMismatchArgument
* @throws NostoException
* @noinspection PhpUnused
*/
public function afterInit()
{
NostoHttpRequest::buildUserAgent(self::PLATFORM_NAME, $this->getShopwareVersion(), self::PLUGIN_VERSION);
$this->registerCustomModels();
}
/**
* @inheritdoc
* @noinspection PhpUnused
*/
public function getCapabilities()
{
return array(
'install' => true,
'update' => true,
'enable' => true
);
}
/**
* @inheritdoc
* @noinspection PhpUnused
*/
public function getInfo()
{
return array(
'version' => $this->getVersion(),
'label' => $this->getLabel(),
'source' => $this->getSource(),
'author' => 'Nosto Solutions Ltd',
'supplier' => 'Nosto Solutions Ltd',
'copyright' => 'Copyright (c) 2016, Nosto Solutions Ltd',
'description' => 'Increase your conversion rate and average order value by delivering ' .
'your customers personalized product recommendations throughout their shopping journey.',
'support' => '[email protected]',
'link' => 'http://nosto.com'
);
}
/**
* @inheritdoc
*/
public function getVersion()
{
return self::PLUGIN_VERSION;
}
/**
* @inheritdoc
*/
public function getLabel()
{
return 'Personalization for Shopware';
}
/**
* @inheritdoc
* @throws Exception
* @throws ToolsException
* @noinspection PhpUnused
*/
public function install()
{
$this->createMyTables();
$this->createMyAttributes('all');
$this->createMyMenu();
$this->createMyEmotions();
$this->registerMyEvents();
$this->createConfiguration();
$this->clearShopwareCache();
return true;
}
/**
* Initialises Nosto Plugin backend settings
* Run on installation
*
*/
public function createConfiguration()
{
$form = $this->Form();
$form->setElement(
'checkbox',
self::CONFIG_SEND_CUSTOMER_DATA,
[
'label' => 'Enable Sending Customer Tagging',
'value' => 1,
'scope' => Element::SCOPE_SHOP,
'description' => 'Enable Sending Customer Tagging To Nosto',
'required' => true
]
);
$form->setElement(
'checkbox',
self::CONFIG_SKU_TAGGING,
[
'label' => 'Enable SKU Tagging',
'value' => 1,
'scope' => Element::SCOPE_SHOP,
'description' => 'Enable SKU Tagging',
'required' => true
]
);
$form->setElement(
'checkbox',
self::CONFIG_PRODUCT_STREAMS,
[
'label' => 'Enable Product Streams Support',
'value' => 0,
'scope' => Element::SCOPE_SHOP,
'description' => 'Add Product Streams To Category Paths',
'required' => true
]
);
$form->setElement(
'checkbox',
self::CONFIG_CUSTOM_FIELD_TAGGING,
[
'label' => 'Enable Custom Field Tagging',
'value' => 1,
'scope' => Element::SCOPE_SHOP,
'description' => 'Add Product Properties In Custom Field Tagging',
'required' => true
]
);
$form->setElement(
'select',
self::CONFIG_MULTI_CURRENCY,
array(
'label' => 'Multi Currency',
'value' => 'Disabled',
'store' => array(
array(self::CONFIG_MULTI_CURRENCY_DISABLED, 'Disabled'),
array(self::CONFIG_MULTI_CURRENCY_EXCHANGE_RATES, 'Exchange Rates'),
),
'description' => 'Set this to "Exchange rates" if your store uses Shopware\'s exchange rates.
If you have a custom pricing handling set this to "Disabled" and Nosto will not
make any currency conversions.',
'required' => true,
'scope' => Element::SCOPE_SHOP)
);
}
/**
* Returns an array with metadata of Nosto tables
*
* @param ModelManager $modelManager
* @return array
*/
protected function getNostoModelClassMetadata(ModelManager $modelManager)
{
return array(
$modelManager->getClassMetadata('\Shopware\CustomModels\Nosto\Account\Account'),
$modelManager->getClassMetadata('\Shopware\CustomModels\Nosto\Customer\Customer'),
$modelManager->getClassMetadata('\Shopware\CustomModels\Nosto\Setting\Setting')
);
}
/**
* Creates needed db tables used by the plugin models.
*
* Run on install.
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::install
* @throws ToolsException
*/
protected function createMyTables()
{
$this->registerCustomModels();
$modelManager = Shopware()->Models();
$schematicTool = new Doctrine\ORM\Tools\SchemaTool($modelManager);
try {
$schematicTool->createSchema($this->getNostoModelClassMetadata($modelManager));
} catch (ToolsException $e) {
// If table already exists, log and continue installation
if (strpos($e->getMessage(), self::MYSQL_TABLE_ALREADY_EXISTS_ERROR)) {
$this->getLogger()->warning(
sprintf(
'Table already exists, continuing with installation. Message was: %s',
$e->getMessage()
)
);
} else {
throw new ToolsException($e);
}
}
}
/**
* Adds needed attributes to core models.
*
* Run on install.
* Adds `nosto_customerID` to Shopware\Models\Attribute\Order.
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::install
*
* @param string $fromVersion default all
*
* @return boolean
* @throws Exception
*/
protected function createMyAttributes($fromVersion = 'all')
{
foreach (self::$customAttributes as $version => $attributes) {
if ($fromVersion === 'all' || version_compare($version, $fromVersion, '>')) {
foreach ($attributes as $attr) {
$this->addMyAttribute($attr);
}
}
}
return true;
}
/**
* Add new custom attribute to the database structure
*
* For the structure of attribute
* @see self::$_customAttributes
* @param array $attribute
* @throws Exception
* @suppress PhanDeprecatedFunction
*/
private function addMyAttribute(array $attribute)
{
try {
/* Shopware()->Models()->removeAttribute will be removed in Shopware 5.3.0 */
self::validateMyAttribute($attribute);
if (version_compare($this->getShopwareVersion(), self::NEW_ATTRIBUTE_MANAGER_VERSION, '>=')) {
$fieldName = sprintf('%s_%s', $attribute['prefix'], $attribute['field']);
/** @var CrudService $attributeService */
$attributeService = $this->get(self::SERVICE_ATTRIBUTE_CRUD);
$attributeService->update(
$attribute['table'],
$fieldName,
$attribute['type']
);
} else {
/** @noinspection PhpUndefinedMethodInspection */
/** @phan-suppress-next-line PhanUndeclaredMethod */
Shopware()->Models()->addAttribute(
$attribute['table'],
$attribute['prefix'],
$attribute['field'],
$attribute['oldType']
);
}
Shopware()->Models()->generateAttributeModels(
array($attribute['table'])
);
} catch (NostoException $e) {
$this->getLogger()->warning($e->getMessage());
}
}
/**
* Validates that attribute can be added to the database
*
* For the structure of attribute
* For the structure of attribute
* @see self::$_customAttributes
*
* @param array $attribute
* @throws NostoException
*/
public static function validateMyAttribute(array $attribute)
{
$keys = array(
'table',
'prefix',
'field',
'type',
'oldType',
'keepOnUninstall',
);
foreach ($keys as $key) {
if (!isset($attribute[$key])) {
throw new NostoException(
sprintf(
'Attribute array is missing key %s',
$key
)
);
}
}
}
/**
* Adds the plugin backend configuration menu item.
*
* Run on install.
*
* @suppress PhanTypeMismatchArgument
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::install
*/
protected function createMyMenu()
{
try {
$parentMenu = $this->Menu()->findOneBy(array('id' => self::MENU_PARENT_ID));
$this->createMenuItem(
array(
'label' => 'Nosto',
'controller' => 'NostoTagging',
'action' => 'Index',
'active' => 1,
'parent' => $parentMenu,
'class' => 'nosto--icon'
)
);
} catch (Exception $e) {
$this->getLogger()->warning($e->getMessage());
}
}
/**
* Returns the Shopware platform version
* @return mixed|string
* @throws InvalidArgumentException
* @throws NostoException in case version cannot be determined
* @suppress PhanUndeclaredConstantOfClass
*/
public function getShopwareVersion()
{
/** @noinspection PhpUndefinedClassConstantInspection */
if (defined('Shopware::VERSION') && Shopware::VERSION !== null && Shopware::VERSION !== '___VERSION___') {
/** @noinspection PhpUndefinedClassConstantInspection */
return Shopware::VERSION;
}
if (Shopware()->Container()->getParameter('shopware.release.version')) {
return Shopware()->Container()->getParameter('shopware.release.version');
}
if (Nosto::getEnvVariable('SHOPWARE_VERSION')) {
return Nosto::getEnvVariable('SHOPWARE_VERSION');
}
throw new NostoException('Could not determine shopware version');
}
/**
* Creates Nosto emotions for Shopping World templates
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::install
* @suppress PhanTypeMismatchArgument
*/
protected function createMyEmotions()
{
$component = $this->createEmotionComponent(
array(
'name' => 'Nosto Recommendation',
'template' => 'nosto_slot',
'description' => 'Add Nosto recommendations to your Shopping World templates'
)
);
$component->createTextField(
array(
'name' => 'slot_id',
'fieldLabel' => 'Nosto slot div ID',
'supportText' => 'E.g. frontpage-nosto-1, nosto-shopware-1',
'helpTitle' => 'Nosto recommendation slot',
'helpText' => '
Nosto slot div ID is the id attribute of the element where
Nosto recommendations are populated. It is recommended that
you create new recommendation slot for Shopping World elements
from Nosto settings. You must have matching slot created in Nosto
settings.',
'defaultValue' => 'frontpage-nosto-1',
'allowBlank' => false
)
);
return true;
}
/**
* Registers events for this plugin.
*
* Run on install.
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::install
*/
protected function registerMyEvents()
{
// Backend events.
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch_Backend_Index',
'onPostDispatchBackendIndex'
);
$this->subscribeEvent(
'Enlight_Controller_Dispatcher_ControllerPath_Backend_NostoTagging',
'onControllerPathBackend'
);
$this->subscribeEvent(
'Shopware\Models\Article\Article::postPersist',
'onPostPersistArticle'
);
$this->subscribeEvent(
'Shopware\Models\Article\Article::postUpdate',
'onPostUpdateArticle'
);
$this->subscribeEvent(
'Shopware\Models\Article\Article::postRemove',
'onPostRemoveArticle'
);
$this->subscribeEvent(
'Shopware\Models\Order\Order::postUpdate',
'onPostUpdateOrder'
);
$this->subscribeEvent(
'Shopware\Models\Article\Detail::postPersist',
'onPostPersistArticle'
);
$this->subscribeEvent(
'Shopware\Models\Article\Detail::postUpdate',
'onPostUpdateArticle'
);
$this->subscribeEvent(
'Shopware_Controllers_Backend_Config_After_Save_Config_Element',
'afterSaveConfig'
);
// Frontend events.
$this->subscribeEvent(
'Enlight_Controller_Dispatcher_ControllerPath_Frontend_NostoTagging',
'onControllerPathFrontend'
);
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch',
'onPostDispatchFrontend'
);
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch_Frontend_Index',
'onPostDispatchFrontendIndex'
);
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch_Frontend_Detail',
'onPostDispatchFrontendDetail'
);
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch_Frontend_Listing',
'onPostDispatchFrontendListing'
);
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch_Frontend_Checkout',
'onPostDispatchFrontendCheckout'
);
$this->subscribeEvent(
'Enlight_Controller_Action_PostDispatch_Frontend_Search',
'onPostDispatchFrontendSearch'
);
$this->subscribeEvent(
'sOrder::sSaveOrder::after',
'onOrderSSaveOrderAfter'
);
$this->subscribeEvent(
'Enlight_Controller_Action_Frontend_Error_GenericError',
'onFrontEndErrorGenericError'
);
}
/**
* Return all shops from a backend context
*
* @return array shops
* @noinspection PhpUndefinedClassInspection
* @noinspection PhpUnused
*/
public function getAllActiveShops()
{
/** @phan-suppress-next-line UndeclaredTypeInInlineVar */
/** @var Shopware_Proxies_ShopwareModelsShopRepositoryProxy $repository */
$repository = Shopware()->Container()->get('models')->getRepository('Shopware\Models\Shop\Shop');
/** @noinspection PhpUndefinedMethodInspection */
return $repository->getActiveShops();
}
/**
* Return backend configuration for a given shop
* in a backend context
*
* @param Shop $shop
* @return array|mixed
* @noinspection PhpUnused
*/
public function getShopConfig(Shop $shop)
{
return $this
->get('shopware.plugin.cached_config_reader')
->getByPluginName('NostoTagging', $shop);
}
/**
* Event that runs on every configuration save
*
* @param Enlight_Event_EventArgs $args
* @throws NostoException
* @noinspection PhpUnused
*/
public function afterSaveConfig(Enlight_Event_EventArgs $args)
{
try {
/** @noinspection PhpUndefinedMethodInspection */
$configValues = $args->getElement()->getValues()->getValues();
} catch (Exception $e) {
$this->getLogger()->error(
'Could not save backend configuration ' . $e->getMessage()
);
return;
}
/** @var Shopware\Models\Config\Value[] $configValues */
foreach ($configValues as $configValue) {
// Trigger update for Multi-Currency Settings
if ($configValue->getElement()
&& $configValue->getElement()->getName() === self::CONFIG_MULTI_CURRENCY
) {
NostoSettingsOperation::updateCurrencySettings($configValue->getShop());
}
}
}
/**
* Registers dependencies / autoloader
* @noinspection PhpUnused
*/
public function registerMyComponents()
{
/** @noinspection PhpIncludeInspection */
require_once $this->Path() . '/vendor/autoload.php';
}
/**
* Clears following Shopware caches
* - proxy cache
* - template cache
* - op cache
*/
private function clearShopwareCache()
{
/** @var CacheManager $cacheManager */
$cacheManager = $this->get('shopware.cache_manager');
if ($cacheManager instanceof CacheManager) {
if (method_exists($cacheManager, 'clearProxyCache')) {
$cacheManager->clearProxyCache();
}
if (method_exists($cacheManager, 'clearTemplateCache')) {
$cacheManager->clearTemplateCache();
}
if (method_exists($cacheManager, 'clearOpCache')) {
$cacheManager->clearOpCache();
}
}
}
/**
* @inheritdoc
* @throws Exception
* @noinspection PhpUnused
*/
public function update($existingVersion)
{
$this->updateMyTables();
$this->createMyAttributes($existingVersion);
$this->createConfiguration();
$this->clearShopwareCache();
return true;
}
/**
* @inheritdoc
* @throws Exception
* @noinspection PhpUnused
*/
public function uninstall()
{
$this->dropMyTables();
$this->dropMyAttributes();
return true;
}
/**
* Drops created db tables.
*
* Run on uninstall.
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::uninstall
*/
protected function dropMyTables()
{
$this->registerCustomModels();
$modelManager = Shopware()->Models();
$schematicTool = new Doctrine\ORM\Tools\SchemaTool($modelManager);
$schematicTool->dropSchema($this->getNostoModelClassMetadata($modelManager));
}
/**
* Update existing db tables.
*
* Run on update.
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::update
*/
protected function updateMyTables()
{
$this->registerCustomModels();
$modelManager = Shopware()->Models();
$schematicTool = new Doctrine\ORM\Tools\SchemaTool($modelManager);
$schematicTool->updateSchema($this->getNostoModelClassMetadata($modelManager), true);
}
/**
* Removes created attributes from core models
*
* Run on uninstall.
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::uninstall
* @throws Exception
*/
protected function dropMyAttributes()
{
foreach (self::$customAttributes as $version => $attributes) {
foreach ($attributes as $table => $attr) {
if ($attr['keepOnUninstall'] === false) {
$this->removeMyAttribute($attr);
}
}
}
}
/**
* Removes custom attribute from the database
*
* For the structure of attribute
* @see self::$_customAttributes
* @suppress PhanDeprecatedFunction
* @param array $attribute
* @throws Exception
*/
private function removeMyAttribute(array $attribute)
{
try {
/* Shopware()->Models()->removeAttribute will be removed in Shopware 5.3.0 */
self::validateMyAttribute($attribute);
if (version_compare($this->getShopwareVersion(), self::NEW_ATTRIBUTE_MANAGER_VERSION, '>=')) {
$fieldName = sprintf('%s_%s', $attribute['prefix'], $attribute['field']);
/** @var CrudService $attributeService */
$attributeService = $this->get(self::SERVICE_ATTRIBUTE_CRUD);
$attributeService->delete(
$attribute['table'],
$fieldName
);
} else {
/** @noinspection PhpUndefinedMethodInspection */
/** @phan-suppress-next-line PhanUndeclaredMethod */
Shopware()->Models()->removeAttribute(
$attribute['table'],
$attribute['prefix'],
$attribute['field']
);
}
Shopware()->Models()->generateAttributeModels(
array($attribute['table'])
);
} catch (NostoException $e) {
$this->getLogger()->warning($e->getMessage());
}
}
/**
* Check if plugin installation path is valid and updates DB config if it is not.
*
* @return void
* @throws ReflectionException|Zend_Db_Adapter_Exception
*/
private function validatePathSource()
{
// Check that the path is valid
$reflection = new ReflectionClass($this);
if ($fileName = $reflection->getFileName()) {
$dirName = dirname($fileName) . DIRECTORY_SEPARATOR;
if ($this->Path() === $dirName) {
return;
}
}
$this->updatePluginSource();
}
/**
* @throws Zend_Db_Adapter_Exception
*/
private function updatePluginSource()
{
// Source folder is different than the one that came from DB
// Update source on the DB.
$path = $this->Path();
$data = [];
if (strpos($path, "Community/Frontend/NostoTagging") !== false) {
$data['source'] = 'Local';
$path = str_replace('Community/Frontend/NostoTagging', 'Local/Frontend/NostoTagging', $path);
} else {
$data['source'] = 'Community';
$path = str_replace('Local/Frontend/NostoTagging', 'Community/Frontend/NostoTagging', $path);
}
$where = [
'name = ?' => $this->getName(),
'source = ?' => $this->getSource(),
];
Shopware()->Db()->update('s_core_plugins', $data, $where);
$this->info->set('path', $path);
}
/**
* Event handler for the `Enlight_Controller_Action_PostDispatch_Backend_Index` event.
*
* Adds Nosto CSS to the backend <head>.
* Check if we should open the Nosto configuration window automatically,
* e.g. if the backend is loaded as a part of the OAuth cycle.
*
* @param Enlight_Controller_ActionEventArgs $args the event arguments.
* @throws NostoException
* @throws ORMException
* @throws OptimisticLockException
* @noinspection PhpUnused
*/
public function onPostDispatchBackendIndex(Enlight_Controller_ActionEventArgs $args)
{
$ctrl = $args->getSubject();
$view = $ctrl->View();
$request = $ctrl->Request();
try {
$this->validatePathSource();
} catch (Exception $e) {
$this->getLogger()->warning(
sprintf(
"Could not validate extension installation path. Error message was: %s",
$e->getMessage()
)
);
}
if ($this->validateEvent($ctrl, 'backend', 'index', 'index')) {
$ratesOp = new NostoExchangeRatesOp();
$ratesOp->updateExchangeRates();
$view->addTemplateDir($this->Path() . 'Views/');
$view->extendsTemplate('backend/plugins/nosto_tagging/index/header.tpl');
if (($shopId = $request->getParam('openNosto')) !== null) {
// Store any OAuth related params as a Nosto setting, so we can
// use them later when building the account config urls.
$code = $request->getParam('messageCode');
$type = $request->getParam('messageType');
$text = $request->getParam('messageText');
if (!empty($code) && !empty($type)) {
$data = array(
$shopId => array(
'message_code' => $code,
'message_type' => $type,
)
);
if (!empty($text)) {
$data[$shopId]['message_text'] = $text;
}
$setting = Shopware()
->Models()
->getRepository('\Shopware\CustomModels\Nosto\Setting\Setting')
->findOneBy(array('name' => 'oauthParams'));
if (is_null($setting)) {
$setting = new Setting();
$setting->setName('oauthParams');
}
$setting->setValue(json_encode($data));
Shopware()->Models()->persist($setting);
Shopware()->Models()->flush($setting);
}
}
} elseif ($request->getActionName() === 'load') {
$view->addTemplateDir($this->Path() . 'Views/');
$view->extendsTemplate('backend/nosto_start_app/menu.js');
}
}
/**
* Validates that current request is for a specific module, controller and
* action combo.
*
* @param Enlight_Controller_Action $controller the controller event.
* @param string $module the module name, e.g. "frontend".
* @param string|null $ctrl the controller name (optional).
* @param string|null $action the action name (optional).
* @return bool true if the event is valid, false otherwise.
*
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::onPostDispatchFrontend
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::onPostDispatchFrontendIndex
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::onPostDispatchFrontendDetail
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::onPostDispatchFrontendListing
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::onPostDispatchFrontendCheckout
* @see Shopware_Plugins_Frontend_NostoTagging_Bootstrap::onPostDispatchFrontendSearch
*/
protected function validateEvent($controller, $module, $ctrl = null, $action = null)
{
$request = $controller->Request();
$response = $controller->Response();
$view = $controller->View();
return !(!$request->isDispatched()
|| !$view->hasTemplate()
|| $response->isException()
|| $request->getModuleName() !== $module
|| (!is_null($ctrl) && $request->getControllerName() !== $ctrl)
|| (!is_null($action) && $request->getActionName() !== $action));
}
/**
* Event handler for the `Enlight_Controller_Action_PostDispatch` event.
*
* Adds the embed Javascript to all pages.
* Adds the customer tagging to all pages.
* Adds the cart tagging to all pages.
*
* @param Enlight_Controller_ActionEventArgs $args the event arguments.
* @throws ORMException
* @noinspection PhpUnused
*/
public function onPostDispatchFrontend(Enlight_Controller_ActionEventArgs $args)
{
if (!$this->validateEvent($args->getSubject(), 'frontend')
) {
return;
}
NostoComponentCustomer::persistSession();
$view = $args->getSubject()->View();
$view->addTemplateDir($this->Path() . 'Views/');
$view->extendsTemplate('frontend/plugins/nosto_tagging/index.tpl');
$this->addEmbedScript($view);
$this->addHcidTagging($view);
$locale = Shopware()->Shop()->getLocale()->getLocale();
$view->assign('nostoVersion', $this->getVersion());
$view->assign('nostoUniqueId', $this->getUniqueId());
$view->assign('nostoLanguage', strtolower(substr($locale, 0, 2)));
}
/**
* Checks if the current active Shop has an Nosto account that is connected to Nosto.
*
* @return bool true if a account exists that is connected to Nosto, false otherwise.
*/
protected function shopHasConnectedAccount()
{
$shop = Shopware()->Shop();
try {
return NostoComponentAccount::accountExistsAndIsConnected($shop);