-
Notifications
You must be signed in to change notification settings - Fork 12
/
Lists.php
439 lines (341 loc) · 16.5 KB
/
Lists.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
<?php
namespace verbb\wishlist\services;
use verbb\wishlist\Wishlist;
use verbb\wishlist\elements\Item;
use verbb\wishlist\elements\ListElement;
use verbb\wishlist\elements\db\ListQuery;
use verbb\wishlist\models\Settings;
use Craft;
use craft\base\Component;
use craft\base\ElementInterface;
use craft\db\Query;
use craft\elements\User as UserElement;
use craft\helpers\ConfigHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\StringHelper;
use DateTime;
use yii\web\Cookie;
use yii\web\UserEvent;
use Throwable;
class Lists extends Component
{
// Properties
// =========================================================================
protected string $listName = 'wishlist_list';
private array $_lists = [];
// Public Methods
// =========================================================================
public function getListById(int $id, $siteId = null): ?ListElement
{
/* @noinspection PhpIncompatibleReturnTypeInspection */
return Craft::$app->getElements()->getElementById($id, ListElement::class, $siteId);
}
public function saveElement(ElementInterface $element, bool $runValidation = true, bool $propagate = true): bool
{
$updateListSearchIndexes = Wishlist::$plugin->getSettings()->updateListSearchIndexes;
return Craft::$app->getElements()->saveElement($element, $runValidation, $propagate, $updateListSearchIndexes);
}
public function getList($id = null, $forceSave = false, $listTypeId = null): ElementInterface
{
$session = Craft::$app->getSession();
$cacheKey = $id . ':' . $listTypeId;
if ($id) {
$this->_lists[$cacheKey] = Wishlist::$plugin->getLists()->getListById($id);
if ($this->_lists[$cacheKey]) {
return $this->_lists[$cacheKey];
}
}
// We need maintain potential different lists in our cache
if (!isset($this->_lists[$cacheKey])) {
$this->_lists[$cacheKey] = null;
}
if ($this->_lists[$cacheKey] === null) {
if ($listTypeId) {
// Get the first list of the typeId we find for the user. If it needs to be more precise, use id.
$this->_lists[$cacheKey] = $this->getListQueryForOwner()->typeId($listTypeId)->one();
} else {
$this->_lists[$cacheKey] = $this->getListQueryForOwner()->default(true)->one();
}
if (!$this->_lists[$cacheKey]) {
$listType = null;
if ($listTypeId) {
// If this list type is new for the user, let's create a new list for it.
$listType = Wishlist::$plugin->getListTypes()->getListTypeById($listTypeId);
}
if ($listType === null) {
// If we still don't have a valid list type, let's get the default one.
$listType = Wishlist::$plugin->getListTypes()->getDefaultListType();
}
$this->_lists[$cacheKey] = new ListElement();
$this->_lists[$cacheKey]->reference = $this->generateReferenceNumber();
$this->_lists[$cacheKey]->typeId = $listType->id;
$this->_lists[$cacheKey]->title = $listType->name;
$this->_lists[$cacheKey]->default = $listType->default;
$this->_lists[$cacheKey]->sessionId = $this->getSessionId();
}
}
$originalIp = $this->_lists[$cacheKey]->lastIp;
$originalUserId = $this->_lists[$cacheKey]->userId;
// These values should always be kept up to date when a list is retrieved from session.
$this->_lists[$cacheKey]->lastIp = Craft::$app->getRequest()->userIP;
$this->_lists[$cacheKey]->userId = Craft::$app->getUser()->getIdentity()->id ?? null;
$changedIp = $originalIp != $this->_lists[$cacheKey]->lastIp;
$changedUserId = $originalUserId != $this->_lists[$cacheKey]->userId;
if ($this->_lists[$cacheKey]->id) {
if ($changedIp || $changedUserId) {
Wishlist::$plugin->getLists()->saveElement($this->_lists[$cacheKey], false);
}
} else if ($forceSave) {
Wishlist::$plugin->getLists()->saveElement($this->_lists[$cacheKey], false);
}
return $this->_lists[$cacheKey];
}
public function getListQueryForOwner(): ListQuery
{
$query = ListElement::find();
$currentUser = Craft::$app->getUser()->getIdentity();
if ($currentUser) {
$query->userId($currentUser->id);
} else {
$query->sessionId($this->getSessionId());
$query->userId(':empty:');
}
return $query;
}
public function isListOwner($list): bool
{
$id = false;
$currentUser = Craft::$app->getUser()->getIdentity();
if ($currentUser) {
$id = $currentUser->id;
} else {
$id = $this->getSessionId();
}
return (int)$list->getOwnerId() === (int)$id;
}
public function createList(): ListElement
{
$listType = Wishlist::$plugin->getListTypes()->getDefaultListType();
$list = new ListElement();
$list->reference = $this->generateReferenceNumber();
$list->typeId = $listType->id;
$list->title = $listType->name;
$list->sessionId = $this->getSessionId();
$list->lastIp = Craft::$app->getRequest()->userIP;
$list->userId = Craft::$app->getUser()->getIdentity()->id ?? null;
return $list;
}
public function purgeInactiveLists(): int
{
$doPurge = Wishlist::$plugin->getSettings()->purgeInactiveLists;
if ($doPurge) {
// Allow batch processing for large items/lists
$limit = 200;
$offset = 0;
$listCount = 0;
do {
$listIds = $this->_getListsIdsToPurge($limit, $offset);
// Taken from craft\services\Elements::deleteElement(); Using the method directly
// takes too many resources since it retrieves the list before deleting it.
// Get element IDs for items first before foreign
$itemIds = [];
foreach ($listIds as $listId) {
$itemIds = array_merge($itemIds, Item::find()
->listId($listId)
->status(null)
->ids());
}
// Delete the elements' table rows, which will cascade across all other InnoDB tables
Db::delete('{{%elements}}', ['id' => $listIds]);
// The searchindex table is probably MyISAM, though
Db::delete('{{%searchindex}}', ['elementId' => $listIds]);
// Remove all items for lists. `wishlist_items` will take care of itself
Db::delete('{{%elements}}', ['id' => $itemIds]);
$offset = $offset + $limit;
$listCount = $listCount + count($listIds);
} while ($listIds);
return $listCount;
}
return 0;
}
public function generateReferenceNumber(): string
{
return StringHelper::randomString(10);
}
public function generateSessionId(): string
{
return md5(uniqid(random_int(0, mt_getrandmax()), true));
}
public function loginHandler(UserEvent $event): void
{
$user = $event->identity;
// Consolidate lists to the user
$this->consolidateListsToUser($user);
}
public function consolidateListsToUser(UserElement $user, array $lists = null): bool
{
try {
/* @var Settings $settings */
$settings = Wishlist::$plugin->getSettings();
$db = Craft::$app->getDb();
// Try and find the default list for the guest
$sessionId = $this->getSessionId();
$db->createCommand()
->update('{{%wishlist_lists}}', ['userId' => $user->id], ['sessionId' => $sessionId, 'userId' => null])
->execute();
Wishlist::log('Moving guest lists for session "' . $sessionId . '" to user "' . $user->id . '"');
if ($settings->mergeLastListOnLogin) {
// Check if we've now got multiple lists for a logged-in user. We need to merge them
$listTypes = Wishlist::$plugin->getListTypes()->getAllListTypes();
// We want to merge lists per list type
foreach ($listTypes as $listType) {
$userLists = ListElement::find()
->userId($user->id)
->typeId($listType->id)
->orderBy('dateCreated asc')
->all();
if ($userLists) {
$oldestList = $userLists[0];
// Update all list items to belong to the oldest list
foreach ($userLists as $userList) {
// Ensure that we check against the title - they should be the same to merge
if ($oldestList->id != $userList->id && $oldestList->title == $userList->title) {
$db->createCommand()
->update('{{%wishlist_items}}', ['listId' => $oldestList->id], ['listId' => $userList->id])
->execute();
// Delete the newer list, now the items have been moved off
$db->createCommand()
->delete('{{%elements}}', ['id' => $userList->id])
->execute();
}
// Now, check if there are any duplicates, and we should check. We ditch the oldest item(s).
if (!$settings->allowDuplicates) {
$db->getSchema()->refresh();
$duplicateItems = $db->createCommand("
SELECT wishlist_items.*
FROM {{%wishlist_items}} [[wishlist_items]]
JOIN (SELECT [[listId]], [[elementId]], [[optionsSignature]], COUNT(*)
FROM {{%wishlist_items}} [[wishlist_items]]
JOIN {{%elements}} [[elements]] ON [[elements.id]] = [[wishlist_items.id]]
WHERE [[elements.dateDeleted]] IS NULL
AND [[listId]] = :list_id
GROUP BY [[listId]], [[elementId]], [[optionsSignature]]
HAVING count(*) > 1 ) temp
ON [[wishlist_items.listId]] = [[temp.listId]]
AND [[wishlist_items.elementId]] = [[temp.elementId]]
AND [[wishlist_items.optionsSignature]] = [[temp.optionsSignature]]
JOIN {{%elements}} [[elements]] ON [[elements.id]] = [[wishlist_items.id]]
WHERE [[elements.dateDeleted]] IS NULL
ORDER BY [[wishlist_items.dateUpdated]] DESC
", [':list_id' => $oldestList->id])->queryAll();
// Save the first occurrence (newest updated) for each item
$processedItems = [];
foreach ($duplicateItems as $duplicateItem) {
$key = implode('_', [$duplicateItem['listId'], $duplicateItem['elementId'], $duplicateItem['optionsSignature']]);
// If first occurrence, save and delete all instances
if (!isset($processedItems[$key])) {
$processedItems[$key] = $duplicateItem;
continue;
}
// Soft-delete the element, just for safety
$now = new DateTime();
$db->createCommand()
->update('{{%elements}}', ['dateDeleted' => Db::prepareDateForDb($now)], ['id' => $duplicateItem['id']])
->execute();
}
}
}
}
}
}
} catch (Throwable $e) {
Wishlist::error(Craft::t('app', '{e} - {f}: {l}.', ['e' => $e->getMessage(), 'f' => $e->getFile(), 'l' => $e->getLine()]));
}
return true;
}
public function addEditUserListInfoTab(array &$context): void
{
if (!$context['isNewUser']) {
$context['tabs']['wishlistInfo'] = [
'label' => Craft::t('wishlist', 'Wishlists'),
'url' => '#wishlistInfo',
];
}
}
public function addEditUserListInfoTabContent(array &$context): string
{
if (!$context['user'] || $context['isNewUser']) {
return '';
}
return Craft::$app->getView()->renderTemplate('wishlist/_includes/_editUserTab', $context);
}
// Private Methods
// =========================================================================
private function getSessionId()
{
/* @var Settings $settings */
$settings = Wishlist::$plugin->getSettings();
$session = Craft::$app->getSession();
$sessionId = $session[$this->listName];
$cookieName = 'Wishlist:sessionId';
// If no session, check for a saved cookie, allowing us to retain lists after sessions have ended
if (!$sessionId) {
$sessionId = Craft::$app->getRequest()->getRawCookies()->getValue($cookieName);
}
// If still no session, we better generate a new one.
if (!$sessionId) {
$sessionId = $this->generateSessionId();
$session->set($this->listName, $sessionId);
$configInterval = ConfigHelper::durationInSeconds($settings->cookieExpiry);
$expiry = (new DateTime())->add(DateTimeHelper::secondsToInterval($configInterval));
// Save this as a cookie for better persistence
$cookie = Craft::createObject(Craft::cookieConfig([
'class' => Cookie::class,
'name' => $cookieName,
'value' => $sessionId,
'httpOnly' => false,
'expire' => $expiry->getTimestamp(),
]));
Craft::$app->getResponse()->getRawCookies()->add($cookie);
}
return $sessionId;
}
private function _getListsIdsToPurge($limit = null, $offset = null): array
{
/* @var Settings $settings */
$settings = Wishlist::$plugin->getSettings();
$configInterval = ConfigHelper::durationInSeconds($settings->purgeInactiveListsDuration);
$edge = new DateTime();
$interval = DateTimeHelper::secondsToInterval($configInterval);
$edge->sub($interval);
$query = (new Query())
->select(['lists.id'])
->from(['{{%wishlist_lists}} lists'])
->join('LEFT OUTER JOIN', '{{%wishlist_items}} items', 'lists.id = [[items.listId]]')
->where('[[lists.dateUpdated]] <= :edge', ['edge' => Db::prepareDateForDb($edge)])
->limit($limit)
->offset($offset);
if ($settings->purgeEmptyListsOnly) {
$query->andWhere(['is', '[[items.listId]]', null]);
}
$userIds = $query->column();
$configInterval = ConfigHelper::durationInSeconds($settings->purgeInactiveGuestListsDuration);
$edge = new DateTime();
$interval = DateTimeHelper::secondsToInterval($configInterval);
$edge->sub($interval);
$query = (new Query())
->select(['lists.id'])
->from(['{{%wishlist_lists}} lists'])
->join('LEFT OUTER JOIN', '{{%wishlist_items}} items', 'lists.id = [[items.listId]]')
->where('[[lists.dateUpdated]] <= :edge', ['edge' => Db::prepareDateForDb($edge)])
->andWhere(['is', '[[lists.userId]]', null])
->limit($limit)
->offset($offset);
if ($settings->purgeEmptyGuestListsOnly) {
$query->andWhere(['is', '[[items.listId]]', null]);
}
$guestIds = $query->column();
return array_merge($userIds, $guestIds);
}
}