-
Notifications
You must be signed in to change notification settings - Fork 201
/
Pages.php
1520 lines (1293 loc) · 50.8 KB
/
Pages.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
/**
* ProcessWire Pages
*
* 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.
*
* @TODO Move everything into delegate classes, leaving this as just the interface to them.
*
* ProcessWire 2.x
* Copyright (C) 2013 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://processwire.com
*
*
* @link http://processwire.com/api/variables/pages/ Offical $pages Documentation
* @link http://processwire.com/api/selectors/ Official Selectors Documentation
*
* @method PageArray find() find($selectorString, array $options) 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 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() clone(Page $page, Page $parent = null, $recursive = true, $options = array()) Clone an entire page, it's assets and children and return it.
*
*/
class Pages extends Wire {
/**
* Instance of PageFinder for finding pages
*
*/
protected $pageFinder;
/**
* 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;
/**
* Create the Pages object
*
*/
public function __construct() {
$this->config = $this->wire('config');
$this->templates = $this->wire('templates');
$this->pageFinder = new PageFinder();
$this->sortfields = new PagesSortfields();
}
/**
* Given a Selector string, return the Page objects that match in a PageArray.
*
* @param string $selectorString
* @param array $options
- findOne: apply optimizations for finding a single page and include pages with 'hidden' status
* @return PageArray
*
*/
public function ___find($selectorString, $options = array()) {
// TODO selector strings with runtime fields, like url=/about/contact/, possibly as plugins to PageFinder
if(!strlen($selectorString)) return new PageArray();
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")) {
$page = $this->getById(array((int) $s));
$pageArray = new PageArray();
$value = $page ? $pageArray->add($page) : $pageArray;
if($this->config->debug) $this->debugLog('find', $selectorString . " [optimized]", $value);
return $value;
}
}
}
// see if this has been cached and return it if so
$pages = $this->getSelectorCache($selectorString, $options);
if(!is_null($pages)) {
if($this->config->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;
$selectors = new Selectors($selectorString);
$pages = $this->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 = $this->pageFinder->getTotal();
$limit = $this->pageFinder->getLimit();
$start = $this->pageFinder->getStart();
// parent_id is null unless a single parent was specified in the selectors
$parent_id = $this->pageFinder->getParentID();
$idsSorted = array();
$idsByTemplate = array();
// organize the pages by template ID
foreach($pages 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 = new PageArray();
foreach($idsByTemplate as $tpl_id => $ids) {
$unsortedPages->import($this->getById($ids, $this->templates->get($tpl_id), $parent_id));
}
// put pages back in the order that the selectorEngine returned them in, while double checking that the selector matches
$pages = new PageArray();
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 = new PageArray();
reset($idsByTemplate);
$pages->import($this->getById($idsSorted, $this->templates->get(key($idsByTemplate)), $parent_id));
}
$pages->setTotal($total);
$pages->setLimit($limit);
$pages->setStart($start);
$pages->setSelectors($selectors);
$pages->setTrackChanges(true);
$this->selectorCache($selectorString, $options, $pages);
if($this->config->debug) $this->debugLog('find', $selectorString, $pages);
return $pages;
//return $pages->filter($selectors);
}
/**
* Like find() but returns only the first match as a Page object (not PageArray)
*
* @param string $selectorString
* @param array $options See $options for Pages::find
* @return Page|null
*
*/
public function findOne($selectorString, $options = array()) {
if(empty($selectorString)) return new NullPage();
if($page = $this->getCache($selectorString)) return $page;
$options['findOne'] = true;
$page = $this->find($selectorString, $options)->first();
if(!$page) $page = new NullPage();
return $page;
}
/**
* Returns only the first match as a Page object (not PageArray).
*
* This is an alias of the findOne() method for syntactic convenience and consistency.
* Using get() is preferred.
*
* @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) {
return $this->findOne($selectorString);
}
/**
* Given an array or CSV string of Page IDs, return a PageArray
*
* @param array|WireArray|string $ids Array of IDs or CSV string of IDs
* @param Template|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.
* @param int|null $parent_id Specify a parent to make the load faster, as it reduces the possibility for full table scans.
* @return PageArray
* @throws WireException
*
*/
public function getById($ids, Template $template = null, $parent_id = null) {
static $instanceID = 0;
$database = $this->wire('database');
$pages = new PageArray();
if(is_string($ids)) $ids = explode(",", $ids);
if(!WireArray::iterable($ids) || !count($ids)) return $pages;
if(is_object($ids)) $ids = $ids->getArray();
$loaded = array();
foreach($ids as $key => $id) {
$id = (int) $id;
$ids[$key] = $id;
if($page = $this->getCache($id)) {
$loaded[$id] = $page;
unset($ids[$key]);
} 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.
$loaded[$id] = Page::$loadingStack[$id];
// cache the pre-loaded version so that other pages referencing it point to this instance rather than loading again
$this->cache($loaded[$id]);
unset($ids[$key]);
} else {
$loaded[$id] = ''; // reserve the spot, in this order
}
}
$idCnt = count($ids);
if(!$idCnt) return $pages->import($loaded);
$idsByTemplate = array();
if(is_null($template)) {
$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 = $query->execute();
if($result) while($row = $query->fetch(PDO::FETCH_NUM)) {
list($id, $templates_id) = $row;
if(!isset($idsByTemplate[$templates_id])) $idsByTemplate[$templates_id] = array();
$idsByTemplate[$templates_id][] = $id;
}
$query->closeCursor();
} else {
$idsByTemplate = array($template->id => $ids);
}
foreach($idsByTemplate as $templates_id => $ids) {
if(!$template || $template->id != $templates_id) $template = $this->wire('templates')->get($templates_id);
$fields = $template->fieldgroup;
$query = new DatabaseQuerySelect();
$joinSortfield = empty($template->sortfield);
$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, ' : '') .
"(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');
foreach($fields as $field) {
if(!($field->flags & Field::flagAutojoin)) continue;
$table = $database->escapeTable($field->table);
if(!$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);
$query->where("pages.templates_id=" . ((int) $template->id)); // QA
$query->where("pages.id IN(" . implode(',', $ids) . ") "); // QA
$query->from("pages");
$stmt = $query->execute();
if($stmt->errorCode() > 0) {
$errorInfo = $result->errorInfo();
throw new WireException($errorInfo[2]);
}
$class = ($template->pageClass && class_exists($template->pageClass)) ? $template->pageClass : 'Page';
while($page = $stmt->fetchObject($class, array($template))) {
$page->instanceID = ++$instanceID;
$page->setIsLoaded(true);
$page->setIsNew(false);
$page->setTrackChanges(true);
$page->setOutputFormatting($this->outputFormatting);
$loaded[$page->id] = $page;
$this->cache($page);
}
$stmt->closeCursor();
$template = null;
}
return $pages->import($loaded);
}
/**
* 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|id|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'] : '';
}
$pageClass = $template->pageClass ? $template->pageClass : 'Page';
$page = new $pageClass();
$page->template = $template;
$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])) return $this->pageIdCache[$id]->path();
if($this->modules->isInstalled('PagePaths')) {
$path = $this->modules->get('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);
$query->execute();
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
* @param array $options See $options in Pages::find
* @return int
* @todo optimize this so that it only counts, and doesn't have to load any pages in the process.
*
*/
public function count($selectorString, $options = array()) {
// PW doesn't count when limit=1, which is why we limit=2
return $this->find("$selectorString, limit=2", $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)
* @return bool True if saveable, False if not
*
*/
public function isSaveable(Page $page, &$reason) {
$saveable = false;
$outputFormattingReason = "Call \$page->setOutputFormatting(false) before getting/setting values that will be modified and saved. ";
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($page->is(Page::statusCorrupted)) $reason = $outputFormattingReason . " [Page::statusCorrupted]";
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($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(!$page->template->fieldgroup->getField($key)) continue;
if(is_object($value) && $value instanceof Wire && $value->isChanged()) {
$reason = $outputFormattingReason . " [$key]";
$saveable = false;
break;
}
}
}
// check for a parent change
if($saveable && $page->parentPrevious && $page->parentPrevious->id != $page->parent->id) {
// page was moved
if($page->template->noMove && ($page->is(Page::statusSystem) || $page->is(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, status<" . Page::statusMax))) {
$saveable = false;
$reason = "Chosen parent '{$page->parent->path}' already has a page named '{$page->name}'";
}
}
return $saveable;
}
/**
* Validate that a new page is in a saveable condition and correct it if not.
*
* Currently just sets up up a unique page->name based on the title if one isn't provided already.
*
* @param Page $page
*
*/
protected function ___setupNew(Page $page) {
if(!$page->name && $page->title) {
$n = 0;
$pageName = $this->wire('sanitizer')->pageName($page->title, Sanitizer::translate);
do {
$name = $pageName . ($n ? "-$n" : '');
$child = $page->parent->child("name=$name, include=all"); // see if another page already has the same name
$n++;
} while($child->id);
$page->name = $name;
}
if($page->sort < 0) {
$page->sort = $page->parent->numChildren;
}
}
/**
* Save a page object and it's fields to database.
*
* If the page is new, it will be inserted. If existing, it will be updated.
*
* This is the same as calling $page->save()
*
* If you want to just save a particular field in a Page, use $page->save($fieldName) instead.
*
* @param Page $page
* @param array $options Optional array with the following optional elements:
* 'uncacheAll' => boolean - Whether the memory cache should be cleared (default=true)
* 'resetTrackChanges' => boolean - Whether the page's change tracking should be reset (default=true)
* 'quiet' => boolean - When true, modified date and modified_users_id won't be updated (default=false)
* @return bool True on success, false on failure
* @throws WireException
*
*/
public function ___save(Page $page, $options = array()) {
$defaultOptions = array(
'uncacheAll' => true,
'resetTrackChanges' => true,
);
$user = $this->wire('user');
$options = array_merge($defaultOptions, $options);
$language = $user->language && $user->language->id ? $user->language : null;
// switch to default language so that saved fields and hooks don't need to be aware of language
if($language) $user->language = $this->wire('languages')->getDefault();
$reason = '';
$isNew = $page->isNew();
if($isNew) $this->setupNew($page);
if(!$this->isSaveable($page, $reason)) {
if($language) $user->language = $language;
throw new WireException("Can't save page {$page->id}: {$page->path}: $reason");
}
if($page->is(Page::statusUnpublished) && $page->template->noUnpublish) $page->removeStatus(Page::statusUnpublished);
if($page->parentPrevious) {
if($page->isTrash() && !$page->parentPrevious->isTrash()) $this->trash($page, false);
else if($page->parentPrevious->isTrash() && !$page->parent->isTrash()) $this->restore($page, false);
}
if(!$this->savePageQuery($page, $options)) return false;
$result = $this->savePageFinish($page, $isNew, $options);
if($language) $user->language = $language;
return $result;
}
/**
* Execute query to save to pages table
*
* triggers hooks: saveReady, statusChangeReady (when status changed)
*
* @param Page $page
* @param array $options
* @return PDOStatement
*
*/
protected function savePageQuery(Page $page, array $options) {
$isNew = $page->isNew();
$database = $this->wire('database');
$user = $this->wire('user');
$userID = $user ? $user->id : $this->config->superUserPageID;
if(!$page->created_users_id) $page->created_users_id = $userID;
if($page->isChanged('status')) $this->statusChangeReady($page);
$extraData = $this->saveReady($page);
$sql = '';
$data = array(
'parent_id' => (int) $page->parent_id,
'templates_id' => (int) $page->template->id,
'name' => $page->name,
'status' => (int) $page->status,
'sort' => ($page->sort > -1 ? (int) $page->sort : 0)
);
if(is_array($extraData)) foreach($extraData as $column => $value) {
$column = $database->escapeCol($column);
$data[$column] = (strtoupper($value) === 'NULL' ? NULL : $value);
}
if($isNew) {
if($page->id) $data['id'] = (int) $page->id;
$data['created_users_id'] = (int) $userID;
}
if($page->template->allowChangeUser) {
$data['created_users_id'] = (int) $page->created_users_id;
}
if(empty($options['quiet'])) {
$sql = 'modified=NOW()';
$data['modified_users_id'] = (int) $userID;
} else {
// quiet option, use existing values already populated to page, when present
$data['modified_users_id'] = (int) ($page->modified_users_id ? $page->modified_users_id : $userID);
$data['created_users_id'] = (int) ($page->created_users_id ? $page->created_users_id : $userID);
if($page->modified > 0) $data['modified'] = date('Y-m-d H:i:s', $page->modified);
else if($isNew) $sql = 'modified=NOW()';
if(!$isNew && $page->created > 0) $data['created'] = date('Y-m-d H:i:s', $page->created);
}
foreach($data as $column => $value) {
$sql .= ", $column=" . (is_null($value) ? "NULL" : ":$column");
}
$sql = trim($sql, ", ");
if($isNew) {
$query = $database->prepare("INSERT INTO pages SET $sql, created=NOW()");
} else {
$query = $database->prepare("UPDATE pages SET $sql WHERE id=:id");
$query->bindValue(":id", (int) $page->id, PDO::PARAM_INT);
}
foreach($data as $column => $value) {
if(is_null($value)) continue; // already bound above
$query->bindValue(":$column", $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
if(!$query->execute()) return false;
if($isNew || !$page->id) $page->id = $database->lastInsertId();
return true;
}
/**
* Save individual Page fields and supporting actions
*
* triggers hooks: saved, added, moved, renamed, templateChanged
*
* @param Page $page
* @param bool $isNew
* @param array $options
* @return bool
*
*/
protected function savePageFinish(Page $page, $isNew, array $options) {
$changes = $page->getChanges();
// update children counts for current/previous parent
if($isNew) {
$page->parent->numChildren++;
} else {
if($page->parentPrevious && $page->parentPrevious->id != $page->parent->id) {
$page->parentPrevious->numChildren--;
$page->parent->numChildren++;
}
}
// if page hasn't changed, don't continue further
if(!$page->isChanged() && !$isNew) {
$this->debugLog('save', '[not-changed]', true);
$this->saved($page, array());
return true;
}
// if page has a files path, trigger filesManager's save
if(PagefilesManager::hasPath($page)) $page->filesManager->save();
// disable outputFormatting and save state
$of = $page->of();
$page->of(false);
// save each individual Fieldtype data in the fields_* tables
foreach($page->fieldgroup as $field) {
if($field->type) $field->type->savePageField($page, $field);
}
// return outputFormatting state
$page->of($of);
if(empty($page->template->sortfield)) $this->sortfields->save($page);
if($options['resetTrackChanges']) $page->resetTrackChanges();
// determine whether we'll trigger the added() hook
if($isNew) {
$page->setIsNew(false);
$triggerAddedPage = $page;
} else $triggerAddedPage = null;
// check for template changes
if($page->templatePrevious && $page->templatePrevious->id != $page->template->id) {
// the template was changed, so we may have data in the DB that is no longer applicable
// find unused data and delete it
foreach($page->templatePrevious->fieldgroup as $field) {
if($page->template->fieldgroup->has($field)) continue;
$field->type->deletePageField($page, $field);
$this->message("Deleted field '$field' on page {$page->url}", Notice::debug);
}
}
if($options['uncacheAll']) $this->uncacheAll();
// determine whether the pages_access table needs to be updated so that pages->find()
// operations can be access controlled.
if($isNew || $page->parentPrevious || $page->templatePrevious) new PagesAccess($page);
// lastly determine whether the pages_parents table needs to be updated for the find() cache
// and call upon $this->saveParents where appropriate.
if($page->parentPrevious && $page->numChildren > 0) {
// page is moved and it has children
$this->saveParents($page->id, $page->numChildren);
if($page->parent->numChildren == 1) $this->saveParents($page->parent_id, $page->parent->numChildren);
} else if(($page->parentPrevious && $page->parent->numChildren == 1) ||
($isNew && $page->parent->numChildren == 1) ||
($page->forceSaveParents)) {
// page is moved and is the first child of it's new parent
// OR page is NEW and is the first child of it's parent
// OR $page->forceSaveParents is set (debug/debug, can be removed later)
$this->saveParents($page->parent_id, $page->parent->numChildren);
}
if($page->parentPrevious && $page->parentPrevious->numChildren == 0) {
// $page was moved and it's previous parent is now left with no children, this ensures the old entries get deleted
$this->saveParents($page->parentPrevious->id, 0);
}
// trigger hooks
$this->saved($page, $changes);
if($triggerAddedPage) $this->added($triggerAddedPage);
if($page->namePrevious && $page->namePrevious != $page->name) $this->renamed($page);
if($page->parentPrevious) $this->moved($page);
if($page->templatePrevious) $this->templateChanged($page);
if(in_array('status', $changes)) $this->statusChanged($page);
$this->debugLog('save', $page, true);
return true;
}
/**
* Save just a field from the given page as used by Page::save($field)
*
* This function is public, but the preferred manner to call it is with $page->save($field)
*
* @param Page $page
* @param string|Field $field Field object or name (string)
* @param array $options Specify option 'quiet' => true, to bypass updating of modified_users_id and modified time.
* @return bool True on success
* @throws WireException
*
*/
public function ___saveField(Page $page, $field, array $options = array()) {
$reason = '';
if($page->isNew()) throw new WireException("Can't save field from a new page - please save the entire page first");
if(!$this->isSaveable($page, $reason)) throw new WireException("Can't save field from page {$page->id}: {$page->path}: $reason");
if($field && (is_string($field) || is_int($field))) $field = $this->fuel('fields')->get($field);
if(!$field instanceof Field) throw new WireException("Unknown field supplied to saveField for page {$page->id}");
if(!$page->fields->has($field)) throw new WireException("Page {$page->id} does not have field {$field->name}");
$value = $page->get($field->name);
if($value instanceof Pagefiles || $value instanceof Pagefile) $page->filesManager()->save();
$page->trackChange($field->name);
if($field->type->savePageField($page, $field)) {
$page->untrackChange($field->name);
if(empty($options['quiet'])) {
$user = $this->wire('user');
$userID = (int) ($user ? $user->id : $this->config->superUserPageID);
$database = $this->wire('database');
$query = $database->prepare("UPDATE pages SET modified_users_id=:userID, modified=NOW() WHERE id=:pageID");
$query->bindValue(':userID', $userID, PDO::PARAM_INT);
$query->bindValue(':pageID', $page->id, PDO::PARAM_INT);
$query->execute();
}
$return = true;
} else {
$return = false;
}
$this->debugLog('saveField', "$page:$field", $return);
return $return;
}
/**
* Save references to the Page's parents in pages_parents table, as well as any other pages affected by a parent change
*
* Any pages_id passed into here are assumed to have children
*
* @param int $pages_id ID of page to save parents from
* @param int $numChildren Number of children this Page has
* @param int $level Recursion level, for debugging.
* @return bool
*
*/
protected function saveParents($pages_id, $numChildren, $level = 0) {
$pages_id = (int) $pages_id;
if(!$pages_id) return false;
$database = $this->wire('database');
$query = $database->prepare("DELETE FROM pages_parents WHERE pages_id=:pages_id");
$query->bindValue(':pages_id', $pages_id, PDO::PARAM_INT);
$query->execute();
if(!$numChildren) return true;
$insertSql = '';
$id = $pages_id;
$cnt = 0;
$query = $database->prepare("SELECT parent_id FROM pages WHERE id=:id");
do {
if($id < 2) break; // home has no parent, so no need to do that query
$query->bindValue(":id", $id, PDO::PARAM_INT);
$query->execute();
list($id) = $query->fetch(PDO::FETCH_NUM);
$id = (int) $id;
if(!$id) break;
$insertSql .= "($pages_id, $id),";
$cnt++;
} while(1);
if($insertSql) {
$sql = "INSERT INTO pages_parents (pages_id, parents_id) VALUES" . rtrim($insertSql, ",");
$database->exec($sql);
}
// find all children of $pages_id that themselves have children
$sql = "SELECT pages.id, COUNT(children.id) AS numChildren " .
"FROM pages " .
"JOIN pages AS children ON children.parent_id=pages.id " .
"WHERE pages.parent_id=:pages_id " .
"GROUP BY pages.id ";
$query = $database->prepare($sql);
$query->bindValue(':pages_id', $pages_id, PDO::PARAM_INT);
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$this->saveParents($row['id'], $row['numChildren'], $level+1);
}
$query->closeCursor();
return true;
}
/**
* Sets a new Page status and saves the page, optionally recursive with the children, grandchildren, and so on.
*
* While this can be performed with other methods, this is here just to make it fast for internal/non-api use.
* See the trash and restore methods for an example.
*
* @param int $pageID
* @param int $status Status per flags in Page::status* constants
* @param bool $recursive Should the status descend into the page's children, and grandchildren, etc?
* @param bool $remove Should the status be removed rather than added?
*
*/
protected function savePageStatus($pageID, $status, $recursive = false, $remove = false) {
$pageID = (int) $pageID;
$status = (int) $status;
$sql = $remove ? "status & ~$status" : $sql = "status|$status";
$database = $this->wire('database');
$query = $database->prepare("UPDATE pages SET status=$sql WHERE id=:page_id");
$query->bindValue(":page_id", $pageID, PDO::PARAM_INT);
$query->execute();
if($recursive) {
$query = $database->prepare("SELECT id FROM pages WHERE parent_id=:parent_id"); // QA
$query->bindValue(":parent_id", $pageID, PDO::PARAM_INT);
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$this->savePageStatus($row['id'], $status, true, $remove);
}
$query->closeCursor();
}
}
/**
* Is the given page deleteable?
*
* Note: this does not account for user permission checking. It only checks if the page is in a state to be saveable via the API.
*
* @param Page $page
* @return bool True if deleteable, False if not
*
*/
public function isDeleteable(Page $page) {
$deleteable = true;
if(!$page->id || $page->status & Page::statusSystemID || $page->status & Page::statusSystem) $deleteable = false;
else if($page instanceof NullPage) $deleteable = false;
return $deleteable;
}
/**
* 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.
*
* @param Page $page
* @param bool $save Set to false if you will perform the save() call, as is the case when called from the Pages::save() method.
* @return bool
* @throws WireException
*
*/
public function ___trash(Page $page, $save = true) {
if(!$this->isDeleteable($page) || $page->template->noTrash) throw new WireException("This page may not be placed in the trash");
if(!$trash = $this->get($this->config->trashPageID)) {
throw new WireException("Unable to load trash page defined by config::trashPageID");
}
$page->addStatus(Page::statusTrash);
if(!$page->parent->isTrash()) $page->parent = $trash;
if(!preg_match('/^' . $page->id . '_.+/', $page->name)) {
// make the name unique when in trash, to avoid namespace collision
$page->name = $page->id . "_" . $page->name;
}
if($save) $this->save($page);
$this->savePageStatus($page->id, Page::statusTrash, true, false);
$this->trashed($page);
$this->debugLog('trash', $page, true);
return true;
}
/**
* Restore a page from the trash back to a non-trash state
*
* Note that this method assumes already have set a new parent, but have not yet saved
*
* @param Page $page