/
PageFinder.php
2208 lines (1889 loc) · 73.8 KB
/
PageFinder.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 namespace ProcessWire;
class PageFinderException extends WireException { }
class PageFinderSyntaxException extends PageFinderException { }
/**
* ProcessWire PageFinder
*
* Matches selector strings to pages
*
* ProcessWire 3.x, Copyright 2016 by Ryan Cramer
* https://processwire.com
*
* Hookable methods:
* =================
* @method array|DatabaseQuerySelect find(Selectors $selectors, $options = array())
* @method DatabaseQuerySelect getQuery($selectors, array $options)
* @method string getQueryAllowedTemplatesWhere(DatabaseQuerySelect $query, $where)
* @method void getQueryJoinPath(DatabaseQuerySelect $query, $selector)
*
*/
class PageFinder extends Wire {
/**
* Options (and their defaults) that may be provided as the 2nd argument to find()
*
*/
protected $defaultOptions = array(
/**
* Specify that you only want to find 1 page and don't need info for pagination
*
*/
'findOne' => false,
/**
* Specify that it's okay for hidden pages to be included in the results
*
*/
'findHidden' => false,
/**
* Specify that it's okay for hidden AND unpublished pages to be included in the results
*
*/
'findUnpublished' => false,
/**
* Specify that it's okay for hidden AND unpublished AND trashed pages to be included in the results
*
*/
'findTrash' => false,
/**
* Specify that no page should be excluded - results can include unpublished, trash, system, no-access pages, etc.
*
*/
'findAll' => false,
/**
* This is an optimization used by the Pages::find method, but we observe it here as we may be able
* to apply some additional optimizations in certain cases. For instance, if loadPages=false, then
* we can skip retrieval of IDs and omit sort fields.
*
*/
'loadPages' => true,
/**
* When true, this function returns array of arrays containing page ID, parent ID, template ID and score.
* When false, returns only an array of page IDs. returnVerbose=true is required by most usage from Pages
* class. False is only for specific cases.
*
*/
'returnVerbose' => true,
/**
* When true, only the DatabaseQuery object is returned by find(), for internal use.
*
*/
'returnQuery' => false,
/**
* Whether the total quantity of matches should be determined and accessible from getTotal()
*
* null: determine automatically (disabled when limit=1, enabled in all other cases)
* true: always calculate total
* false: never calculate total
*
*/
'getTotal' => null,
/**
* Method to use when counting total records
*
* If 'count', total will be calculated using a COUNT(*).
* If 'calc, total will calculate using SQL_CALC_FOUND_ROWS.
* If blank or something else, method will be determined automatically.
*
*/
'getTotalType' => 'calc',
/**
* Only start loading pages after this ID
*
*/
'startAfterID' => 0,
/**
* Stop and load no more if a page having this ID is found
*
*/
'stopBeforeID' => 0,
/**
* For internal use with startAfterID or stopBeforeID (when combined with a 'limit=n' selector)
*
*/
'softLimit' => 0,
/**
* Reverse whatever sort is specified
*
*/
'reverseSort' => false,
/**
* Allow use of _custom="another selector" in Selectors?
*
*/
'allowCustom' => false,
/**
* Use sortsAfter feature where PageFinder lets you perform the sorting manually after the find()
*
* When in use, you can access the PageFinder::getSortsAfter() method to retrieve an array of sort
* fields that should be sent to PageArray::sort()
*
* So far this option seems to add more overhead in most cases (rather than save it) so recommend not
* using it. Kept for further experimenting.
*
*/
'useSortsAfter' => false,
);
protected $fieldgroups;
protected $getTotal = true; // whether to find the total number of matches
protected $getTotalType = 'calc'; // May be: 'calc', 'count', or blank to auto-detect.
protected $total = 0;
protected $limit = 0;
protected $start = 0;
protected $parent_id = null;
protected $templates_id = null;
protected $checkAccess = true;
protected $getQueryNumChildren = 0; // number of times the function has been called
protected $lastOptions = array();
protected $extraOrSelectors = array(); // one from each field must match
protected $sortsAfter = array(); // apply these sorts after pages loaded
protected $reverseAfter = false; // reverse order after load?
// protected $extraSubSelectors = array(); // subselectors that are added in after getQuery()
// protected $extraJoins = array();
// protected $nativeWheres = array(); // where statements for native fields, to be reused in subselects where appropriate.
/**
* Pre-process the selectors to add Page status checks
*
* @param Selectors $selectors
* @param array $options
*
*/
protected function setupStatusChecks(Selectors $selectors, array &$options) {
$maxStatus = null;
$limit = 0; // for getTotal auto detection
$start = 0;
$limitSelector = null;
$checkAccessSpecified = false;
$hasParents = array(); // requests for parent(s) in the selector
$hasSort = false; // whether or not a sort is requested
foreach($selectors as $key => $selector) {
$fieldName = $selector->field;
if($fieldName == 'status') {
$value = $selector->value;
if(!ctype_digit("$value")) {
// allow use of some predefined labels for Page statuses
if($value == 'hidden') $selector->value = Page::statusHidden;
else if($value == 'unpublished') $selector->value = Page::statusUnpublished;
else if($value == 'draft') $selector->value = Page::statusDraft;
else if($value == 'versions') $selector->value = Page::statusVersions;
else if($value == 'locked') $selector->value = Page::statusLocked;
else if($value == 'trash') $selector->value = Page::statusTrash;
else if($value == 'max') $selector->value = Page::statusMax;
else $selector->value = 1;
}
$not = false;
if(($selector->operator == '!=' && !$selector->not) || ($selector->not && $selector->operator == '=')) {
$s = $this->wire(new SelectorBitwiseAnd('status', $selector->value));
$s->not = true;
$not = true;
$selectors[$key] = $s;
} else if($selector->operator == '=' || ($selector->operator == '!=' && $selector->not)) {
$selectors[$key] = $this->wire(new SelectorBitwiseAnd('status', $selector->value));
} else {
$not = $selector->not;
// some other operator like: >, <, >=, <=
}
if(!$not && (is_null($maxStatus) || $selector->value > $maxStatus)) $maxStatus = (int) $selector->value;
} else if($fieldName == 'include' && $selector->operator == '=' && in_array($selector->value, array('hidden', 'all', 'unpublished', 'trash'))) {
if($selector->value == 'hidden') $options['findHidden'] = true;
else if($selector->value == 'unpublished') $options['findUnpublished'] = true;
else if($selector->value == 'trash') $options['findTrash'] = true;
else if($selector->value == 'all') $options['findAll'] = true;
$selectors->remove($key);
} else if($fieldName == 'check_access' || $fieldName == 'checkAccess') {
$this->checkAccess = ((int) $selector->value) > 0 ? true : false;
$checkAccessSpecified = true;
$selectors->remove($key);
} else if($fieldName == 'limit') {
// for getTotal auto detect
$limit = (int) $selector->value;
$limitSelector = $selector;
} else if($fieldName == 'start') {
// for getTotal auto detect
$start = (int) $selector->value;
} else if($fieldName == 'sort') {
// sorting is not needed if we are only retrieving totals
if($options['loadPages'] === false) $selectors->remove($selector);
$hasSort = true;
} else if($fieldName == 'parent' || $fieldName == 'parent_id') {
$hasParents[] = $selector->value;
} else if($fieldName == 'getTotal' || $fieldName == 'get_total') {
// whether to retrieve the total, and optionally what type: calc or count
// this applies only if user hasn't themselves created a field called getTotal or get_total
if(!$this->wire('fields')->get($fieldName)) {
if(ctype_digit("$selector->value")) {
$options['getTotal'] = (bool) $selector->value;
} else if(in_array($selector->value, array('calc', 'count'))) {
$options['getTotal'] = true;
$options['getTotalType'] = $selector->value;
}
$selectors->remove($selector);
}
}
} // foreach($selectors)
if(!is_null($maxStatus) && empty($options['findAll']) && empty($options['findUnpublished'])) {
// if a status was already present in the selector, without a findAll/findUnpublished, then just make sure the page isn't unpublished
if($maxStatus < Page::statusUnpublished) {
$selectors->add(new SelectorLessThan('status', Page::statusUnpublished));
}
} else if($options['findAll']) {
// findAll option means that unpublished, hidden, trash, system may be included
if(!$checkAccessSpecified) $this->checkAccess = false;
} else if($options['findHidden']) {
// findHidden option, apply optimizations enabling hidden pages to be loaded
$selectors->add(new SelectorLessThan('status', Page::statusUnpublished));
} else if($options['findUnpublished']) {
$selectors->add(new SelectorLessThan('status', Page::statusTrash));
} else if($options['findTrash']) {
$selectors->add(new SelectorLessThan('status', Page::statusDeleted));
} else {
// no status is present, so exclude everything hidden and above
$selectors->add(new SelectorLessThan('status', Page::statusHidden));
}
if($options['findOne']) {
// findOne option is never paginated, always starts at 0
$selectors->add(new SelectorEqual('start', 0));
if(empty($options['startAfterID']) && empty($options['stopBeforeID'])) {
$selectors->add(new SelectorEqual('limit', 1));
}
// getTotal default is false when only finding 1 page
if(is_null($options['getTotal'])) $options['getTotal'] = false;
} else if(!$limit && !$start) {
// getTotal is not necessary since there is no limit specified (getTotal=same as count)
if(is_null($options['getTotal'])) $options['getTotal'] = false;
} else {
// get Total default is true when finding multiple pages
if(is_null($options['getTotal'])) $options['getTotal'] = true;
}
if(count($hasParents) == 1 && !$hasSort) {
// if single parent specified and no sort requested, default to the sort specified with the requested parent
try {
$parent = $this->wire('pages')->get(reset($hasParents));
} catch(\Exception $e) {
// don't try to add sort
$parent = null;
}
if($parent && $parent->id) {
$sort = $parent->template->sortfield;
if(!$sort) $sort = $parent->sortfield;
if($sort) $selectors->add(new SelectorEqual('sort', $sort));
}
}
if(!$options['findOne'] && $limitSelector && ($options['startAfterID'] || $options['stopBeforeID'])) {
$options['softLimit'] = $limitSelector->value;
$selectors->remove($limitSelector);
}
$this->lastOptions = $options;
}
/**
* Return all pages matching the given selector.
*
* @param Selectors|string|array $selectors Selectors object or selector string
* @param array $options
* - `findOne` (bool): Specify that you only want to find 1 page and don't need info for pagination (default=false).
* - `findHidden` (bool): Specify that it's okay for hidden pages to be included in the results (default=false).
* - `findUnpublished` (bool): Specify that it's okay for hidden AND unpublished pages to be included in the
* results (default=false).
* - `findTrash` (bool): Specify that it's okay for hidden AND unpublished AND trashed pages to be included in the
* results (default=false).
* - `findAll` (bool): Specify that no page should be excluded - results can include unpublished, trash, system,
* no-access pages, etc. (default=false)
* - `getTotal` (bool|null): Whether the total quantity of matches should be determined and accessible from
* getTotal() method call.
* - null: determine automatically (default is disabled when limit=1, enabled in all other cases).
* - true: always calculate total.
* - false: never calculate total.
* - `getTotalType` (string): Method to use to get total, specify 'count' or 'calc' (default='calc').
* - `returnQuery` (bool): When true, only the DatabaseQuery object is returned by find(), for internal use. (default=false)
* - `loadPages` (bool): This is an optimization used by the Pages::find() method, but we observe it here as we
* may be able to apply some additional optimizations in certain cases. For instance, if loadPages=false, then
* we can skip retrieval of IDs and omit sort fields. (default=true)
* - `stopBeforeID` (int): Stop loading pages once a page matching this ID is found. Page having this ID will be
* excluded as well (default=0).
* - `startAfterID` (int): Start loading pages once a page matching this ID is found. Page having this ID will be
* excluded as well (default=0).
* - `reverseSort` (bool): Reverse whatever sort is specified.
* - `returnVerbose` (bool): When true, this function returns array of arrays containing page ID, parent ID,
* template ID and score. When false, returns only an array of page IDs. True is required by most usage from
* Pages class. False is only for specific cases.
* - `allowCustom` (bool): Whether or not to allow _custom='selector string' type values (default=false).
* - `useSortsAfter` (bool): When true, PageFinder may ask caller to perform sort manually in some cases (default=false).
* @return array|DatabaseQuerySelect
* @throws PageFinderException
*
*/
public function ___find($selectors, array $options = array()) {
if(is_string($selectors) || is_array($selectors)) {
$selectors = new Selectors($selectors);
} else if(!$selectors instanceof Selectors) {
throw new PageFinderException("find() requires Selectors object or string");
}
$this->fieldgroups = $this->wire('fieldgroups');
$options = array_merge($this->defaultOptions, $options);
$this->parent_id = null;
$this->templates_id = null;
$this->checkAccess = true;
$this->getQueryNumChildren = 0;
$this->setupStatusChecks($selectors, $options);
// move getTotal option to a class property, after setupStatusChecks
$this->getTotal = $options['getTotal'];
$this->getTotalType = $options['getTotalType'] == 'count' ? 'count' : 'calc';
unset($options['getTotal']); // so we get a notice if we try to access it
$stopBeforeID = (int) $options['stopBeforeID'];
$startAfterID = (int) $options['startAfterID'];
$database = $this->wire('database');
$matches = array();
/** @var DatabaseQuerySelect $query */
$query = $this->getQuery($selectors, $options);
//if($this->wire('config')->debug) $query->set('comment', "Selector: " . (string) $selectors);
if($options['returnQuery']) return $query;
if($options['loadPages'] || $this->getTotalType == 'calc') {
try {
$stmt = $query->prepare();
$database->execute($stmt);
$error = '';
} catch(\Exception $e) {
$this->trackException($e, true);
$error = $e->getMessage();
$stmt = null;
}
if($error) {
$this->log($error);
throw new PageFinderException($error);
}
if($options['loadPages']) {
$softCnt = 0; // for startAfterID when combined with 'limit'
/** @noinspection PhpAssignmentInConditionInspection */
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
if($startAfterID > 0) {
if($row['id'] != $startAfterID) continue;
$startAfterID = -1; // -1 indicates that recording may start
continue;
}
if($stopBeforeID && $row['id'] == $stopBeforeID) {
if($options['findOne']) {
$matches = array(end($matches));
} else if($options['softLimit']) {
$matches = array_slice($matches, -1 * $options['softLimit']);
}
break;
}
if($options['returnVerbose']) {
// determine score for this row
$score = 0;
foreach($row as $k => $v) if(strpos($k, '_score') === 0) {
$score += $v;
unset($row[$k]);
}
$row['score'] = $score; // @todo do we need this anymore?
$matches[] = $row;
} else {
$matches[] = (int) $row['id'];
}
if($startAfterID === -1) {
// -1 indicates that recording may start
if($options['findOne']) {
break;
} else if($options['softLimit'] && ++$softCnt >= $options['softLimit']) {
break;
}
}
}
}
$stmt->closeCursor();
}
if($this->getTotal) {
if($this->getTotalType === 'count') {
$query->set('select', array('COUNT(*)'));
$query->set('orderby', array());
$query->set('groupby', array());
$query->set('limit', array());
$stmt = $query->execute();
$errorInfo = $stmt->errorInfo();
if($stmt->errorCode() > 0) throw new PageFinderException($errorInfo[2]);
list($this->total) = $stmt->fetch(\PDO::FETCH_NUM);
$stmt->closeCursor();
} else {
$this->total = (int) $database->query("SELECT FOUND_ROWS()")->fetchColumn();
}
} else {
$this->total = count($matches);
}
$this->lastOptions = $options;
if($this->reverseAfter) $matches = array_reverse($matches);
return $matches;
}
/**
* Same as find() but returns just a simple array of page IDs without any other info
*
* @param Selectors $selectors
* @param array $options
* @return array of page IDs
*
*/
public function findIDs(Selectors $selectors, $options = array()) {
$options['returnVerbose'] = false;
return $this->find($selectors, $options);
}
/**
* Pre-process given Selectors object
*
* @param Selectors $selectors
* @param array $options
*
*/
protected function preProcessSelectors(Selectors $selectors, $options = array()) {
$sortAfterSelectors = array();
$sortSelectors = array();
$start = null;
$limit = null;
$eq = null;
foreach($selectors as $selector) {
$field = $selector->field;
if($field === '_custom') {
$selectors->remove($selector);
if(!empty($options['allowCustom'])) {
$_selectors = $this->wire(new Selectors($selector->value()));
/** @var Selectors $_selectors */
foreach($_selectors as $s) $selectors->add($s);
}
} else if($field === 'sort') {
$sortSelectors[] = $selector;
if(!empty($options['useSortsAfter']) && $selector->operator == '=' && strpos($selector->value, '.') === false) {
$sortAfterSelectors[] = $selector;
}
} else if($field === 'limit') {
$limit = (int) $selector->value;
} else if($field === 'start') {
$start = (int) $selector->value;
} else if($field == 'eq' || $field == 'index') {
if($this->wire('fields')->get($field)) continue;
$value = $selector->value;
if($value === 'first') {
$eq = 0;
} else if($value === 'last') {
$eq = -1;
} else {
$eq = (int) $value;
}
$selectors->remove($selector);
}
}
if(!is_null($eq)) {
if($eq === -1) {
$limit = -1;
$start = null;
} else if($eq === 0) {
$start = 0;
$limit = 1;
} else {
$start = $eq;
$limit = 1;
}
}
if(!$limit && !$start && count($sortAfterSelectors)
&& $options['returnVerbose'] && !empty($options['useSortsAfter'])
&& empty($options['startAfterID']) && empty($options['stopBeforeID'])) {
// the `useSortsAfter` option is enabled and potentially applicable
$sortsAfter = array();
foreach($sortAfterSelectors as $n => $selector) {
if(!$n && $this->wire('pages')->loader()->isNativeColumn($selector->value)) {
// first iteration only, see if it's a native column and prevent sortsAfter if so
break;
}
if(strpos($selector->value, '.') !== false) {
// we don't supports sortsAfter for subfields, so abandon entirely
$sortsAfter = array();
break;
}
if($selector->operator != '=') {
// sort property being used for something else that we don't recognize
continue;
}
$sortsAfter[] = $selector->value;
$selectors->remove($selector);
}
$this->sortsAfter = $sortsAfter;
}
if($limit !== null && $limit < 0) {
// negative limit value means we pull results from end rather than start
if($start !== null && $start < 0) {
// we don't support a double negative, so double negative makes a positive
$start = abs($start);
$limit = abs($limit);
} else if($start > 0) {
$start = $start - abs($limit);
$limit = abs($limit);
} else {
$this->reverseAfter = true;
$limit = abs($limit);
}
}
if($start !== null && $start < 0) {
// negative start value means we start from a value from the end rather than the start
if($limit) {
// determine how many pages total and subtract from that to get start
$o = $options;
$o['getTotal'] = true;
$o['loadPages'] = false;
$o['returnVerbose'] = false;
$sel = clone $selectors;
foreach($sel as $s) {
if($s->field == 'limit' || $s->field == 'start') $sel->remove($s);
}
$sel->add(new SelectorEqual('limit', 1));
$finder = new PageFinder();
$this->wire($finder);
$finder->find($sel);
$total = $finder->getTotal();
$start = abs($start);
$start = $total - $start;
if($start < 0) $start = 0;
} else {
// same as negative limit
$this->reverseAfter = true;
$limit = abs($start);
$start = null;
}
}
if($this->reverseAfter) {
// reverse the sorts
foreach($sortSelectors as $s) {
if($s->operator != '=' || ctype_digit($s->value)) continue;
if(strpos($s->value, '-') === 0) {
$s->value = ltrim($s->value, '-');
} else {
$s->value = '-' . $s->value;
}
}
}
$this->limit = $limit;
$this->start = $start;
}
/**
* Pre-process the given selector to perform any necessary replacements
*
* This is primarily used to handle sub-selections, i.e. "bar=foo, id=[this=that, foo=bar]"
* and OR-groups, i.e. "(bar=foo), (foo=bar)"
*
* @param Selector $selector
* @param Selectors $selectors
* @param array $options
* @param int $level
* @return bool|Selector Returns false if selector should be skipped over by getQuery(), returns Selector otherwise
* @throws PageFinderSyntaxException
*
*/
protected function preProcessSelector(Selector $selector, Selectors $selectors, array $options, $level = 0) {
$quote = $selector->quote;
$fields = $selector->fields;
$hasDoubleDot = false;
foreach($fields as $fn) {
$dot = strpos($fn, '.');
if($dot && strrpos($fn, '.') !== $dot) {
$hasDoubleDot = true;
break;
}
}
if($quote == '[') {
// selector contains another embedded selector that we need to convert to page IDs
// i.e. field=[id>0, name=something, this=that]
$this->preProcessSubSelector($selector, $selectors);
} else if($quote == '(') {
// selector contains an OR group (quoted selector)
// at least one (quoted selector) must match for each field specified in front of it
$groupName = $this->wire('sanitizer')->fieldName($selector->getField('string'));
if(!$groupName) $groupName = 'none';
if(!isset($this->extraOrSelectors[$groupName])) $this->extraOrSelectors[$groupName] = array();
if($selector->value instanceof Selectors) {
$this->extraOrSelectors[$groupName][] = $selector->value;
} else {
$this->extraOrSelectors[$groupName][] = $this->wire(new Selectors($selector->value));
}
return false;
} else if($hasDoubleDot) {
// has an "a.b.c" type string in the field, convert to a sub-selector
if(count($fields) > 1) {
throw new PageFinderSyntaxException("Multi-dot 'a.b.c' type selectors may not be used with OR '|' fields");
}
$fn = reset($fields);
$parts = explode('.', $fn);
$fieldName = array_shift($parts);
$field = $this->isPageField($fieldName);
if($field) {
// we have a workable page field
/** @var Selectors $_selectors */
if($options['findAll']) $s = "include=all";
else if($options['findHidden']) $s = "include=hidden";
else if($options['findUnpublished']) $s = "include=unpublished";
else $s = '';
$_selectors = $this->wire(new Selectors($s));
$_selector = $_selectors->create(implode('.', $parts), $selector->operator, $selector->values);
$_selectors->add($_selector);
$sel = new SelectorEqual("$fieldName", $_selectors);
$sel->quote = '[';
if(!$level) $selectors->replace($selector, $sel);
$selector = $sel;
$sel = $this->preProcessSelector($sel, $selectors, $options, $level + 1);
if($sel) $selector = $sel;
} else {
// not a page field
}
}
return $selector;
}
/*
* This turns out to be a lot slower than preProcessSubSelector(), but kept here for additional experiments
*
protected function preProcessSubquery(Selector $selector) {
$finder = $this->wire(new PageFinder());
$selectors = $selector->getValue();
if(!$selectors instanceof Selectors) return true; // not a sub-selector
$subfield = '';
$fieldName = $selector->field;
if(is_array($fieldName)) return true; // we don't allow OR conditions for field here
if(strpos($fieldName, '.')) list($fieldName, $subfield) = explode('.', $fieldName);
$field = $this->wire('fields')->get($fieldName);
if(!$field) return true; // does not resolve to a known field
$query = $finder->find($selectors, array(
'returnQuery' => true,
'returnVerbose' => false
));
$database = $this->wire('database');
$table = $database->escapeTable($field->getTable());
if($subfield == 'id' || !$subfield) {
$subfield = 'data';
} else {
$subfield = $database->escapeCol($this->wire('sanitizer')->fieldName($subfield));
}
if(!$table || !$subfield) return true;
static $n = 0;
$n++;
$tableAlias = "_subquery_{$n}_$table";
$join = "$table AS $tableAlias ON $tableAlias.pages_id=pages.id AND $tableAlias.$subfield IN (" . $query->getQuery() . ")";
echo $join . "<br />";
$this->extraJoins[] = $join;
}
*/
/**
* Pre-process a Selector that has a [quoted selector] embedded within its value
*
* @param Selector $selector
* @param Selectors $parentSelectors
*
*/
protected function preProcessSubSelector(Selector $selector, Selectors $parentSelectors) {
// Selector contains another embedded selector that we need to convert to page IDs.
// Example: "field=[id>0, name=something, this=that]" converts to "field.id=123|456|789"
$selectors = $selector->getValue();
if(!$selectors instanceof Selectors) return;
$hasTemplate = false;
$hasParent = false;
$hasInclude = false;
foreach($selectors as $s) {
if(is_array($s->field)) continue;
if($s->field == 'template') $hasTemplate = true;
if($s->field == 'parent' || $s->field == 'parent_id' || $s->field == 'parent.id') $hasParent = true;
if($s->field == 'include' || $s->field == 'status') $hasInclude = true;
}
if(!$hasInclude) {
// see if parent selector has an include mode, and copy it over to this one
foreach($parentSelectors as $s) {
if($s->field == 'include' || $s->field == 'status' || $s->field == 'check_access') {
$selectors->add(clone $s);
}
}
}
// special handling for page references, detect if parent or template is defined,
// and add it to the selector if available. This makes it faster.
if(!$hasTemplate || !$hasParent) {
$fields = is_array($selector->field) ? $selector->field : array($selector->field);
$templates = array();
$parents = array();
$findSelector = '';
foreach($fields as $fieldName) {
if(strpos($fieldName, '.') !== false) {
/** @noinspection PhpUnusedLocalVariableInspection */
list($unused, $fieldName) = explode('.', $fieldName);
}
$field = $this->wire('fields')->get($fieldName);
if(!$field) continue;
if(!$hasTemplate && $field->template_id) {
if(is_array($field->template_id)) {
$templates = array_merge($templates, $field->template_id);
} else {
$templates[] = (int) $field->template_id;
}
}
if(!$hasParent && $field->parent_id) {
if(strpos($field->type->className(), 'FieldtypeRepeater') !== false) {
// repeater items not stored directly under parent_id, but as another parent under parent_id.
// so we use has_parent instead here
$selectors->prepend(new SelectorEqual('has_parent', $field->parent_id));
} else {
// direct parent: FieldtypePage or similar
$parents[] = (int) $field->parent_id;
}
}
if($field->findPagesSelector && count($fields) == 1) $findSelector = $field->findPagesSelector;
}
if(count($templates)) $selectors->prepend(new SelectorEqual('template', $templates));
if(count($parents)) $selectors->prepend(new SelectorEqual('parent_id', $parents));
if($findSelector) {
foreach(new Selectors($findSelector) as $s) {
// add everything from findSelector, except for dynamic/runtime 'page.[something]' vars
if(strpos($s->getField('string'), 'page.') === 0 || strpos($s->getValue('string'), 'page.') === 0) continue;
$selectors->append($s);
}
}
}
$pageFinder = $this->wire(new PageFinder());
$ids = $pageFinder->findIDs($selectors);
$fieldNames = $selector->fields;
$fieldName = reset($fieldNames);
$natives = array('parent', 'parent.id', 'parent_id', 'children', 'children.id', 'child', 'child.id');
// populate selector value with array of page IDs
if(count($ids) == 0) {
// subselector resulted in 0 matches
// force non-match for this subselector by populating 'id' subfield to field name(s)
$fieldNames = array();
foreach($selector->fields as $key => $fieldName) {
if(strpos($fieldName, '.') !== false) {
// reduce fieldName to just field name without subfield name
/** @noinspection PhpUnusedLocalVariableInspection */
list($fieldName, $subname) = explode('.', $fieldName); // subname intentionally unused
}
$field = $this->isPageField($fieldName);
if(is_string($field) && in_array($field, $natives)) {
// prevent matching something like parent_id=0, as that would match homepage
$fieldName = 'id';
} else if($field) {
$fieldName .= '.id';
} else {
// non-Page value field
$selector->forceMatch = false;
}
$fieldNames[$key] = $fieldName;
}
$selector->fields = $fieldNames;
$selector->value = 0;
} else if(in_array($fieldName, $natives)) {
// i.e. parent, parent_id, children, etc
$selector->value = count($ids) > 1 ? $ids : reset($ids);
} else {
$isPageField = $this->isPageField($fieldName, true);
if($isPageField) {
// FieldtypePage fields can use the "," separation syntax for speed optimization
$selector->value = count($ids) > 1 ? implode(',', $ids) : reset($ids);
} else {
// otherwise use array
$selector->value = count($ids) > 1 ? $ids : reset($ids);
}
}
$selector->quote = '';
}
/**
* Given one or more selectors, create the SQL query for finding pages.
*
* @TODO split this method up into more parts, it's too long
*
* @param Selectors $selectors Array of selectors.
* @param array $options
* @return DatabaseQuerySelect
* @throws PageFinderSyntaxException
*
*/
protected function ___getQuery($selectors, array $options) {
$where = '';
$whereBindValues = array();
$cnt = 1;
$fieldCnt = array(); // counts number of instances for each field to ensure unique table aliases for ANDs on the same field
$lastSelector = null;
$sortSelectors = array(); // selector containing 'sort=', which gets added last
$joins = array();
// $this->extraJoins = array();
$database = $this->wire('database');
$this->preProcessSelectors($selectors, $options);
/** @var DatabaseQuerySelect $query */
$query = $this->wire(new DatabaseQuerySelect());
$query->select($options['returnVerbose'] ? array('pages.id', 'pages.parent_id', 'pages.templates_id') : array('pages.id'));
$query->from("pages");
$query->groupby("pages.id");
$this->getQueryStartLimit($query);
foreach($selectors as $selector) {
/** @var Selector $selector */
if(is_null($lastSelector)) $lastSelector = $selector;
$selector = $this->preProcessSelector($selector, $selectors, $options);
if(!$selector || $selector->forceMatch === true) continue;
if($selector->forceMatch === false) {
$query->where("1>2"); // force non match
continue;
}
$fields = $selector->field;
$group = $selector->group; // i.e. @field
$fields = is_array($fields) ? $fields : array($fields);
if(count($fields) > 1) $fields = $this->arrangeFields($fields);
$fieldsStr = ':' . implode(':', $fields) . ':'; // for strpos
$field = reset($fields); // first field
$subfield = '';
if(strpos($field, '.')) list($field, $subfield) = explode('.', $field);
// TODO Make native fields and path/url multi-field and multi-value aware
if($field == 'sort' && $selector->operator === '=' && !$subfield) {
$sortSelectors[] = $selector;
continue;
} else if($field == 'limit' || $field == 'start') {
continue;
} else if($field == 'path' || $field == 'url') {
$this->getQueryJoinPath($query, $selector);
continue;
} else if($field == 'has_parent' || $field == 'hasParent') {
$this->getQueryHasParent($query, $selector);
continue;
} else if($field == 'num_children' || $field == 'numChildren' || ($field == 'children' && $subfield == 'count')) {
$this->getQueryNumChildren($query, $selector);
continue;
} else if($this->wire('fields')->isNative($field) || strpos($fieldsStr, ':parent.') !== false) {
$this->getQueryNativeField($query, $selector, $fields);
continue;
}
// where SQL specific to the foreach() of fields below, if needed.
// in this case only used by internally generated shortcuts like the blank value condition
$whereFields = '';
$whereFieldsType = 'AND';
foreach($fields as $n => $fieldName) {
// if a specific DB field from the table has been specified, then get it, otherwise assume 'data'
if(strpos($fieldName, ".")) list($fieldName, $subfield) = explode(".", $fieldName);
else $subfield = 'data';
if(!$field = $this->wire('fields')->get($fieldName)) {
// field does not exist, try to match an API variable
$value = $this->wire($fieldName);
if(!$value) throw new PageFinderSyntaxException("Field does not exist: $fieldName");
if(count($fields) > 1) throw new PageFinderSyntaxException("You may only match 1 API variable at a time");
if(is_object($value)) {
if($subfield == 'data') $subfield = 'id';
$selector->field = $subfield;
}
if(!$selector->matches($value)) {
$query->where("1>2"); // force non match