Passed
Push — master ( d4c39a...eb00de )
by Nicolaas
03:16
created

SearchApi::writeAndPublish()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
namespace Sunnysideup\SiteWideSearch\Api;
4
5
use SilverStripe\Core\ClassInfo;
6
use SilverStripe\Core\Config\Config;
7
use SilverStripe\Core\Config\Configurable;
8
use SilverStripe\Core\Environment;
9
use SilverStripe\Core\Extensible;
10
use SilverStripe\Core\Injector\Injectable;
11
use SilverStripe\Core\Injector\Injector;
12
use SilverStripe\ORM\ArrayList;
13
use SilverStripe\ORM\DataObject;
14
use SilverStripe\ORM\DB;
15
use SilverStripe\ORM\FieldType\DBDatetime;
16
use SilverStripe\ORM\FieldType\DBString;
17
use SilverStripe\Security\LoginAttempt;
18
use SilverStripe\Security\MemberPassword;
19
use SilverStripe\Security\RememberLoginHash;
20
use SilverStripe\Versioned\ChangeSet;
21
use SilverStripe\Versioned\Versioned;
22
use SilverStripe\Versioned\ReadingMode;
23
use SilverStripe\Versioned\ChangeSetItem;
24
use SilverStripe\View\ArrayData;
25
26
use SilverStripe\SessionManager\Models\LoginSession;
0 ignored issues
show
Bug introduced by
The type SilverStripe\SessionManager\Models\LoginSession was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use Sunnysideup\SiteWideSearch\Helpers\Cache;
28
use Sunnysideup\SiteWideSearch\Helpers\FindEditableObjects;
29
30
class SearchApi
31
{
32
    use Extensible;
33
    use Configurable;
34
    use Injectable;
35
36
    /**
37
     * @var string
38
     */
39
    private const CACHE_NAME = 'SearchApi';
40
41
    protected $debug = false;
42
43
    protected $isQuickSearch = false;
44
45
    protected $searchWholePhrase = false;
46
47
    protected $baseClass = DataObject::class;
48
49
    protected $excludedClasses = [];
50
51
    protected $excludedFields = [];
52
53
    protected $words = [];
54
55
    protected $replace = '';
56
57
    /**
58
     * format is as follows:
59
     * ```php
60
     *      [
61
     *          'AllDataObjects' => [
62
     *              'BaseClassUsed' => [
63
     *                  0 => ClassNameA,
64
     *                  1 => ClassNameB,
65
     *              ],
66
     *          ],
67
     *          'AllValidFields' => [
68
     *              'ClassNameA' => [
69
     *                  'FieldA' => 'FieldA'
70
     *              ],
71
     *          ],
72
     *          'IndexedFields' => [
73
     *              'ClassNameA' => [
74
     *                  0 => ClassNameA,
75
     *                  1 => ClassNameB,
76
     *              ],
77
     *          ],
78
     *          'ListOfTextClasses' => [
79
     *              0 => ClassNameA,
80
     *              1 => ClassNameB,
81
     *          ],
82
     *          'ValidFieldTypes' => [
83
     *              'Varchar(30)' => true,
84
     *              'Boolean' => false,
85
     *          ],
86
     *     ],
87
     * ```
88
     * we use true rather than false to be able to use empty to work out if it has been tested before.
89
     *
90
     * @var array
91
     */
92
    protected $cache = [];
93
94
    private $objects = [];
95
96
    private static $limit_of_count_per_data_object = 999;
97
98
    private static $hours_back_for_recent = 48;
99
100
    private static $limit_per_class_for_recent = 5;
101
102
    private static $default_exclude_classes = [
103
        MemberPassword::class,
104
        LoginAttempt::class,
105
        ChangeSet::class,
106
        ChangeSetItem::class,
107
        RememberLoginHash::class,
108
        LoginSession::class,
109
    ];
110
111
    private static $default_exclude_fields = [
112
        'ClassName',
113
        'LastEdited',
114
        'Created',
115
        'ID',
116
    ];
117
118
    public function setDebug(bool $b): SearchApi
119
    {
120
        $this->debug = $b;
121
122
        return $this;
123
    }
124
125
    public function setIsQuickSearch(bool $b): SearchApi
126
    {
127
        $this->isQuickSearch = $b;
128
129
        return $this;
130
    }
131
132
    public function setSearchWholePhrase(bool $b): SearchApi
133
    {
134
        $this->searchWholePhrase = $b;
135
136
        return $this;
137
    }
138
139
    public function setBaseClass(string $class): SearchApi
140
    {
141
        $this->baseClass = $class;
142
143
        return $this;
144
    }
145
146
    public function setExcludedClasses(array $a): SearchApi
147
    {
148
        $this->excludedClasses = $a;
149
150
        return $this;
151
    }
152
153
    public function setExcludedFields(array $a): SearchApi
154
    {
155
        $this->excludedFields = $a;
156
157
        return $this;
158
    }
159
160
    public function setWordsAsString(string $s): SearchApi
161
    {
162
        $this->words = explode(' ', $s);
163
164
        return $this;
165
    }
166
167
    public function setWords(array $a): SearchApi
168
    {
169
        $this->words = array_combine($a, $a);
170
171
        return $this;
172
    }
173
174
    public function addWord(string $s): SearchApi
175
    {
176
        $this->words[$s] = $s;
177
178
        return $this;
179
    }
180
181
    public function getFileCache()
182
    {
183
        return Injector::inst()->get(Cache::class);
184
    }
185
186
    public function initCache(): self
187
    {
188
        $this->cache = $this->getFileCache()->getCacheValues(self::CACHE_NAME);
189
190
        return $this;
191
    }
192
193
    public function saveCache(): self
194
    {
195
        $this->getFileCache()->setCacheValues(self::CACHE_NAME, $this->cache);
196
197
        return $this;
198
    }
199
200
    // public function __construct()
201
    // {
202
    //     Environment::increaseTimeLimitTo(300);
203
    //     Environment::setMemoryLimitMax(-1);
204
    //     Environment::increaseMemoryLimitTo(-1);
205
    // }
206
207
    public function buildCache(?string $word = ''): SearchApi
208
    {
209
        $this->getLinksInner($word);
210
211
        return $this;
212
213
    }
214
215
    public function getLinks(?string $word = ''): ArrayList
216
    {
217
        return $this->getLinksInner($word);
218
    }
219
220
    protected function getLinksInner(?string $word = ''): ArrayList
221
    {
222
        $this->initCache();
223
224
        //always do first ...
225
        $matches = $this->getMatches($word);
226
227
        $list = $this->turnMatchesIntoList($matches);
228
229
        $this->saveCache();
230
231
        return $list;
232
233
    }
234
235
    public function doReplacement(string $word, string $replace): int
236
    {
237
        $this->initCache();
238
        $count = 0;
239
        // we should have these already.
240
        foreach ($this->objects as $item) {
241
            if ($item->canEdit()) {
242
                $fields = $this->getAllValidFields($item->ClassName);
243
                foreach ($fields as $field) {
244
                    $new = str_replace($word, $replace, $item->{$field});
245
                    if ($new !== $item->{$field}) {
246
                        ++$count;
247
                        $item->{$field} = $new;
248
                        $this->writeAndPublish($item);
249
250
                        if ($this->debug) {
251
                            DB::alteration_message('<h2>Match:  ' . $item->ClassName . $item->ID . '</h2>' . $new . '<hr />');
252
                        }
253
                    }
254
                }
255
            }
256
        }
257
258
        return $count;
259
    }
260
261
    protected function writeAndPublish($item)
262
    {
263
        if ($item->hasExtension(Versioned::class)) {
264
            ReadingMode::validateStage(Versioned::DRAFT);
265
            // is it on live and is live the same as draft
266
            $canBePublished = $item->isPublished() && ! $item->isModifiedOnDraft();
267
            $item->writeToStage(Versioned::DRAFT);
268
            if ($canBePublished) {
269
                $item->publishSingle();
270
            }
271
        } else {
272
            $item->write();
273
        }
274
275
    }
276
277
    protected function getMatches(?string $word = ''): array
278
    {
279
        $startInner = 0;
280
        $startOuter = 0;
281
        if ($this->debug) {
282
            $startOuter = microtime(true);
283
        }
284
        $this->workOutExclusions();
285
        $this->workOutWords($word);
0 ignored issues
show
Bug introduced by
It seems like $word can also be of type null; however, parameter $word of Sunnysideup\SiteWideSear...archApi::workOutWords() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

285
        $this->workOutWords(/** @scrutinizer ignore-type */ $word);
Loading history...
286
        if ($this->debug) {
287
            DB::alteration_message('Words searched for ' . implode(', ', $this->words));
288
        }
289
290
        $array = [];
291
292
        if (count($this->words)) {
293
            foreach ($this->getAllDataObjects() as $className) {
294
                if ($this->debug) {
295
                    DB::alteration_message(' ... Searching in ' . $className);
296
                }
297
298
                if (! in_array($className, $this->excludedClasses, true)) {
299
                    $array[$className] = [];
300
                    $fields = $this->getAllValidFields($className);
301
                    $filterAny = [];
302
                    foreach ($fields as $field) {
303
                        if (! in_array($field, $this->excludedFields, true)) {
304
                            if ($this->debug) {
305
                                DB::alteration_message(' ... ... Searching in ' . $className . '.' . $field);
306
                            }
307
308
                            $filterAny[$field . ':PartialMatch'] = $this->words;
309
                        }
310
                    }
311
312
                    if ([] !== $filterAny) {
313
                        if ($this->debug) {
314
                            $startInner = microtime(true);
315
                            DB::alteration_message(' ... Filter: ' . implode(', ', array_keys($filterAny)));
316
                        }
317
318
                        $array[$className] = $className::get()
319
                            ->filterAny($filterAny)
320
                            ->limit($this->Config()->get('limit_of_count_per_data_object'))
321
                            ->column('ID')
322
                        ;
323
                        if ($this->debug) {
324
                            $elaps = microtime(true) - $startInner;
325
                            DB::alteration_message('search for ' . $className . ' taken : ' . $elaps);
326
                        }
327
                    }
328
329
                    if ($this->debug) {
330
                        DB::alteration_message(' ... No fields in ' . $className);
331
                    }
332
                }
333
334
                if ($this->debug) {
335
                    DB::alteration_message(' ... Skipping ' . $className);
336
                }
337
            }
338
        } else {
339
            $array = $this->getDefaultList();
340
        }
341
342
        if ($this->debug) {
343
            $elaps = microtime(true) - $startOuter;
344
            DB::alteration_message('seconds taken find results: ' . $elaps);
345
        }
346
347
        return $array;
348
    }
349
350
    protected function getDefaultList(): array
351
    {
352
        $back = $this->config()->get('hours_back_for_recent') ?? 24;
353
        $limit = $this->Config()->get('limit_per_class_for_recent') ?? 5;
354
        $threshold = strtotime('-' . $back . ' hours', DBDatetime::now()->getTimestamp());
355
        if (! $threshold) {
356
            $threshold = time() - 86400;
357
        }
358
359
        $array = [];
360
        $classNames = $this->getAllDataObjects();
361
        foreach ($classNames as $className) {
362
            if (! in_array($className, $this->excludedClasses, true)) {
363
                $array[$className] = $className::get()
364
                    ->filter('LastEdited:GreaterThan', date('Y-m-d H:i:s', $threshold))
365
                    ->sort('LastEdited', 'DESC')
366
                    ->limit($limit)
367
                    ->column('ID')
368
                ;
369
            }
370
        }
371
372
        return $array;
373
    }
374
375
    protected function turnArrayIntoObjects(array $matches, ?int $limit = 0): array
376
    {
377
        $start = 0;
378
        if (empty($this->objects)) {
379
            if (empty($limit)) {
380
                $limit = (int) $this->Config()->get('limit_of_count_per_data_object');
381
            }
382
383
            $this->objects = [];
384
            if ($this->debug) {
385
                DB::alteration_message('number of classes: ' . count($matches));
386
            }
387
388
            foreach ($matches as $className => $ids) {
389
                if ($this->debug) {
390
                    $start = microtime(true);
391
                    DB::alteration_message(' ... number of matches for : ' . $className . ': ' . count($ids));
392
                }
393
394
                if (count($ids)) {
395
                    $className = (string) $className;
396
                    $items = $className::get()
397
                        ->filter(['ID' => $ids, 'ClassName' => $className])
398
                        ->limit($limit)
399
                    ;
400
                    foreach ($items as $item) {
401
                        if ($item->canView()) {
402
                            $this->objects[] = $item;
403
                        }
404
                    }
405
                }
406
407
                if ($this->debug) {
408
                    $elaps = microtime(true) - $start;
409
                    DB::alteration_message('seconds taken to find objects in: ' . $className . ': ' . $elaps);
410
                }
411
            }
412
        }
413
414
        return $this->objects;
415
    }
416
417
    protected function turnMatchesIntoList(array $matches): ArrayList
418
    {
419
        // helper
420
        //return values
421
        $list = ArrayList::create();
422
        $finder = Injector::inst()->get(FindEditableObjects::class);
423
        $finder->initCache();
424
425
        $items = $this->turnArrayIntoObjects($matches);
426
        foreach ($items as $item) {
427
            $link = $finder->getLink($item, $this->excludedClasses);
428
            $cmsEditLink = $item->canEdit() ? $finder->getCMSEditLink($item, $this->excludedClasses) : '';
429
            $list->push(
430
                ArrayData::create(
431
                    [
432
                        'HasLink' => (bool) $link,
433
                        'HasCMSEditLink' => (bool) $cmsEditLink,
434
                        'Link' => $link,
435
                        'CMSEditLink' => $cmsEditLink,
436
                        'Object' => $item,
437
                        'SiteWideSearchSortValue' => $this->getSortValue($item),
438
                    ]
439
                )
440
            );
441
        }
442
443
        $finder->saveCache();
444
445
        return $list->sort('SiteWideSearchSortValue', 'ASC');
446
    }
447
448
    protected function getSortValue($item)
449
    {
450
        $className = $item->ClassName;
451
        $fields = $this->getAllValidFields($className);
452
        $fullWords = implode(' ', $this->words);
453
454
        $done = false;
455
        $score = 0;
456
        if ($fullWords) {
457
            $fieldValues = [];
458
            $fieldValuesAll = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $fieldValuesAll is dead and can be removed.
Loading history...
459
            foreach ($fields as $field) {
460
                $fieldValues[$field] = strtolower(strip_tags($item->{$field}));
461
            }
462
463
            $fieldValuesAll = implode(' ', $fieldValues);
464
            $testWords = array_merge(
465
                [$fullWords],
466
                $this->words
467
            );
468
            $testWords = array_unique($testWords);
469
            foreach ($testWords as $wordKey => $word) {
470
                //match a exact field to full words / one word
471
                $fullWords = ! (bool) $wordKey;
472
                if (false === $done) {
473
                    $count = 0;
474
                    foreach ($fieldValues as $fieldValue) {
475
                        ++$count;
476
                        if ($fieldValue === $word) {
477
                            $score += (int) $wordKey + $count;
478
                            $done = true;
479
480
                            break;
481
                        }
482
                    }
483
                }
484
485
                // the full string / any of the words are present?
486
                if (false === $done) {
487
                    $pos = strpos($fieldValuesAll, $word);
488
                    if (false !== $pos) {
489
                        $score += (($pos + 1) / strlen($word)) * 1000;
490
                        $done = true;
491
                    }
492
                }
493
494
                // all individual words are present
495
                if (false === $done) {
496
                    if ($fullWords) {
497
                        $score += 1000;
498
                        $allMatch = true;
499
                        foreach ($this->words as $tmpWord) {
500
                            $pos = strpos($fieldValuesAll, $tmpWord);
501
                            if (false === $pos) {
502
                                $allMatch = false;
503
504
                                break;
505
                            }
506
                        }
507
508
                        if ($allMatch) {
509
                            $done = true;
510
                        }
511
                    }
512
                }
513
            }
514
        }
515
516
        //the older the item, the higher the scoare
517
        //1104622247 = 1 jan 2005
518
        return $score + (1 / (strtotime($item->LastEdited) - 1104537600));
519
    }
520
521
    protected function workOutExclusions()
522
    {
523
        $this->excludedClasses = array_unique(
524
            array_merge(
525
                $this->Config()->get('default_exclude_classes'),
526
                $this->excludedClasses
527
            )
528
        );
529
        $this->excludedFields = array_unique(
530
            array_merge(
531
                $this->Config()->get('default_exclude_fields'),
532
                $this->excludedFields
533
            )
534
        );
535
    }
536
537
    protected function workOutWords(string $word = ''): array
538
    {
539
        if ($this->searchWholePhrase) {
540
            $this->words = [implode(' ', $this->words)];
541
        }
542
543
        if ($word) {
544
            $this->words[] = $word;
545
        }
546
547
        if (! count($this->words)) {
548
            user_error('No word has been provided');
549
        }
550
551
        $this->words = array_unique($this->words);
552
        $this->words = array_filter($this->words);
553
        $this->words = array_map('strtolower', $this->words);
554
555
        return $this->words;
556
    }
557
558
    protected function getAllDataObjects(): array
559
    {
560
        if ($this->debug) {
561
            DB::alteration_message('Base Class: ' . $this->baseClass);
562
        }
563
564
        if (! isset($this->cache['AllDataObjects'][$this->baseClass])) {
565
            $this->cache['AllDataObjects'][$this->baseClass] = array_values(
566
                ClassInfo::subclassesFor($this->baseClass, false)
567
            );
568
            $this->cache['AllDataObjects'][$this->baseClass] = array_unique($this->cache['AllDataObjects'][$this->baseClass]);
569
        }
570
571
        return $this->cache['AllDataObjects'][$this->baseClass];
572
    }
573
574
    protected function getAllValidFields(string $className): array
575
    {
576
        if (! isset($this->cache['AllValidFields'][$className])) {
577
            $array = [];
578
            $fullList = Config::inst()->get($className, 'db');
579
            if (is_array($fullList)) {
580
                if ($this->isQuickSearch) {
581
                    $fullList = $this->getIndexedFields(
582
                        $className,
583
                        $fullList
584
                    );
585
                }
586
587
                foreach ($fullList as $name => $type) {
588
                    if ($this->isValidFieldType($className, $name, $type)) {
589
                        $array[] = $name;
590
                    }
591
                }
592
            }
593
594
            $this->cache['AllValidFields'][$className] = $array;
595
        }
596
597
        return $this->cache['AllValidFields'][$className];
598
    }
599
600
    protected function getIndexedFields(string $className, array $dbFields): array
601
    {
602
        if (! isset($this->cache['IndexedFields'][$className])) {
603
            $this->cache['IndexedFields'][$className] = [];
604
            $indexes = Config::inst()->get($className, 'indexes');
605
            if (is_array($indexes)) {
606
                foreach ($indexes as $key => $field) {
607
                    if (isset($dbFields[$key])) {
608
                        $this->cache['IndexedFields'][$className][$key] = $dbFields[$key];
609
                    } elseif (is_array($field)) {
610
                        foreach ($field as $test) {
611
                            if (is_array($test)) {
612
                                if (isset($test['columns'])) {
613
                                    $test = $test['columns'];
614
                                } else {
615
                                    continue;
616
                                }
617
                            }
618
619
                            $testArray = explode(',', $test);
620
                            foreach ($testArray as $testInner) {
621
                                $testInner = trim($testInner);
622
                                if (isset($dbFields[$testInner])) {
623
                                    $this->cache['IndexedFields'][$className][$testInner] = $dbFields[$key];
624
                                }
625
                            }
626
                        }
627
                    }
628
                }
629
            }
630
        }
631
632
        return $this->cache['IndexedFields'][$className];
633
    }
634
635
    protected function isValidFieldType(string $className, string $fieldName, string $type): bool
636
    {
637
        if (! isset($this->cache['ValidFieldTypes'][$type])) {
638
            $this->cache['ValidFieldTypes'][$type] = false;
639
            $singleton = Injector::inst()->get($className);
640
            $field = $singleton->dbObject($fieldName);
641
            if ($field instanceof DBString) {
642
                $this->cache['ValidFieldTypes'][$type] = true;
643
            }
644
        }
645
646
        return $this->cache['ValidFieldTypes'][$type];
647
    }
648
}
649