-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathPages.php
More file actions
2736 lines (2390 loc) · 94.9 KB
/
Pages.php
File metadata and controls
2736 lines (2390 loc) · 94.9 KB
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;
/**
* ProcessWire Pages ($pages API variable)
*
* Manages Page instances, providing find, load, save and delete capabilities,
* some of which are delegated to other classes but this provides the interface to them.
*
* This is the most used object in the ProcessWire API.
*
* ProcessWire 3.x (development), Copyright 2015 by Ryan Cramer
* https://processwire.com
*
* @link http://processwire.com/api/variables/pages/ Offical $pages Documentation
* @link http://processwire.com/api/selectors/ Official Selectors Documentation
*
* PROPERTIES
* ==========
* @property bool cloning Whether or not a clone() operation is currently active
* @property bool outputFormatting Current default output formatting mode.
*
* HOOKABLE METHODS
* ================
* @method PageArray find() find($selectorString, array $options = array()) Find and return all pages matching the given selector string. Returns a PageArray.
* @method bool save() save(Page $page) Save any changes made to the given $page. Same as : $page->save() Returns true on success
* @method bool saveField() saveField(Page $page, $field) Save just the named field from $page. Same as : $page->save('field')
* @method bool trash() trash(Page $page, $save = true) Move a page to the trash. If you have already set the parent to somewhere in the trash, then this method won't attempt to set it again.
* @method bool restore(Page $page, $save = true) Restore a trashed page to its original location.
* @method int emptyTrash() Empty the trash and return number of pages deleted.
* @method bool delete() delete(Page $page, $recursive = false) Permanently delete a page and it's fields. Unlike trash(), pages deleted here are not restorable. If you attempt to delete a page with children, and don't specifically set the $recursive param to True, then this method will throw an exception. If a recursive delete fails for any reason, an exception will be thrown.
* @method Page|NullPage clone(Page $page, Page $parent = null, $recursive = true, $options = array()) Clone an entire page, it's assets and children and return it.
* @method Page|NullPage add($template, $parent, $name = '', array $values = array())
* @method setupNew(Page $page) Setup new page that does not yet exist by populating some fields to it.
* @method string setupPageName(Page $page, array $options = array()) Determine and populate a name for the given page.
*
* METHODS PURELY FOR HOOKS
* ========================
* You can hook these methods, but you should not call them directly.
* See the phpdoc in the actual methods for more details about arguments and additional properties that can be accessed.
*
* @method saveReady(Page $page) Hook called just before a page is saved.
* @method saved(Page $page, array $changes = array(), $values = array()) Hook called after a page is successfully saved.
* @method added(Page $page) Hook called when a new page has been added.
* @method moved(Page $page) Hook called when a page has been moved from one parent to another.
* @method templateChanged(Page $page) Hook called when a page template has been changed.
* @method trashed(Page $page) Hook called when a page has been moved to the trash.
* @method restored(Page $page) Hook called when a page has been moved OUT of the trash.
* @method deleteReady(Page $page) Hook called just before a page is deleted.
* @method deleted(Page $page) Hook called after a page has been deleted.
* @method cloneReady(Page $page, Page $copy) Hook called just before a page is cloned.
* @method cloned(Page $page, Page $copy) Hook called after a page has been successfully cloned.
* @method renamed(Page $page) Hook called after a page has been successfully renamed.
* @method statusChangeReady(Page $page) Hook called when a page's status has changed and is about to be saved.
* @method statusChanged(Page $page) Hook called after a page status has been changed and saved.
* @method publishReady(Page $page) Hook called just before an unpublished page is published.
* @method published(Page $page) Hook called after an unpublished page has just been published.
* @method unpublishReady(Page $page) Hook called just before a pubished page is unpublished.
* @method unpublished(Page $page) Hook called after a published page has just been unpublished.
* @method saveFieldReady(Page $page, Field $field) Hook called just before a saveField() method saves a page fied.
* @method savedField(Page $page, Field $field) Hook called after saveField() method successfully executes.
* @method found(PageArray $pages, array $details) Hook called at the end of a $pages->find().
* @method unknownColumnError($column) Called when a page-data loading query encounters an unknown column.
*
* TO-DO
* =====
* @todo Add a getCopy method that does a getById($id, array('cache' => false) ?
* @todo Some methods here (find, save, etc.) need their own dedicated classes.
* @todo Update saveField to accept array of field names as an option.
*
*/
class Pages extends Wire {
/**
* Max length for page name
*
*/
const nameMaxLength = 128;
/**
* Instance of PageFinder (when cached)
*
*/
protected $pageFinder = null;
/**
* Instance of Templates
*
*/
protected $templates;
/**
* Instance of PagesSortfields
*
*/
protected $sortfields;
/**
* Pages that have been cached, indexed by ID
*
*/
protected $pageIdCache = array();
/**
* Cached selector strings and the PageArray that was found.
*
*/
protected $pageSelectorCache = array();
/**
* Controls the outputFormatting state for pages that are loaded
*
*/
protected $outputFormatting = false;
/**
* Runtime debug log of Pages class activities, see getDebugLog()
*
*/
protected $debugLog = array();
/**
* Shortcut to $config API var
*
*/
protected $config = null;
/**
* Are we currently cloning a page?
*
* This is true only when the clone() method is currently in progress.
*
* @var bool
*
*/
protected $cloning = false;
/**
* Autojoin allowed?
*
* @var bool
*
*/
protected $autojoin = true;
/**
* Name for autogenerated page names when fields to generate name aren't populated
*
* @var string
*
*/
protected $untitledPageName = 'untitled';
/**
* Enable 2.x compatibility mode?
*
* @var bool
*
*/
protected $compat2x = false;
/**
* Create the Pages object
*
* @param ProcessWire $wire
*
*/
public function __construct(ProcessWire $wire) {
$this->setWire($wire);
$this->config = $this->wire('config');
$this->templates = $this->wire('templates');
$this->sortfields = $this->wire(new PagesSortfields());
$this->compat2x = $this->config->compat2x;
}
/**
* Initialize $pages API var by preloading some pages
*
*/
public function init() {
$this->getById($this->config->preloadPageIDs);
}
/**
* Given a Selector string, return the Page objects that match in a PageArray.
*
* Non-visible pages are excluded unless an include=hidden|unpublished|all mode is specified in the selector string,
* or in the $options array. If 'all' mode is specified, then non-accessible pages (via access control) can also be included.
*
* @param string|int|array $selectorString Specify selector string (standard usage), but can also accept page ID or array of page IDs.
* @param array|string $options Optional one or more options that can modify certain behaviors. May be assoc array or key=value string.
* - findOne: boolean - apply optimizations for finding a single page
* - findAll: boolean - find all pages with no exculsions (same as include=all option)
* - getTotal: boolean - whether to set returning PageArray's "total" property (default: true except when findOne=true)
* - loadPages: boolean - whether to populate the returned PageArray with found pages (default: true).
* The only reason why you'd want to change this to false would be if you only needed the count details from
* the PageArray: getTotal(), getStart(), getLimit, etc. This is intended as an optimization for Pages::count().
* Does not apply if $selectorString argument is an array.
* - caller: string - optional name of calling function, for debugging purposes, i.e. pages.count
* - include: string - Optional inclusion mode of 'hidden', 'unpublished' or 'all'. Default=none. Typically you would specify this
* directly in the selector string, so the option is mainly useful if your first argument is not a string.
* - loadOptions: array - Optional assoc array of options to pass to getById() load options.
* @return PageArray
*
*/
public function ___find($selectorString, $options = array()) {
if(is_string($options)) $options = Selectors::keyValueStringToArray($options);
$loadOptions = isset($options['loadOptions']) && is_array($options['loadOptions']) ? $options['loadOptions'] : array();
if(is_array($selectorString)) {
if(ctype_digit(implode('', array_keys($selectorString))) && ctype_digit(implode('', $selectorString))) {
// if given a regular array of page IDs, we delegate that to getById() method, but with access/visibility control
return $this->filterListable(
$this->getById($selectorString),
(isset($options['include']) ? $options['include'] : ''),
$loadOptions);
} else {
// some other type of array/values that we don't yet recognize
// @todo add support for array selectors, per Selectors::arrayToSelectorString()
return $this->newPageArray($loadOptions);
}
}
$loadPages = true;
$debug = $this->wire('config')->debug;
if(array_key_exists('loadPages', $options)) $loadPages = (bool) $options['loadPages'];
if(!strlen($selectorString)) return $this->newPageArray($loadOptions);
if($selectorString === '/' || $selectorString === 'path=/') $selectorString = 1;
if($selectorString[0] == '/') {
// if selector begins with a slash, then we'll assume it's referring to a path
$selectorString = "path=$selectorString";
} else if(strpos($selectorString, ",") === false && strpos($selectorString, "|") === false) {
// there is just one param. Lets see if we can find a shortcut.
if(ctype_digit("$selectorString") || strpos($selectorString, "id=") === 0) {
// if selector is just a number, or a string like "id=123" then we're going to do a shortcut
$s = str_replace("id=", '', $selectorString);
if(ctype_digit("$s")) {
$value = $this->getById(array((int) $s), $loadOptions);
if(empty($options['findOne'])) $value = $this->filterListable(
$value, (isset($options['include']) ? $options['include'] : ''), $loadOptions);
if($debug) $this->debugLog('find', $selectorString . " [optimized]", $value);
return $value;
}
}
}
if(isset($options['include']) && in_array($options['include'], array('hidden', 'unpublished', 'all'))) {
$selectorString .= ", include=$options[include]";
}
// see if this has been cached and return it if so
$pages = $this->getSelectorCache($selectorString, $options);
if(!is_null($pages)) {
if($debug) $this->debugLog('find', $selectorString, $pages . ' [from-cache]');
return $pages;
}
// check if this find has already been executed, and return the cached results if so
// if(null !== ($pages = $this->getSelectorCache($selectorString, $options))) return clone $pages;
// if a specific parent wasn't requested, then we assume they don't want results with status >= Page::statusUnsearchable
// if(strpos($selectorString, 'parent_id') === false) $selectorString .= ", status<" . Page::statusUnsearchable;
$caller = isset($options['caller']) ? $options['caller'] : 'pages.find';
$selectors = $this->wire(new Selectors());
$selectors->init($selectorString);
$pageFinder = $this->getPageFinder();
if($debug) Debug::timer("$caller($selectorString)", true);
$pagesInfo = $pageFinder->find($selectors, $options);
// note that we save this pagination state here and set it at the end of this method
// because it's possible that more find operations could be executed as the pages are loaded
$total = $pageFinder->getTotal();
$limit = $pageFinder->getLimit();
$start = $pageFinder->getStart();
if($loadPages) {
// parent_id is null unless a single parent was specified in the selectors
$parent_id = $pageFinder->getParentID();
$idsSorted = array();
$idsByTemplate = array();
// organize the pages by template ID
foreach($pagesInfo as $page) {
$tpl_id = $page['templates_id'];
if(!isset($idsByTemplate[$tpl_id])) $idsByTemplate[$tpl_id] = array();
$idsByTemplate[$tpl_id][] = $page['id'];
$idsSorted[] = $page['id'];
}
if(count($idsByTemplate) > 1) {
// perform a load for each template, which results in unsorted pages
$unsortedPages = $this->newPageArray($loadOptions);
foreach($idsByTemplate as $tpl_id => $ids) {
$opt = $loadOptions;
$opt['template'] = $this->templates->get($tpl_id);
$opt['parent_id'] = $parent_id;
$unsortedPages->import($this->getById($ids, $opt));
}
// put pages back in the order that the selectorEngine returned them in, while double checking that the selector matches
$pages = $this->newPageArray($loadOptions);
foreach($idsSorted as $id) {
foreach($unsortedPages as $page) {
if($page->id == $id) {
$pages->add($page);
break;
}
}
}
} else {
// there is only one template used, so no resorting is necessary
$pages = $this->newPageArray($loadOptions);
reset($idsByTemplate);
$opt = $loadOptions;
$opt['template'] = $this->templates->get(key($idsByTemplate));
$opt['parent_id'] = $parent_id;
$pages->import($this->getById($idsSorted, $opt));
}
} else {
$pages = $this->newPageArray($loadOptions);
}
$pages->setTotal($total);
$pages->setLimit($limit);
$pages->setStart($start);
$pages->setSelectors($selectors);
$pages->setTrackChanges(true);
if($loadPages) $this->selectorCache($selectorString, $options, $pages);
if($this->config->debug) $this->debugLog('find', $selectorString, $pages);
if($debug) {
$count = $pages->count();
$note = ($count == $total ? $count : $count . "/$total") . " page(s)";
if($count) {
$note .= ": " . $pages->first()->path;
if($count > 1) $note .= " ... " . $pages->last()->path;
}
Debug::saveTimer("$caller($selectorString)", $note);
foreach($pages as $item) {
if($item->_debug_loaded) continue;
$item->setQuietly('_debug_loader', "$caller($selectorString)");
}
}
if($this->hasHook('found()')) $this->found($pages, array(
'pageFinder' => $pageFinder,
'pagesInfo' => $pagesInfo,
'options' => $options
));
return $pages;
}
/**
* Like find() but returns only the first match as a Page object (not PageArray)
*
* This is functionally similar to the get() method except that its default behavior is to
* filter for access control and hidden/unpublished/etc. states, in the same way that the
* find() method does. You can add an "include=..." to your selector string to bypass.
* This method also accepts an $options arrray, whereas get() does not.
*
* @param string $selectorString
* @param array|string $options See $options for Pages::find
* @return Page|NullPage
*
*/
public function findOne($selectorString, $options = array()) {
if(empty($selectorString)) return $this->newNullPage();
if(is_string($options)) $options = Selectors::keyValueStringToArray($options);
$defaults = array(
'findOne' => true, // find only one page
'getTotal' => false, // don't count totals
'caller' => 'pages.findOne'
);
$options = array_merge($defaults, $options);
$page = $this->find($selectorString, $options)->first();
if(!$page || !$page->viewable(false)) $page = $this->newNullPage();
return $page;
}
/**
* Returns the first page matching the given selector with no exclusions
*
* @param string $selectorString
* @return Page|NullPage Always returns a Page object, but will return NullPage (with id=0) when no match found
*
*/
public function get($selectorString) {
if(empty($selectorString)) return $this->newNullPage();
$page = $this->getCache($selectorString);
if($page) return $page;
$options = array(
'findOne' => true, // find only one page
'findAll' => true, // no exclusions
'getTotal' => false, // don't count totals
'caller' => 'pages.get'
);
$page = $this->find($selectorString, $options)->first();
if(!$page) $page = $this->newNullPage();
return $page;
}
/**
* Given an array or CSV string of Page IDs, return a PageArray
*
* Optionally specify an $options array rather than a template for argument 2. When present, the 'template' and 'parent_id' arguments may be provided
* in the given $options array. These options may be specified:
*
* LOAD OPTIONS (argument 2 array):
* - cache: boolean, default=true. place loaded pages in memory cache?
* - getFromCache: boolean, default=true. Allow use of previously cached pages in memory (rather than re-loading it from DB)?
* - template: instance of Template (see $template argument)
* - parent_id: integer (see $parent_id argument)
* - getNumChildren: boolean, default=true. Specify false to disable retrieval and population of 'numChildren' Page property.
* - getOne: boolean, default=false. Specify true to return just one Page object, rather than a PageArray.
* - autojoin: boolean, default=true. Allow use of autojoin option?
* - joinFields: array, default=empty. Autojoin the field names specified in this array, regardless of field settings (requires autojoin=true).
* - joinSortfield: boolean, default=true. Whether the 'sortfield' property will be joined to the page.
* - findTemplates: boolean, default=true. Determine which templates will be used (when no template specified) for more specific autojoins.
* - pageClass: string, default=auto-detect. Class to instantiate Page objects with. Leave blank to determine from template.
* - pageArrayClass: string, default=PageArray. PageArray-derived class to store pages in (when 'getOne' is false).
*
* Use the $options array for potential speed optimizations:
* - Specify a 'template' with your call, when possible, so that this method doesn't have to determine it separately.
* - Specify false for 'getNumChildren' for potential speed optimization when you know for certain pages will not have children.
* - Specify false for 'autojoin' for potential speed optimization in certain scenarios (can also be a bottleneck, so be sure to test).
* - Specify false for 'joinSortfield' for potential speed optimization when you know the Page will not have children or won't need to know the order.
* - Specify false for 'findTemplates' so this method doesn't have to look them up. Potential speed optimization if you have few autojoin fields globally.
* - Note that if you specify false for 'findTemplates' the pageClass is assumed to be 'Page' unless you specify something different for the 'pageClass' option.
*
* @param array|WireArray|string $_ids Array of IDs or CSV string of IDs
* @param Template|array|null $template Specify a template to make the load faster, because it won't have to attempt to join all possible fields... just those used by the template.
* Optionally specify an $options array instead, see the method notes above.
* @param int|null $parent_id Specify a parent to make the load faster, as it reduces the possibility for full table scans.
* This argument is ignored when an options array is supplied for the $template.
* @return PageArray|Page Returns Page only if the 'getOne' option is specified, otherwise always returns a PageArray.
* @throws WireException
*
*/
public function getById($_ids, $template = null, $parent_id = null) {
static $instanceID = 0;
$options = array(
'cache' => true,
'getFromCache' => true,
'template' => null,
'parent_id' => null,
'getNumChildren' => true,
'getOne' => false,
'autojoin' => true,
'findTemplates' => true,
'joinSortfield' => true,
'joinFields' => array(),
'pageClass' => '', // blank = auto detect
'pageArrayClass' => 'PageArray',
);
if(is_array($template)) {
// $template property specifies an array of options
$options = array_merge($options, $template);
$template = $options['template'];
$parent_id = $options['parent_id'];
} else if(!is_null($template) && !$template instanceof Template) {
throw new WireException('getById argument 2 must be Template or $options array');
}
if(!is_null($parent_id) && !is_int($parent_id)) {
// convert Page object or string to integer id
$parent_id = (int) ((string) $parent_id);
}
if(!is_null($template) && !is_object($template)) {
// convert template string or id to Template object
$template = $this->wire('templates')->get($template);
}
if(is_string($_ids)) {
// convert string of IDs to array
if(strpos($_ids, '|') !== false) $_ids = explode('|', $_ids);
else $_ids = explode(",", $_ids);
} else if(is_int($_ids)) {
$_ids = array($_ids);
}
if(!WireArray::iterable($_ids) || !count($_ids)) {
// return blank if $_ids isn't iterable or is empty
return $options['getOne'] ? $this->newNullPage() : $this->newPageArray($options);
}
if(is_object($_ids)) $_ids = $_ids->getArray(); // ArrayObject or the like
$loaded = array(); // array of id => Page objects that have been loaded
$ids = array(); // sanitized version of $_ids
// sanitize ids and determine which pages we can pull from cache
foreach($_ids as $key => $id) {
$id = (int) $id;
if($id < 1) continue;
if($options['getFromCache'] && $page = $this->getCache($id)) {
// page is already available in the cache
$loaded[$id] = $page;
} else if(isset(Page::$loadingStack[$id])) {
// if the page is already in the process of being loaded, point to it rather than attempting to load again.
// the point of this is to avoid a possible infinite loop with autojoin fields referencing each other.
$p = Page::$loadingStack[$id];
if($p) {
$loaded[$id] = $p;
// cache the pre-loaded version so that other pages referencing it point to this instance rather than loading again
$this->cache($loaded[$id]);
}
} else {
$loaded[$id] = ''; // reserve the spot, in this order
$ids[(int) $key] = $id; // queue id to be loaded
}
}
$idCnt = count($ids); // idCnt contains quantity of remaining page ids to load
if(!$idCnt) {
// if there are no more pages left to load, we can return what we've got
if($options['getOne']) return count($loaded) ? reset($loaded) : $this->newNullPage();
$pages = $this->newPageArray($options);
$pages->import($loaded);
return $pages;
}
$database = $this->wire('database');
$idsByTemplate = array();
if(is_null($template) && $options['findTemplates']) {
// template was not defined with the function call, so we determine
// which templates are used by each of the pages we have to load
$sql = "SELECT id, templates_id FROM pages WHERE ";
if($idCnt == 1) {
$sql .= "id=" . (int) reset($ids);
} else {
$sql .= "id IN(" . implode(",", $ids) . ")";
}
$query = $database->prepare($sql);
$result = $this->executeQuery($query);
if($result) {
/** @noinspection PhpAssignmentInConditionInspection */
while($row = $query->fetch(\PDO::FETCH_NUM)) {
list($id, $templates_id) = $row;
$id = (int) $id;
$templates_id = (int) $templates_id;
if(!isset($idsByTemplate[$templates_id])) $idsByTemplate[$templates_id] = array();
$idsByTemplate[$templates_id][] = $id;
}
}
$query->closeCursor();
} else if(is_null($template)) {
// no template provided, and autojoin not needed (so we don't need to know template)
$idsByTemplate = array(0 => $ids);
} else {
// template was provided
$idsByTemplate = array($template->id => $ids);
}
foreach($idsByTemplate as $templates_id => $ids) {
if($templates_id && (!$template || $template->id != $templates_id)) {
$template = $this->wire('templates')->get($templates_id);
}
if($template) {
$fields = $template->fieldgroup;
} else {
$fields = $this->wire('fields');
}
/** @var DatabaseQuerySelect $query */
$query = $this->wire(new DatabaseQuerySelect());
$sortfield = $template ? $template->sortfield : '';
$joinSortfield = empty($sortfield) && $options['joinSortfield'];
$query->select(
// note that "false AS isLoaded" triggers the setIsLoaded() function in Page intentionally
"false AS isLoaded, pages.templates_id AS templates_id, pages.*, " .
($joinSortfield ? 'pages_sortfields.sortfield, ' : '') .
($options['getNumChildren'] ? '(SELECT COUNT(*) FROM pages AS children WHERE children.parent_id=pages.id) AS numChildren' : '')
);
if($joinSortfield) $query->leftjoin('pages_sortfields ON pages_sortfields.pages_id=pages.id');
$query->groupby('pages.id');
if($options['autojoin'] && $this->autojoin) foreach($fields as $field) {
if(!empty($options['joinFields']) && in_array($field->name, $options['joinFields'])) {
// joinFields option specified to force autojoin this field
} else {
if(!($field->flags & Field::flagAutojoin)) continue; // autojoin not enabled for field
if($fields instanceof Fields && !($field->flags & Field::flagGlobal)) continue; // non-fieldgroup, autojoin only if global flag is set
}
$table = $database->escapeTable($field->table);
if(!$field->type || !$field->type->getLoadQueryAutojoin($field, $query)) continue; // autojoin not allowed
$query->leftjoin("$table ON $table.pages_id=pages.id"); // QA
}
if(!is_null($parent_id)) $query->where("pages.parent_id=" . (int) $parent_id);
if($template) $query->where("pages.templates_id=" . ((int) $template->id)); // QA
$query->where("pages.id IN(" . implode(',', $ids) . ") "); // QA
$query->from("pages");
$stmt = $query->prepare();
$this->executeQuery($stmt);
$class = $options['pageClass'];
if(empty($class)) {
if($template) {
$class = ($template->pageClass && wireClassExists($template->pageClass)) ? $template->pageClass : 'Page';
} else {
$class = 'Page';
}
}
if($class != 'Page' && !wireClassExists($class)) {
$this->error("Class '$class' for Pages::getById() does not exist", Notice::log);
$class = 'Page';
}
if($this->compat2x && class_exists("\\$class")) $class = "\\$class";
try {
$_class = wireClassName($class, true);
// while($page = $stmt->fetchObject($_class, array($template))) {
/** @noinspection PhpAssignmentInConditionInspection */
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$page = $this->newPage(array(
'pageClass' => $_class,
'template' => $template ? $template : $row['templates_id'],
));
unset($row['templates_id']);
foreach($row as $key => $value) $page->set($key, $value);
$page->instanceID = ++$instanceID;
$page->setIsLoaded(true);
$page->setIsNew(false);
$page->setTrackChanges(true);
$page->setOutputFormatting($this->outputFormatting);
$loaded[$page->id] = $page;
if($options['cache']) $this->cache($page);
}
} catch(\Exception $e) {
$error = $e->getMessage() . " [pageClass=$class, template=$template]";
$user = $this->wire('user');
if($user && $user->isSuperuser()) $this->error($error);
$this->wire('log')->error($error);
$this->trackException($e, false);
}
$stmt->closeCursor();
$template = null;
}
if($options['getOne']) return count($loaded) ? reset($loaded) : $this->newNullPage();
$pages = $this->newPageArray($options);
$pages->import($loaded);
// debug mode only
if($this->wire('config')->debug) {
$_template = is_null($template) ? '' : ", $template";
$_parent_id = is_null($parent_id) ? '' : ", $parent_id";
$_ids = count($_ids) > 1 ? "[" . implode(',', $_ids) . "]" : implode('', $_ids);
foreach($pages as $item) {
$item->setQuietly('_debug_loader', "getByID($_ids$_template$_parent_id)");
}
}
return $pages;
}
/**
* Remove pages from already-loaded PageArray aren't visible or accessible
*
* @param PageArray $items
* @param string $includeMode Optional inclusion mode:
* - 'hidden': Allow pages with 'hidden' status'
* - 'unpublished': Allow pages with 'unpublished' or 'hidden' status
* - 'all': Allow all pages (not much point in calling this method)
* @param array $options loadOptions
* @return PageArray
*
*/
protected function filterListable(PageArray $items, $includeMode = '', array $options = array()) {
if($includeMode === 'all') return $items;
$itemsAllowed = $this->newPageArray($options);
foreach($items as $item) {
if($includeMode === 'unpublished') {
$allow = $item->status < Page::statusTrash;
} else if($includeMode === 'hidden') {
$allow = $item->status < Page::statusUnpublished;
} else {
$allow = $item->status < Page::statusHidden;
}
if($allow) $allow = $item->listable(); // confirm access
if($allow) $itemsAllowed->add($item);
}
$itemsAllowed->resetTrackChanges(true);
return $itemsAllowed;
}
/**
* Add a new page using the given template to the given parent
*
* If no name is specified one will be assigned based on the current timestamp.
*
* @param string|Template $template Template name or Template object
* @param string|int|Page $parent Parent path, ID or Page object
* @param string $name Optional name or title of page. If none provided, one will be automatically assigned based on microtime stamp.
* If you want to specify a different name and title then specify the $name argument, and $values['title'].
* @param array $values Field values to assign to page (optional). If $name is ommitted, this may also be 3rd param.
* @return Page Returned page has output formatting off.
* @throws WireException When some criteria prevents the page from being saved.
*
*/
public function ___add($template, $parent, $name = '', array $values = array()) {
// the $values may optionally be the 3rd argument
if(is_array($name)) {
$values = $name;
$name = isset($values['name']) ? $values['name'] : '';
}
if(!is_object($template)) {
$template = $this->wire('templates')->get($template);
if(!$template) throw new WireException("Unknown template");
}
$pageClass = wireClassName($template->pageClass ? $template->pageClass : 'Page', true);
$page = $this->newPage(array(
'template' => $template,
'pageClass' => $pageClass
));
$page->parent = $parent;
$exceptionMessage = "Unable to add new page using template '$template' and parent '{$page->parent->path}'.";
if(empty($values['title'])) {
// no title provided in $values, so we assume $name is $title
// but if no name is provided, then we default to: Untitled Page
if(!strlen($name)) $name = $this->_('Untitled Page');
// the setupNew method will convert $page->title to a unique $page->name
$page->title = $name;
} else {
// title was provided
$page->title = $values['title'];
// if name is provided we use it
// otherwise setupNew will take care of assign it from title
if(strlen($name)) $page->name = $name;
unset($values['title']);
}
// save page before setting $values just in case any fieldtypes
// require the page to have an ID already (like file-based)
if(!$this->save($page)) throw new WireException($exceptionMessage);
// set field values, if provided
if(!empty($values)) {
unset($values['id'], $values['parent'], $values['template']); // fields that may not be set from this array
foreach($values as $key => $value) $page->set($key, $value);
$this->save($page);
}
return $page;
}
/**
* Given an ID return a path to a page, without loading the actual page
*
* This is not meant to be public API: You should just use $pages->get($id)->path (or url) instead.
* This is just a small optimization function for specific situations (like the PW bootstrap).
* This function is not meant to be part of the public $pages API, as I think it only serves
* to confuse with $page->path(). However, if you ever have a situation where you need to get a page
* path and want to avoid loading the page for some reason, this function is your ticket.
*
* @param int $id ID of the page you want the URL to
* @return string URL to page or blank on error
*
*/
public function _path($id) {
if(is_object($id) && $id instanceof Page) return $id->path();
$id = (int) $id;
if(!$id) return '';
// if page is already loaded, then get the path from it
if(isset($this->pageIdCache[$id])) {
/** @var Page $page */
$page = $this->pageIdCache[$id];
return $page->path();
}
if($this->modules->isInstalled('PagePaths')) {
/** @var PagePaths $pagePaths */
$pagePaths = $this->modules->get('PagePaths');
$path = $pagePaths->getPath($id);
if(is_null($path)) $path = '';
return $path;
}
$path = '';
$parent_id = $id;
$database = $this->wire('database');
do {
$query = $database->prepare("SELECT parent_id, name FROM pages WHERE id=:parent_id"); // QA
$query->bindValue(":parent_id", (int) $parent_id, \PDO::PARAM_INT);
$this->executeQuery($query);
list($parent_id, $name) = $query->fetch(\PDO::FETCH_NUM);
$path = $name . '/' . $path;
} while($parent_id > 1);
return '/' . ltrim($path, '/');
}
/**
* Count and return how many pages will match the given selector string
*
* @param string $selectorString Specify selector string, or omit to retrieve a site-wide count.
* @param array|string $options See $options in Pages::find
* @return int
*
*/
public function count($selectorString = '', $options = array()) {
if(is_string($options)) $options = Selectors::keyValueStringToArray($options);
if(!strlen($selectorString)) {
if(empty($options)) {
// optimize away a simple site-wide total count
return (int) $this->wire('database')->query("SELECT COUNT(*) FROM pages")->fetch(\PDO::FETCH_COLUMN);
} else {
// no selector string, but options specified
$selectorString = "id>0";
}
}
$options['loadPages'] = false;
$options['getTotal'] = true;
$options['caller'] = 'pages.count';
$options['returnVerbose'] = false;
//if($this->wire('config')->debug) $options['getTotalType'] = 'count'; // test count method when in debug mode
return $this->find("$selectorString, limit=1", $options)->getTotal();
}
/**
* Is the given page in a state where it can be saved?
*
* @param Page $page
* @param string $reason Text containing the reason why it can't be saved (assuming it's not saveable)
* @param string|Field $fieldName Optional fieldname to limit check to.
* @param array $options Options array given to the original save method (optional)
* @return bool True if saveable, False if not
*
*/
public function isSaveable(Page $page, &$reason, $fieldName = '', array $options = array()) {
$saveable = false;
$outputFormattingReason = "Call \$page->setOutputFormatting(false) before getting/setting values that will be modified and saved. ";
$corrupted = array();
if($fieldName && is_object($fieldName)) {
/** @var Field $fieldName */
$fieldName = $fieldName->name;
/** @var string $fieldName */
}
if($page->hasStatus(Page::statusCorrupted)) {
$corruptedFields = $page->_statusCorruptedFields;
foreach($page->getChanges() as $change) {
if(isset($corruptedFields[$change])) $corrupted[] = $change;
}
// if focused on a specific field...
if($fieldName && !in_array($fieldName, $corrupted)) $corrupted = array();
}
if($page instanceof NullPage) $reason = "Pages of type NullPage are not saveable";
else if((!$page->parent || $page->parent instanceof NullPage) && $page->id !== 1) $reason = "It has no parent assigned";
else if(!$page->template) $reason = "It has no template assigned";
else if(!strlen(trim($page->name)) && $page->id != 1) $reason = "It has an empty 'name' field";
else if(count($corrupted)) $reason = $outputFormattingReason . " [Page::statusCorrupted] fields: " . implode(', ', $corrupted);
else if($page->id == 1 && !$page->template->useRoles) $reason = "Selected homepage template cannot be used because it does not define access.";
else if($page->id == 1 && !$page->template->hasRole('guest')) $reason = "Selected homepage template cannot be used because it does not have the required 'guest' role in it's access settings.";
else $saveable = true;
// check if they could corrupt a field by saving
if($saveable && $page->outputFormatting) {
// iternate through recorded changes to see if any custom fields involved
foreach($page->getChanges() as $change) {
if($fieldName && $change != $fieldName) continue;
if($page->template->fieldgroup->getField($change) !== null) {
$reason = $outputFormattingReason . " [$change]";
$saveable = false;
break;
}
}
// iterate through already-loaded data to see if any are objects that have changed
if($saveable) foreach($page->getArray() as $key => $value) {
if($fieldName && $key != $fieldName) continue;
if(!$page->template->fieldgroup->getField($key)) continue;
if(is_object($value) && $value instanceof Wire && $value->isChanged()) {
$reason = $outputFormattingReason . " [$key]";
$saveable = false;
break;
}
}
}
// FAMILY CHECKS
// check for a parent change and whether it is allowed
if($saveable && $page->parentPrevious && $page->parentPrevious->id != $page->parent->id && empty($options['ignoreFamily'])) {
// page was moved
if($page->template->noMove && ($page->hasStatus(Page::statusSystem) || $page->hasStatus(Page::statusSystemID) || !$page->isTrash())) {
// make sure the page's template allows moves. only move laways allowed is to the trash, unless page has system status
$saveable = false;
$reason = "Pages using template '{$page->template}' are not moveable (template::noMove)";
} else if($page->parent->template->noChildren) {
$saveable = false;
$reason = "Chosen parent '{$page->parent->path}' uses template that does not allow children.";
} else if($page->parent->id && $page->parent->id != $this->config->trashPageID && count($page->parent->template->childTemplates) && !in_array($page->template->id, $page->parent->template->childTemplates)) {
// make sure the new parent's template allows pages with this template
$saveable = false;
$reason = "Can't move '{$page->name}' because Template '{$page->parent->template}' used by '{$page->parent->path}' doesn't allow children with this template.";
} else if(count($page->template->parentTemplates) && $page->parent->id != $this->config->trashPageID && !in_array($page->parent->template->id, $page->template->parentTemplates)) {
$saveable = false;
$reason = "Can't move '{$page->name}' because Template '{$page->parent->template}' used by '{$page->parent->path}' is not allowed by template '{$page->template->name}'.";
} else if(count($page->parent->children("name={$page->name}, id!=$page->id, include=all"))) {
$saveable = false;
$reason = "Chosen parent '{$page->parent->path}' already has a page named '{$page->name}'";
}
}
return $saveable;
}
/**
* Auto-populate some fields for a new page that does not yet exist
*
* Currently it does this:
* - Sets up a unique page->name based on the format or title if one isn't provided already.
* - Assigns a 'sort' value'.
*
* @param Page $page
*
*/
public function ___setupNew(Page $page) {
$parent = $page->parent();
if(!$parent->id) {
// auto-assign a parent, if we can find one in family settings
$parentTemplates = $page->template->parentTemplates;
$parent = null;
if(!empty($parentTemplates)) {
$idStr = implode('|', $parentTemplates);
$parent = $this->get("include=hidden, template=$idStr");
if(!$parent->id) $parent = $this->get("include=all, template=$idStr");
}
if($parent->id) $page->parent = $parent;
}
if(!strlen($page->name)) $this->setupPageName($page);
if($page->sort < 0) {
// auto assign a sort
$page->sort = $page->parent->numChildren();
}
foreach($page->template->fieldgroup as $field) {
if($page->__isset($field->name)) continue; // value already set
if(!strlen($field->defaultValue)) continue; // no defaultValue property defined with Fieldtype config inputfields
try {
$blankValue = $field->type->getBlankValue($page, $field);
if(is_object($blankValue) || is_array($blankValue)) continue; // we don't currently handle complex types
$defaultValue = $field->type->getDefaultValue($page, $field);
if(is_object($defaultValue) || is_array($defaultValue)) continue; // we don't currently handle complex types
if("$blankValue" !== "$defaultValue") {
$page->set($field->name, $defaultValue);
}
} catch(\Exception $e) {