/
ProcessPageLister.module
2483 lines (2140 loc) · 76.2 KB
/
ProcessPageLister.module
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;
/**
* Process Lister
* __ _ __
* / / (_)____/ /____ _____
* / / / / ___/ __/ _ \/ ___/
* / /___/ (__ ) /_/ __/ /
* /_____/_/____/\__/\___/_/
*
* Provides an alternative listing view for pages using specific templates.
*
* ProcessWire 3.x, Copyright 2022 by Ryan Cramer
* https://processwire.com
*
* For support of actions, new edit modules, and custom configurable Listers,
* check out ListerPro at http://processwire.com/ListerPro/
*
*
* GET vars recognized by Lister:
*
* session_bookmark: name of session bookmark (session_bookmark=...)
* pageNum: page number, if specified as GET var rather than URL segment (pageNum=1)
* open: CSV string of page IDs that should be open/selected (open=1,2,3)
* reset: Initiates reset of filters (reset=1)
* minimal: Minimal mode shows only results and nothing else (minimal=1, usually combined with modal=1)
*
*
* PROPERTIES
*
* @property string $initSelector The selector string that may not be changed.
* @property string $defaultSelector The default selector string that appears but MAY be removed or changed [template=, title%=]
* @property array $statusLabels Array of status labels of status_name => label
* @property null|Page $parent Parent page for all listed children (optional)
* @property null|Template $template Template page for all listed children (optional)
* @property array $columns Array of columns (field names) to display in the lister
* @property array $delimiters Delimiters for multi-value column values, indexed by field name
* @property string $defaultSort Default field to sort by [-modified]
* @property int $defaultLimit Max items to show per pagination [25]
* @property int $imageWidth Width for thumbnails, 0=proportional to height [0]
* @property int $imageHeight Height for thumbnails, 0=proportional to width [100]
* @property int|bool $imageFirst Show only first image? [false]
* @property int $imageStyle 1=Detailed, 0=Image only (default=0)
* @property int $viewMode View mode, see windowMode constants [self::windowModeNone]
* @property int $editMode Edit mode, see windowMode constants [self::windowModeNone]
* @property string $editURL Edit page base URL [$config->urls->admin . 'page/edit/']
* @property string $addURL Add page base URL [$config->urls->admin . 'page/add/']
* @property array $disallowColumns columns that may not be displayed [array(pass,config)]
* @property bool $useColumnLabels whether to use labels for fields (versus names) in column selection and column labels [true]
* @property bool $allowSystem whether or not system templates/fields are allowed for selection. for system fields, it only refers to system custom fields excluding title. [false]
* @property bool $allowIncludeAll allow include=all or check_access=0 mode when user is non-superuser? [false]
* @property bool $allowBookmarks Whether or not to allow bookmarks
* @property bool $preview whether or not to show the selector string preview in InputfieldSelector [self::debug]
* @property bool $cacheTotal cache the total, per selector, for increased performance? [true]
* @property array $toggles One or more of: collapseFilters, collapseColumns, noNewFilters, disableColumns, noButtons [empty]
* @property array $systemLabels Array of system page labels of field_name => label
* @property array $limitFields Limit selectable filters/columns to only those present in this array [empty]
* @property string $nativeDateFormat wireDate() format for created and modified dates
* @property bool $showIncludeWarnings Whether or not to show warnings about what pages were excluded to to max "include=" mode [true]
* @property string $blankLabel Label when a field is blank (default=Blank)
* @property int $editOption Edit option setting, used only by ListerPro
* @property bool $responsiveTable Whether or not Lister table should be responsive rather than horiz scroll
* @property bool $configMode Configuration mode where some limits are removed (default=false)
*
* @method string buildListerTableColActions(Page $p, $value)
* @method string renderResults($selector = null)
* @method string getSelector($limit = null)
* @method PageArray findResults($selector)
* @method string executeReset()
* @method string executeEditBookmark()
* @method string executeViewport() ListerPro
* @method string executeConfig() ListerPro
* @method string executeActions() ListerPro
* @method string executeSave() ListerPro
* @method string renderedExtras($markup) #pw-hooker
*
*
* @todo make system fields hookable for output like markupValue is for custom fields
* @todo show bookmark title somewhere on page so users know what they are looking at (+ browser title?)
*
*/
class ProcessPageLister extends Process implements ConfigurableModule {
/**
* Makes additional info appear for Lister development
*
*/
const debug = false;
/**
* Name of session variable used for Lister bookmarks
*
*/
const sessionBookmarksName = '_lister_bookmarks';
/**
* Constants for the $window config option
*
*/
const windowModeNone = 0; // regular link
const windowModeModal = 2; // opens modal
const windowModeBlank = 4; // opens target=_blank
const windowModeHide = 8; // doesn't show
const windowModeDirect = 16; // click takes you directly there
/**
* Instance of InputfieldSelector
*
*/
protected $inputfieldSelector = null;
/**
* Cached totals per selector, so we don't have to re-calculate on each pagination
*
*/
protected $knownTotal = array(
'selector' => '',
'total' => null, // null=unset, integer=set
'time' => 0,
);
/**
* Default columns to display when none configured
*
*/
protected $defaultColumns = array('title', 'template', 'parent', 'modified', 'modified_users_id');
/**
* Default selector to use when none defined
*
*/
protected $defaultInitSelector = '';
/**
* Final selector string sent to Pages::find, for debugging purposes
*
*/
protected $finalSelector = '';
/**
* Final selector string after being fully parsed by PageFinder (used only in debug mode)
*
* @var string
*
*/
protected $finalSelectorParsed = '';
/**
* IDs of pages that should appear open automatically
*
* May be set by GET variable 'open' or by openPageIDs setting.
*
*/
protected $openPageIDs = array();
/**
* Additional notes about the results to display underneath them
*
* @var array
*
*/
protected $resultNotes = array();
/**
* Render results during this request?
*
* @var bool
*
*/
protected $renderResults = false;
/**
* Initalize module config variables
*
*/
public function __construct() {
parent::__construct();
if(!$this->wire()->page) return;
$this->defaultColumns = array('title', 'template', 'parent', 'modified', 'modified_users_id');
// default init selector
$initSelector = "has_parent!=2"; // exclude admin
/*
if($this->wire('user')->isSuperuser()) {
$initSelector .= "include=all";
} else if($this->wire('user')->hasPermission('page-edit')) {
$initSelector .= "include=unpublished";
} else {
$initSelector .= "include=hidden";
}
*/
// exclude admin pages from defaultInitSelector when user is not superuser
// if(!$this->wire('user')->isSuperuser()) $initSelector .= ", has_parent!=" . $this->wire('config')->adminRootPageID;
// the initial selector string that all further selections are filtered by
// this selector string is not visible to user are MAY NOT be removed or changed,
// except for 'sort' properties.
$this->set('initSelector', $initSelector);
// the default selector string that appears but MAY be removed or changed
$this->set('defaultSelector', "template=, title%=");
// Array of status labels of status_name => label
$this->set('statusLabels', array());
// Parent page for all listed children (optional)
$this->set('parent', null);
// Template page for all listed children (optional)
$this->set('template', null);
// Array of columns (field names) to display in the lister
$this->set('columns', $this->defaultColumns);
// Delimiters for multi-value column values, indexed by field name
$this->set('delimiters', array());
// Default field to sort by
$this->set('defaultSort', '-modified');
// Max items to show per pagination
$this->set('defaultLimit', 25);
// image width/height for thumbnail images
$this->set('imageWidth', 0);
$this->set('imageHeight', 100);
$this->set('imageFirst', 0);
$this->set('imageStyle', 0); // 0=image only, 1=detailed
// view and edit window modes
$this->set('viewMode', self::windowModeNone);
$this->set('editMode', self::windowModeNone);
$this->set('editURL', $this->wire('config')->urls->admin . 'page/edit/');
$this->set('addURL', $this->wire('config')->urls->admin . 'page/add/');
// columns that may not be displayed
$this->set('disallowColumns', array('pass', 'config'));
// limit selectable columns and filters to only those present in this array
// if empty, then it is not applicable
$this->set('limitFields', array());
// whether to use labels for fields (versus names) in column selection and column labels
$this->set('useColumnLabels', true);
// whether or not system templates/fields are allowed for selection
// for system fields, it only refers to system custom fields excluding title
$this->set('allowSystem', false);
// allow include=all or check_access=0 mode when user is non-superuser?
$this->set('allowIncludeAll', false);
// allow bookmarks?
$this->set('allowBookmarks', true);
// whether or not to show the selector string preview in InputfieldSelector
$this->set('preview', self::debug);
// cache the total, per selector, for increased performance?
$this->set('cacheTotal', true);
// toggles: collapseFilters, collapseColumns, noNewFilters, disableColumns, noButtons
$this->set('toggles', array());
// date format for native properties: created and modified
$this->set('nativeDateFormat', $this->_('rel')); // Native date format: use wireDate(), PHP date() or strftime() date format
// whether or not to show warnings about max include mode
$this->set('showIncludeWarnings', true);
// label when a field is blank
$this->set('blankLabel', $this->_('Blank'));
// bookmarked selectors
$this->set('bookmarks', array());
// whether or not table collapses (rather than horiz scroll) at lower resolutions
$this->set('responsiveTable', true);
// configuration mode where some limits are removed
$this->set('configMode', false);
$idLabel = $this->_('ID');
$pathLabel = $this->_('Path');
$nameLabel = $this->_('Name');
$createdLabel = $this->_('Created');
$modifiedLabel = $this->_('Modified');
$publishedLabel = $this->_('Published');
$modifiedUserLabel = $this->_('Mod By');
$createdUserLabel = $this->_('Created By');
$templateLabel = $this->_('Template');
$statusLabel = $this->_('Status');
$parentLabel = $this->_('Parent');
// Array of system page labels of field_name => label
$this->set('systemLabels', array(
'id' => $idLabel,
'name' => $nameLabel,
'path' => $pathLabel,
'status' => $statusLabel,
'template' => $templateLabel,
'templates_id' => $templateLabel . ' ' . $idLabel,
'modified' => $modifiedLabel,
'created' => $createdLabel,
'published' => $publishedLabel,
'modified_users_id' => $modifiedUserLabel,
'created_users_id' => $createdUserLabel,
'parent' => $parentLabel,
'num_children' => $this->_('Num Children'),
'url' => 'URL',
'httpUrl' => 'Http URL',
));
$this->statusLabels = array(
Page::statusHidden => $this->_('Hidden'),
Page::statusUnpublished => $this->_('Unpublished'),
Page::statusLocked => $this->_('Locked'),
Page::statusTrash => $this->_('Trash'),
);
// remembering pagination
$input = $this->wire()->input;
$pageNum = $input->pageNum;
$pageNum2 = (int) $this->sessionGet('pageNum');
if($input->get('pageNum')) {
// okay, keep pageNum
} else if($pageNum > 1) {
// okay, also just fine
} else if($pageNum2 > 1) {
$pageNum = $pageNum2;
}
$this->sessionSet('pageNum', $pageNum);
$input->setPageNum($pageNum);
}
/**
* Initalize lister variables
*
*/
public function init() {
if(!$this->wire()->page) return;
$input = $this->wire()->input;
$config = $this->wire()->config;
$config->admin = true;
$this->checkSessionBookmark();
$columns = $this->sessionGet('columns');
if($columns) $this->columns = $columns;
$ajax = $config->ajax;
$this->renderResults = $ajax && $input->post('render_results') > 0;
if($this->renderResults) $this->processInput();
if(!$this->template) {
$selector = $this->initSelector;
if($ajax) {
$s = $this->getInputfieldSelector();
$selector .= ", $s->value";
}
$template = $this->getSelectorTemplates($selector);
if(count($template) === 1) $this->set('template', reset($template));
}
if($input->post('reset_total')) {
$this->sessionSet('knownTotal', null);
} else {
$knownTotal = $this->sessionGet('knownTotal');
if(is_array($knownTotal)) $this->knownTotal = $knownTotal;
}
parent::init();
}
/**
* Check for a bookmark specified in GET variable $n
*
* @param string $bookmarkID
* @return null|string|false Returns NULL if not applicable, boolean false if bookmark not found, or integer of bookmark ID if applied
*
*/
public function checkBookmark($bookmarkID = '') {
if(!$bookmarkID) $bookmarkID = $this->wire()->input->get('bookmark');
if(!$bookmarkID) return null;
$bookmarks = $this->getBookmarksInstance();
$bookmarkID = $bookmarks->_bookmarkID($bookmarkID);
if(!$bookmarkID) return false;
$bookmark = $bookmarks->getBookmark($bookmarkID);
if(!$bookmark || !$bookmarks->isBookmarkViewable($bookmark)) return false;
$this->sessionClear();
$this->set('defaultSelector', $bookmark['selector']);
$this->set('defaultSort', $bookmark['sort']);
$this->sessionSet('sort', $bookmark['sort']);
$this->set('columns', $bookmark['columns']);
$this->headline($this->wire()->page->title . ' - ' . $bookmark['title']);
return $bookmarkID;
}
/**
* Check and process session bookmarks and regular bookmarks
*
* If a session_bookmark GET variable is provided with a number that corresponds to session variable
* PageListerBookmarks[session_bookmark] then this function will pull out and use any settings
* specified there rather than the defaults.
*
*/
protected function checkSessionBookmark() {
// check for regular bookmarks first: those specified as $_GET['n']
$bookmarkID = $this->checkBookmark();
if(is_bool($bookmarkID) || is_int($bookmarkID)) return (bool) $bookmarkID;
// then check for session bookmarks
$id = $this->wire()->input->get('session_bookmark');
$clear = $id;
if(!$id) $id = $this->sessionGet('bookmark');
if(is_null($id)) return false;
$id = $this->wire()->sanitizer->name($id);
$bookmarks = $this->wire()->session->get(self::sessionBookmarksName);
if(!is_array($bookmarks) || !isset($bookmarks[$id]) || !is_array($bookmarks[$id])) {
$this->error($this->_('Unrecognized bookmark or bookmark no longer active'));
$this->sessionClear();
return false;
}
if($clear) {
//$this->message("Using session bookmark: $id", Notice::debug);
$this->sessionClear();
$this->sessionSet('bookmark', $id);
}
foreach($bookmarks[$id] as $key => $value) {
if(array_key_exists($key, $this->data)) {
$this->set($key, $value);
}
}
return true;
}
/**
* Given a unique ID and an array of Lister settings (in $bookmark) return a URL to view those pages in Lister
*
* @param string $id ID or name of bookmark
* @param array $bookmark Bookmark data
* @return string Returns URL to Lister with this bookmark or blank on failure (like if user doesn't have access)
*
*/
public static function addSessionBookmark($id, array $bookmark) {
$user = wire()->user;
if(!$user->isSuperuser() && !$user->hasPermission('page-lister')) return '';
$maxBookmarks = 30;
$bookmarks = wire()->session->get(self::sessionBookmarksName);
if(!is_array($bookmarks)) $bookmarks = array();
if(count($bookmarks) > $maxBookmarks) {
// trim bookmarks to max size
$bookmarks = array_slice($bookmarks, -1 * $maxBookmarks, null, true);
}
$bookmarks[$id] = $bookmark;
wire()->session->set(self::sessionBookmarksName, $bookmarks);
return wire()->config->urls->admin . "page/lister/?session_bookmark=$id";
}
/**
* Get the InputfieldSelector instance for this Lister
*
* @return InputfieldSelector
*
*/
public function getInputfieldSelector() {
if($this->inputfieldSelector) return $this->inputfieldSelector;
/** @var InputfieldSelector $s */
$s = $this->wire()->modules->get('InputfieldSelector');
$s->attr('name', 'filters');
$s->attr('id', 'ProcessListerFilters');
$s->initValue = $this->initSelector;
if($this->template) $s->initTemplate = $this->template;
$s->label = $this->_('Filters');
$s->addLabel = $this->_('Add Filter');
$s->icon = 'search-plus';
$s->preview = $this->preview;
$s->counter = false;
$s->allowSystemCustomFields = $this->allowSystem;
$s->allowSystemTemplates = $this->allowSystem;
$s->allowSubfieldGroups = false; // we only support in ListerPro
$s->allowSubselectors = false; // we only support in ListerPro
$s->exclude = 'sort';
$s->limitFields = $this->limitFields;
$s->showFieldLabels = $this->useColumnLabels ? 1 : 0;
if(in_array('collapseFilters', $this->toggles)) $s->collapsed = Inputfield::collapsedYes;
if(in_array('disableFilters', $this->toggles)) {
$s->attr('disabled', 'disabled');
}
$selector = (string) $this->sessionGet('selector');
if($this->initSelector) {
if(strpos($selector, $this->initSelector) !== false) {
$selector = str_replace($this->initSelector, '', $selector); // ensure that $selector does not contain initSelector
}
}
if(!strlen($selector)) {
$selector = $this->defaultSelector;
} else if($this->defaultSelector && strpos($selector, $this->defaultSelector) === false) {
$selector = $this->combineSelector($this->defaultSelector, $selector);
}
$s->attr('value', $selector);
$this->inputfieldSelector = $s;
return $s;
}
/**
* Set a Lister setting
*
* @param string $key
* @param mixed $value
* @return ProcessPageLister|Process
*
*/
public function set($key, $value) {
if($key === 'openPageIDs' && is_array($value)) {
$this->openPageIDs = $value;
return $this;
} else if($key === 'parent' && !$value instanceof Page) {
$value = $this->wire()->pages->get($value);
} else if($key === 'finalSelector') {
$this->finalSelector = $value;
} else if($key === 'limitFields' && !is_array($value)) {
$value = $this->wire()->sanitizer->array($value);
}
return parent::set($key, $value);
}
/**
* Get a Lister setting
*
* @param string $key
* @return mixed|string
*
*/
public function get($key) {
if($key === 'finalSelector') return $this->finalSelector;
return parent::get($key);
}
/**
* Set a Lister session variable
*
* @param string $key
* @param string|int|array $value
*
*/
public function sessionSet($key, $value) {
$key = $this->page->name . '_lister_' . $key;
if(is_null($value)) {
$this->wire()->session->remove($key);
} else {
$this->wire()->session->set($key, $value);
}
}
/**
* Get a Lister session variable
*
* @param string $key
* @param array|string|int $fallback Optional fallback value if session value not present
* @return string|int|array|null
*
*/
public function sessionGet($key, $fallback = null) {
$key = $this->page->name . '_lister_' . $key;
$value = $this->wire()->session->get($key);
if($value === null && $fallback !== null) $value = $fallback;
return $value;
}
/**
* Clear all Lister session variables
*
*/
public function sessionClear() {
$name = $this->page->name;
$session = $this->wire()->session;
foreach($session as $key => $value) {
if(strpos($key, "{$name}_lister_") === 0) $session->remove($key);
}
}
/**
* Process input for the filters form and populate session variables with the results
*
*/
protected function processInput() {
$input = $this->wire()->input;
$sanitizer = $this->wire()->sanitizer;
$filters = $input->post('filters');
if($filters !== null && $filters !== 'ignore') {
$is = $this->getInputfieldSelector();
try {
$is->processInput($input->post);
$selector = $this->sessionGet("selector");
if($selector != $is->value) {
$this->sessionSet("selector", $is->value);
$this->sessionSet("pageNum", 1);
$input->setPageNum(1);
}
} catch(\Exception $e) {
$this->error($e->getMessage());
}
}
$value = $input->post('columns');
if($value !== null && $value !== 'ignore' && !in_array('disableColumns', $this->toggles)) {
$columns = array();
foreach($sanitizer->array($value) as $name) {
$name = $sanitizer->name($name);
if(strlen($name)) $columns[] = $name;
}
if(count($columns)) {
$this->sessionSet('columns', $columns);
$this->columns = $columns;
}
}
$sort = $input->post('sort');
if($sort !== null) {
$sort = $sanitizer->name($sort);
if(strlen($sort)) {
$this->sessionSet("sort", $sort);
$this->set('sort', $sort);
}
}
}
/**
* Build the columns asmSelect
*
*/
public function buildColumnsField() {
$fields = $this->wire()->fields;
$systemColumns = $this->getSystemColumns();
$useLabels = $this->useColumnLabels;
$systemLabels = $this->getSystemLabels();
$template = $this->template;
$customFields = array();
$languages = $this->wire()->languages;
$languagePageNames = $languages && $languages->hasPageNames() && method_exists($this, '___executeSave');
$asmParents = array('name', 'path', 'url', 'httpUrl');
$asmParentValueSuffix = ' …';
/** @var InputfieldAsmSelect $f */
$f = $this->wire()->modules->get('InputfieldAsmSelect');
$f->attr('name', 'columns');
$f->label = $this->_('Default columns');
$f->description = $this->_('Select and sort the columns that will display in the pages list table.');
$f->notes = $this->_('The user can optionally change which columns are shown, so these will just serve as the defaults.'); // columns description
$f->icon = 'table';
// system fields
foreach($systemColumns as $field) {
$label = isset($systemLabels[$field]) ? $systemLabels[$field] : $field;
$isAsmParent = $languagePageNames && in_array($field, $asmParents);
if($useLabels) {
$label1 = $label;
$label2 = $field;
} else {
$label1 = $field;
$label2 = $label;
}
$attrs = array();
if($isAsmParent) {
$asmParentValue = $field . $asmParentValueSuffix;
$value = $asmParentValue;
$attrs['class'] = 'asmParent';
$label1 .= " $asmParentValueSuffix";
$label2 .= " $asmParentValueSuffix";
} else {
$value = $field;
}
$attrs['data-desc'] = $label2;
$f->addOption($value, $label1, $attrs);
if($languagePageNames && $isAsmParent) {
$f->addOption("$field", ($useLabels ? $label : $value), array(
'data-desc' => ($useLabels ? $value : $label),
'data-asmParent' => $value,
'class' => 'asmChild',
));
foreach($languages as $language) {
$langLabel = $this->addLanguageLabel($label, $language, true);
$langValue = "$field-$language->name";
$f->addOption($langValue, ($useLabels ? $langLabel : $langValue), array(
'data-desc' => ($useLabels ? $langValue : $langLabel),
'data-asmParent' => $value,
'class' => 'asmChild',
));
}
}
}
$f->addOption('-', '———', array('disabled' => 'disabled'));
// custom fields (sort)
foreach($fields as $field) {
/** @var Field $field */
if(!$this->allowColumnField($field)) continue;
if($useLabels) {
if($template) {
$_field = $template->fieldgroup->getField($field->name, true); // context
if($_field) $field = $_field;
}
$key = $field->getLabel();
if(isset($customFields[$key])) $key .= " $field->name";
} else {
$key = $field->name;
}
$customFields[$key] = $field;
}
ksort($customFields);
// custom fields (add)
foreach($customFields as $field) {
if($template) {
$_field = $template->fieldgroup->getField($field->name, true); // context
if($_field) $field = $_field;
}
if($useLabels) {
$label = $field->getLabel();
$desc = $field->name;
} else {
$label = $field->name;
$desc = $field->getLabel();
}
$attr = array('data-desc' => $desc);
$icon = $field->getIcon(true);
if($icon) $attr['data-handle'] = wireIconMarkup($icon, 'fw');
$f->addOption($field->name, $label, $attr);
}
$f->attr('value', $this->columns);
return $f;
}
/**
* Get plain array of system field names, for use as columns in buildColumnsField
*
*/
protected function getSystemColumns() {
$systemColumns = array_keys($this->systemLabels);
$systemColumns = array_merge($systemColumns, array('id', 'name', 'path', 'url', 'httpUrl'));
sort($systemColumns);
return $systemColumns;
}
/**
* Get array of system labels, indexed by property name
*
* @return array
*
*/
protected function getSystemLabels() {
$labels = $this->systemLabels;
if($this->template) {
$label = $this->template->getNameLabel();
if($label) $labels['name'] = $label;
}
return $labels;
}
/**
* Whether or not to allow the given $field as a column, for buildColumnsField
*
* @param Field $field
* @return bool
*
*/
protected function allowColumnField(Field $field) {
if(in_array($field->name, $this->disallowColumns)) return false;
if(count($this->limitFields) && !$this->configMode && !in_array($field->name, $this->limitFields)) {
if(!in_array($field->name, $this->columns)) return false;
}
if($field->type instanceof FieldtypeFieldsetOpen) return false;
static $templates = array();
if(empty($templates)) {
$templates = $this->getSelectorTemplates($this->initSelector);
}
if(count($templates)) {
$allow = false;
foreach($templates as $template) {
if($template->fieldgroup->hasField($field)) {
$_field = $template->fieldgroup->getFieldContext($field);
if($_field) $field = $_field;
$allow = $field->viewable();
break;
}
}
} else {
$allow = $field->viewable();
}
return $allow;
}
/**
* Build the Lister columns form
*
* @return InputfieldForm
*
*/
protected function buildColumnsForm() {
/** @var InputfieldForm $form */
$form = $this->wire()->modules->get('InputfieldForm');
$form->attr('id', 'ProcessListerColumnsForm');
$form->method = 'get';
$form->action = './';
$form->class .= ' WireTab';
$form->attr('title', $this->_x('Columns', 'tab'));
$f = $this->buildColumnsField();
$f->description .= ' ' . $this->_('The changes you make here should be reflected immediately in the results below.');
$f->attr('id', 'lister_columns');
$f->label = $this->_('What columns to show in the results');
$f->notes = '';
$form->add($f);
return $form;
}
/**
* Build the Lister filters form
*
* @return InputfieldForm
*
*/
protected function buildFiltersForm() {
/** @var InputfieldForm $form */
$form = $this->wire()->modules->get('InputfieldForm');
$form->attr('id', 'ProcessListerFiltersForm');
$form->method = 'get';
$form->action = './';
$form->class .= ' WireTab';
$f = $this->getInputfieldSelector();
$f->class .= ' WireTab';
$form->attr('title', $f->label);
$f->label = $this->_('What pages to show');
if(in_array('noNewFilters', $this->toggles)) $f->allowAddRemove = false;
$form->add($f);
/** @var InputfieldHidden $f */
$f = $this->wire()->modules->get('InputfieldHidden');
$f->attr('name', 'sort');
$f->attr('id', 'lister_sort');
$f->attr('value', $this->sessionGet('sort'));
$form->add($f);
return $form;
}
/**
* Given two selector strings, combine them into one without duplicates
*
* @param $s1
* @param $s2
* @return string
*
*/
protected function combineSelector($s1, $s2) {
if(empty($s2)) return $s1;
if(empty($s1)) return $s2;
try {
$selectors1 = $this->wire(new Selectors($s1));
} catch(\Exception $e) {
$this->error($e->getMessage());
$selectors1 = new Selectors();
}
try {
$selectors2 = $this->wire(new Selectors($s2));
} catch(\Exception $e) {
$this->error($e->getMessage());
$selectors2 = new Selectors();
}
foreach($selectors1 as /* $key1 => */ $selector1) {
//$value = $selector1->value;
//if(is_array($value) || strlen($value)) continue;
$fieldName1 = $selector1->field;
if(is_array($fieldName1)) $fieldName1 = implode('|', $fieldName1);
// see if we have the same field in selectors2
foreach($selectors2 as /* $key2 => */ $selector2) {
$fieldName2 = $selector2->field;
if(is_array($fieldName2)) $fieldName2 = implode('|', $fieldName2);
if($fieldName1 == $fieldName2) {
// move value from selector2 to selector1
$selectors1->replace($selector1, $selector2);
$selectors2->remove($selector2);
// break out now so that additional values don't get replaced again
break;
}
}
}
$combined = ((string) $selectors1) . ", " . ((string) $selectors2);
return $combined;
}
/**
* Get the selector string to be used in finding results
*
* @param int $limit Max number of results per pagination
* @return string
*
*/
public function ___getSelector($limit = null) {
$selector = $this->sessionGet('selector');
if(!$selector) $selector = $this->initSelector;
if($this->initSelector && strpos($selector, $this->initSelector) === false) {
$selector = "$this->initSelector, $selector";
}
// optionally limit results to just those present in CSV row_page_id POST var containing page IDs, like: 1,2,3
if(isset($_POST['row_page_id'])) {
$pageIDs = array();
foreach(explode(',', $this->wire()->input->post('row_page_id')) as $id) {
$id = (int) $id;
if($id) $pageIDs[] = $id;
}
if(count($pageIDs)) {
$selector .= ", id=" . implode('|', $pageIDs);
return $this->validateSelector($selector);
}
}
if(stripos($selector, 'limit=') === false) {
// no limit is specified in the selector
if($limit) {
$selector .= ", limit=" . (int) $limit;
} else if(is_null($limit)) {
$selector .= ", limit=" . $this->defaultLimit;
}
} else if(!is_null($limit)) {
// limit is specified in both the selector and the arguments.
// we don't allow specifying limit in selector if one is specified in the arguments
$selector = preg_replace('/[, ]*\blimit=\d+/i', '', $selector);
if($limit > 0) $selector .= ", limit=" . (int) $limit;
}
if(stripos($selector, 'sort=') !== false) {
// we don't allow specifying the sort in the selector
// since it is covered by the $this->sort property
$selector = preg_replace('/[, ]*\bsort=([^,]|$)+/i', '', $selector);
}
$sort = $this->sessionGet("sort");
if(!$sort) $sort = $this->defaultSort;
if(!$sort || $sort == 'path') $sort = 'name';