forked from craftcms/commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugin.php
502 lines (440 loc) · 18.8 KB
/
Plugin.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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\commerce;
use Craft;
use craft\base\Plugin as BasePlugin;
use craft\commerce\base\Purchasable;
use craft\commerce\elements\Order;
use craft\commerce\elements\Product;
use craft\commerce\elements\Subscription;
use craft\commerce\elements\Variant;
use craft\commerce\fields\Customer;
use craft\commerce\fields\Products;
use craft\commerce\fields\Variants;
use craft\commerce\helpers\ProjectConfigData;
use craft\commerce\migrations\Install;
use craft\commerce\models\Settings;
use craft\commerce\plugin\DeprecatedVariables;
use craft\commerce\plugin\Routes;
use craft\commerce\plugin\Services as CommerceServices;
use craft\commerce\plugin\Variables;
use craft\commerce\services\Emails;
use craft\commerce\services\Gateways;
use craft\commerce\services\Orders as OrdersService;
use craft\commerce\services\OrderStatuses;
use craft\commerce\services\ProductTypes;
use craft\commerce\services\Subscriptions;
use craft\commerce\web\twig\CraftVariableBehavior;
use craft\commerce\web\twig\Extension;
use craft\commerce\widgets\Orders;
use craft\commerce\widgets\Revenue;
use craft\elements\User as UserElement;
use craft\events\RebuildConfigEvent;
use craft\events\RegisterCacheOptionsEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\events\RegisterUserPermissionsEvent;
use craft\fixfks\controllers\RestoreController;
use craft\helpers\FileHelper;
use craft\helpers\UrlHelper;
use craft\redactor\events\RegisterLinkOptionsEvent;
use craft\redactor\Field as RedactorField;
use craft\services\Dashboard;
use craft\services\Elements;
use craft\services\Fields;
use craft\services\ProjectConfig;
use craft\services\Sites;
use craft\services\UserPermissions;
use craft\utilities\ClearCaches;
use craft\web\twig\variables\CraftVariable;
use yii\base\Event;
use yii\base\Exception;
use yii\web\User;
/**
* @property array $cpNavItem the control panel navigation menu
* @property Settings $settings
* @property mixed $settingsResponse the settings page response
* @method Settings getSettings()
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 2.0
*/
class Plugin extends BasePlugin
{
// Constants
// =========================================================================
// Edition constants
const EDITION_LITE = 'lite';
const EDITION_PRO = 'pro';
// Static
// =========================================================================
public static function editions(): array
{
return [
self::EDITION_LITE,
self::EDITION_PRO,
];
}
// Public Properties
// =========================================================================
/**
* @inheritDoc
*/
public $schemaVersion = '2.1.06';
/**
* @inheritdoc
*/
public $hasCpSettings = true;
/**
* @inheritdoc
*/
public $hasCpSection = true;
/**
* @inheritdoc
*/
public $minVersionRequired = '1.2.1360';
// Traits
// =========================================================================
use CommerceServices;
use Variables;
use DeprecatedVariables;
use Routes;
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->_setPluginComponents();
$this->_registerCpRoutes();
$this->_addTwigExtensions();
$this->_registerFieldTypes();
$this->_registerRedactorLinkOptions();
$this->_registerPermissions();
$this->_registerCraftEventListeners();
$this->_registerSessionEventListeners();
$this->_registerProjectConfigEventListeners();
$this->_registerWidgets();
$this->_registerVariables();
$this->_registerForeignKeysRestore();
$this->_registerPoweredByHeader();
$this->_registerElementTypes();
$this->_registerCacheTypes();
}
/**
* @inheritdoc
*/
public function beforeInstall(): bool
{
if (version_compare(Craft::$app->getInfo()->version, '3.0', '<')) {
throw new Exception('Craft Commerce 2 requires Craft CMS 3+ in order to run.');
}
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 70000) {
Craft::error('Craft Commerce requires PHP 7.0+ in order to run.');
return false;
}
return true;
}
/**
* @inheritdoc
*/
public function getSettingsResponse()
{
return Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('commerce/settings/general'));
}
/**
* @inheritdoc
*/
public function getCpNavItem(): array
{
$ret = parent::getCpNavItem();
$ret['label'] = Craft::t('commerce', 'Commerce');
if (Craft::$app->getUser()->checkPermission('commerce-manageOrders')) {
$ret['subnav']['orders'] = [
'label' => Craft::t('commerce', 'Orders'),
'url' => 'commerce/orders'
];
}
$hasEditableProductTypes = !empty($this->getProductTypes()->getEditableProductTypes());
if ($hasEditableProductTypes && Craft::$app->getUser()->checkPermission('commerce-manageProducts')) {
$ret['subnav']['products'] = [
'label' => Craft::t('commerce', 'Products'),
'url' => 'commerce/products'
];
}
if (Craft::$app->getUser()->checkPermission('commerce-manageSubscriptions')) {
$ret['subnav']['subscriptions'] = [
'label' => Craft::t('commerce', 'Subscriptions'),
'url' => 'commerce/subscriptions'
];
}
if (Craft::$app->getUser()->checkPermission('commerce-managePromotions')) {
$ret['subnav']['promotions'] = [
'label' => Craft::t('commerce', 'Promotions'),
'url' => 'commerce/promotions'
];
}
if (self::getInstance()->is('pro', '>=')) {
if (Craft::$app->getUser()->checkPermission('commerce-manageShipping')) {
$ret['subnav']['shipping'] = [
'label' => Craft::t('commerce', 'Shipping'),
'url' => 'commerce/shipping'
];
}
if (Craft::$app->getUser()->checkPermission('commerce-manageTaxes')) {
$ret['subnav']['tax'] = [
'label' => Craft::t('commerce', 'Tax'),
'url' => 'commerce/tax'
];
}
}
if (Craft::$app->getUser()->checkPermission('commerce-manageStoreSettings')) {
$ret['subnav']['store-settings'] = [
'label' => Craft::t('commerce', 'Store Settings'),
'url' => 'commerce/store-settings'
];
}
if (Craft::$app->getUser()->getIsAdmin() && Craft::$app->getConfig()->getGeneral()->allowAdminChanges) {
$ret['subnav']['settings'] = [
'label' => Craft::t('commerce', 'System Settings'),
'url' => 'commerce/settings'
];
}
return $ret;
}
// Protected Methods
// =========================================================================
/**
* @inheritdoc
*/
protected function createSettingsModel()
{
return new Settings();
}
// Private Methods
// =========================================================================
/**
* Register Commerce’s twig extensions
*/
private function _addTwigExtensions()
{
Craft::$app->view->registerTwigExtension(new Extension);
}
/**
* Register links to product in the redactor rich text field
*/
private function _registerRedactorLinkOptions()
{
if (!class_exists(RedactorField::class)) {
return;
}
Event::on(RedactorField::class, RedactorField::EVENT_REGISTER_LINK_OPTIONS, function(RegisterLinkOptionsEvent $event) {
// Include a Product link option if there are any product types that have URLs
$productSources = [];
$currentSiteId = Craft::$app->getSites()->getCurrentSite()->id;
foreach ($this->getProductTypes()->getAllProductTypes() as $productType) {
if (isset($productType->getSiteSettings()[$currentSiteId]) && $productType->getSiteSettings()[$currentSiteId]->hasUrls) {
$productSources[] = 'productType:' . $productType->uid;
}
}
if ($productSources) {
$event->linkOptions[] = [
'optionTitle' => Craft::t('commerce', 'Link to a product'),
'elementType' => Product::class,
'refHandle' => Product::refHandle(),
'sources' => $productSources
];
$event->linkOptions[] = [
'optionTitle' => Craft::t('commerce', 'Link to a variant'),
'elementType' => Variant::class,
'refHandle' => Variant::refHandle(),
'sources' => $productSources
];
}
});
}
/**
* Register Commerce’s permissions
*/
private function _registerPermissions()
{
Event::on(UserPermissions::class, UserPermissions::EVENT_REGISTER_PERMISSIONS, function(RegisterUserPermissionsEvent $event) {
$productTypes = Plugin::getInstance()->getProductTypes()->getAllProductTypes();
$productTypePermissions = [];
foreach ($productTypes as $productType) {
$suffix = ':' . $productType->uid;
$productTypePermissions['commerce-manageProductType' . $suffix] = ['label' => Craft::t('commerce', 'Manage “{type}” products', ['type' => $productType->name])];
}
$event->permissions[Craft::t('commerce', 'Craft Commerce')] = [
'commerce-manageProducts' => ['label' => Craft::t('commerce', 'Manage products'), 'nested' => $productTypePermissions],
'commerce-manageOrders' => [
'label' => Craft::t('commerce', 'Manage orders'), 'nested' => [
'commerce-capturePayment' => [
'label' => Craft::t('commerce', 'Capture Payment')
],
'commerce-refundPayment' => [
'label' => Craft::t('commerce', 'Refund Payment')
],
]
],
'commerce-managePromotions' => ['label' => Craft::t('commerce', 'Manage promotions')],
'commerce-manageSubscriptions' => ['label' => Craft::t('commerce', 'Manage subscriptions')],
'commerce-manageShipping' => ['label' => Craft::t('commerce', 'Manage shipping (Pro edition Only)')],
'commerce-manageTaxes' => ['label' => Craft::t('commerce', 'Manage taxes (Pro edition Only)')],
'commerce-manageStoreSettings' => ['label' => Craft::t('commerce', 'Manage store settings')],
];
});
}
/**
* Register Commerce’s session event listeners
*/
private function _registerSessionEventListeners()
{
if (!Craft::$app->getRequest()->getIsConsoleRequest()) {
Event::on(UserElement::class, UserElement::EVENT_AFTER_SAVE, [$this->getCustomers(), 'saveUserHandler']);
Event::on(User::class, User::EVENT_AFTER_LOGIN, [$this->getCustomers(), 'loginHandler']);
Event::on(User::class, User::EVENT_AFTER_LOGOUT, [$this->getCustomers(), 'logoutHandler']);
}
}
/**
* Register Commerce’s project config event listeners
*/
private function _registerProjectConfigEventListeners()
{
$projectConfigService = Craft::$app->getProjectConfig();
$gatewayService = $this->getGateways();
$projectConfigService->onAdd(Gateways::CONFIG_GATEWAY_KEY . '.{uid}', [$gatewayService, 'handleChangedGateway'])
->onUpdate(Gateways::CONFIG_GATEWAY_KEY . '.{uid}', [$gatewayService, 'handleChangedGateway'])
->onRemove(Gateways::CONFIG_GATEWAY_KEY . '.{uid}', [$gatewayService, 'handleArchivedGateway']);
$productTypeService = $this->getProductTypes();
$projectConfigService->onAdd(ProductTypes::CONFIG_PRODUCTTYPES_KEY . '.{uid}', [$productTypeService, 'handleChangedProductType'])
->onUpdate(ProductTypes::CONFIG_PRODUCTTYPES_KEY . '.{uid}', [$productTypeService, 'handleChangedProductType'])
->onRemove(ProductTypes::CONFIG_PRODUCTTYPES_KEY . '.{uid}', [$productTypeService, 'handleDeletedProductType']);
Event::on(Fields::class, Fields::EVENT_AFTER_DELETE_FIELD, [$productTypeService, 'pruneDeletedField']);
Event::on(Sites::class, Sites::EVENT_AFTER_DELETE_SITE, [$productTypeService, 'pruneDeletedSite']);
$ordersService = $this->getOrders();
$projectConfigService->onAdd(OrdersService::CONFIG_FIELDLAYOUT_KEY, [$ordersService, 'handleChangedFieldLayout'])
->onUpdate(OrdersService::CONFIG_FIELDLAYOUT_KEY, [$ordersService, 'handleChangedFieldLayout'])
->onRemove(OrdersService::CONFIG_FIELDLAYOUT_KEY, [$ordersService, 'handleDeletedFieldLayout']);
Event::on(Fields::class, Fields::EVENT_AFTER_DELETE_FIELD, [$ordersService, 'pruneDeletedField']);
$subscriptionsService = $this->getSubscriptions();
$projectConfigService->onAdd(Subscriptions::CONFIG_FIELDLAYOUT_KEY, [$subscriptionsService, 'handleChangedFieldLayout'])
->onUpdate(Subscriptions::CONFIG_FIELDLAYOUT_KEY, [$subscriptionsService, 'handleChangedFieldLayout'])
->onRemove(Subscriptions::CONFIG_FIELDLAYOUT_KEY, [$subscriptionsService, 'handleDeletedFieldLayout']);
Event::on(Fields::class, Fields::EVENT_AFTER_DELETE_FIELD, [$subscriptionsService, 'pruneDeletedField']);
$orderStatusService = $this->getOrderStatuses();
$projectConfigService->onAdd(OrderStatuses::CONFIG_STATUSES_KEY . '.{uid}', [$orderStatusService, 'handleChangedOrderStatus'])
->onUpdate(OrderStatuses::CONFIG_STATUSES_KEY . '.{uid}', [$orderStatusService, 'handleChangedOrderStatus'])
->onRemove(OrderStatuses::CONFIG_STATUSES_KEY . '.{uid}', [$orderStatusService, 'handleArchivedOrderStatus']);
Event::on(Emails::class, Emails::EVENT_AFTER_DELETE_EMAIL, [$orderStatusService, 'pruneDeletedEmail']);
$emailService = $this->getEmails();
$projectConfigService->onAdd(Emails::CONFIG_EMAILS_KEY . '.{uid}', [$emailService, 'handleChangedEmail'])
->onUpdate(Emails::CONFIG_EMAILS_KEY . '.{uid}', [$emailService, 'handleChangedEmail'])
->onRemove(Emails::CONFIG_EMAILS_KEY . '.{uid}', [$emailService, 'handleDeletedEmail']);
Event::on(ProjectConfig::class, ProjectConfig::EVENT_REBUILD, function(RebuildConfigEvent $event) {
$event->config['commerce'] = ProjectConfigData::rebuildProjectConfig();
});
}
/**
* Register general event listeners
*/
private function _registerCraftEventListeners()
{
Event::on(Sites::class, Sites::EVENT_AFTER_SAVE_SITE, [$this->getProductTypes(), 'afterSaveSiteHandler']);
Event::on(Sites::class, Sites::EVENT_AFTER_SAVE_SITE, [$this->getProducts(), 'afterSaveSiteHandler']);
Event::on(UserElement::class, UserElement::EVENT_BEFORE_DELETE, [$this->getSubscriptions(), 'beforeDeleteUserHandler']);
Event::on(Purchasable::class, Elements::EVENT_BEFORE_RESTORE_ELEMENT, [$this->getPurchasables(), 'beforeRestorePurchasableHandler']);
}
/**
* Register Commerce’s fields
*/
private function _registerFieldTypes()
{
Event::on(Fields::class, Fields::EVENT_REGISTER_FIELD_TYPES, function(RegisterComponentTypesEvent $event) {
$event->types[] = Products::class;
$event->types[] = Variants::class;
$event->types[] = Customer::class;
});
}
/**
* Register Commerce’s widgets.
*/
private function _registerWidgets()
{
Event::on(Dashboard::class, Dashboard::EVENT_REGISTER_WIDGET_TYPES, function(RegisterComponentTypesEvent $event) {
$event->types[] = Orders::class;
$event->types[] = Revenue::class;
});
}
/**
* Register Commerce’s template variable.
*/
private function _registerVariables()
{
Event::on(CraftVariable::class, CraftVariable::EVENT_INIT, function(Event $event) {
/** @var CraftVariable $variable */
$variable = $event->sender;
$variable->attachBehavior('commerce', CraftVariableBehavior::class);
});
}
/**
* Register for FK restore plugin
*/
private function _registerForeignKeysRestore()
{
if (!class_exists(RestoreController::class)) {
return;
}
Event::on(RestoreController::class, RestoreController::EVENT_AFTER_RESTORE_FKS, function(Event $event) {
// Add default FKs
(new Install())->addForeignKeys();
});
}
/**
* Register the powered-by header
*/
private function _registerPoweredByHeader()
{
if (!Craft::$app->request->isConsoleRequest) {
$headers = Craft::$app->getResponse()->getHeaders();
// Send the X-Powered-By header?
if (Craft::$app->getConfig()->getGeneral()->sendPoweredByHeader) {
$original = $headers->get('X-Powered-By');
$headers->set('X-Powered-By', $original . ($original ? ',' : '') . 'Craft Commerce');
} else {
// In case PHP is already setting one
header_remove('X-Powered-By');
}
}
}
/**
* Register the element types supplied by Craft Commerce
*/
private function _registerElementTypes()
{
Event::on(Elements::class, Elements::EVENT_REGISTER_ELEMENT_TYPES, function(RegisterComponentTypesEvent $e) {
$e->types[] = Variant::class;
$e->types[] = Product::class;
$e->types[] = Order::class;
$e->types[] = Subscription::class;
});
}
private function _registerCacheTypes()
{
// create the directory if it doesn't exist
FileHelper::createDirectory(Craft::$app->getPath()->getTempPath() . DIRECTORY_SEPARATOR . 'commerce-order-exports');
Event::on(ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS, function(RegisterCacheOptionsEvent $e) {
$e->options[] = [
'key' => 'commerce-order-exports',
'label' => Craft::t('commerce', 'Commerce order exports'),
'action' => function() {
FileHelper::clearDirectory(Craft::$app->getPath()->getTempPath() . DIRECTORY_SEPARATOR . 'commerce-order-exports');
}
];
});
}
}