-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPageTableNext.module
More file actions
693 lines (568 loc) · 21.1 KB
/
PageTableNext.module
File metadata and controls
693 lines (568 loc) · 21.1 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
<?php
/**
* COPYRIGHT NOTICE
* Copyright (c) 2025 Neue Rituale GbR
* @author NR <code@neuerituale.com>
* @license MIT
*/
namespace ProcessWire;
/**
* @method string getContentElementTitle(Page $page, $formatted = false)
* @method string getContentElementTitlePostfix(Page $page, $formatted = false)
* @method WireArray findPageTableNextFields()
* @method WireArray findAdditionalReferenceFields()
* @method array findAbandonedPageIds()
* @method PageArray findAbandonedPages(array $options = [])
* @method false|int|string getDbColumn(Field $field, Page $page)
* @method void setupFieldAndTemplate(string $newFieldName = 'ptn')
*/
class PageTableNext extends WireData implements Module {
public array $isPageTableNextContentElementCache = [];
public static function getModuleInfo(): array {
return [
'title' => __('PageTable Next (Controller)'),
'summary' => __('PageTable with scoped admin preview'),
'version' => 205,
'requires' => ['ProcessWire>=3.0.179', 'PHP>=7.4.0'],
'installs' => [
'InputfieldPageTableNext',
'InputfieldPageTable',
'FieldtypePageTableNext',
'FieldtypePageTable',
'ProcessPageClone'
],
'autoload' => true,
'singular' => true
];
}
public function init() {
// Add page reference to other fields like PageTable(Next) or Profields: Table
$this->addHookAfter('Page::references', $this, 'hookReferences');
$this->addHookAfter('Page::numReferences', $this, 'hookReferences');
// Optimize PageEditForm (headline, browser title and breadcrumbs)
$this->addHookBefore('ProcessPageEdit::execute', $this, 'hookContentElementEditForm');
// Allow view for content element templates
$this->addHook('Page::viewable', $this, 'hookContentElementViewStatus');
// Invalidate content element parent page cache
$this->addHookAfter('Pages::saved', $this, 'hookInvalidateReferencedPagesCache');
// Persist sorting on update
$this->addHookBefore('InputfieldPageTableAjax::checkAjax', $this, 'hookInputfieldPageTableAjaxCheckAjax', ['priority' => 200]);
// Make PageTableNext field indexable for SearchEngine
if($this->modules->isInstalled('SearchEngine')) {
$this->addHookAfter('Indexer::isRepeatableField', $this, 'hookSearchEngineIsRepeatable');
}
}
public function ready() {
// Manipulate localHttpUrl for content element templates
$this->addHook('Page::path', $this, 'hookContentElementPath');
$this->addHook('Page::localHttpUrl', $this, 'hookContentElementPath');
}
/**
* Check if page is a content element page
* @param Page $page
* @return bool
*/
private function isPageTableNextContentElement(Page $page): bool {
// skip double check
if(array_key_exists($page->id, $this->isPageTableNextContentElementCache)) return $this->isPageTableNextContentElementCache[$page->id];
$pageTableNextFields = $this->findPageTableNextFields();
foreach($pageTableNextFields as $pageTableNextField) {
if($page->parents('id=' . $pageTableNextField->parent_id)->count) {
$this->isPageTableNextContentElementCache[$page->id] = true;
return true;
}
}
$this->isPageTableNextContentElementCache[$page->id] = false;
return false;
}
/**
* Find all PageTableNext fields
* @return WireArray
*/
public function ___findPageTableNextFields(): WireArray {
return $this->fields->find('type=FieldtypePageTableNext');
}
/**
* Find compatible field for reference Pages
* @return WireArray
*/
public function ___findAdditionalReferenceFields(): WireArray {
return $this->fields->find('type=FieldtypePageTableNext|FieldtypePageTableExtended|FieldtypePageTable|FieldtypeTable');
}
/**
* Find abandoned page ids
* Check all pages in the ptn store to see whether they are still linked to a ptn field.
*
* @return array
* @throws WireDatabaseQueryException
* @throws WireException
*/
public function ___findAbandonedPageIds(): array {
$fields = $this->findPageTableNextFields();
if(!$fields->count) throw new \Exception('PageTable next fields not found');
$query = new DatabaseQuerySelect();
$query->select('id');
$query->from('pages');
/** @var Field $field */
foreach($fields as $field) {
if(!$field->parent_id) continue; // skip fields without valid parent_id
$table = $field->getTable();
$query->leftjoin("$table on {$table}.data = pages.id");
$query->where("pages.parent_id=?", $field->parent_id);
$query->where("{$table}.data is null");
}
return $query->execute()->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* Find abandoned pages
*
* @param array $options
* @return PageArray
* @throws WireException
*/
public function ___findAbandonedPages(array $options = []): PageArray {
$options = array_merge([
'selector' => 'limit=25, sort=-modified, include=all',
'additionalSelector' => '',
'finderOptions' => ['lazy' => true]
], $options);
$abandonedPageIds = $this->findAbandonedPageIds();
if(!count($abandonedPageIds)) return new PageArray();
$selectors = new Selectors($options['selector']);
if($options['additionalSelector']) $selectors->import($options['additionalSelector']);
$selectors->add(new SelectorEqual('id', $abandonedPageIds));
return wire()->pages->find($selectors, $options['finderOptions']);
}
/**
* Build ContentElementTitle for overview, window and browser title
* @param Page $page
* @param bool $formatted
* @return string
*/
public function ___getContentElementTitle(Page $page, bool $formatted = false): string {
$category = $page->template->get('label|name');
$title = $page->title;
$out = !empty($title)
? "<b>$category:</b> <i>$title</i>"
: "<b>$category</b>"
;
return $formatted ? $out : strip_tags($out);
}
/**
* Add some title postfixes
* @param Page $page
* @param bool $formatted
* @return string
*/
public function ___getContentElementTitlePostfix(Page $page, bool $formatted = false): string {
return '';
}
/**
* Build path to content element e.g. /de/my-page/#s5421
* @param Page $page
* @param Page $reference
* @param Language|null $language
* @return string
*/
public function ___buildContentElementPath(Page $page, Page $reference, Language $language = null): string {
// get path
$path = $this->modules->isInstalled('LanguageSupportPageNames') && $language instanceof Language
? $reference->localPath($language)
: $reference->path()
;
return $path . '#s' . $page->id;
}
/**
* Optimize headline, browser title and breadcrumb to sections
* @param HookEvent $event
* @return void
* @throws WireException
*/
public function hookContentElementEditForm(HookEvent $event): void {
/** @var ProcessPageEdit $processPageEdit */
$processPageEdit = $event->object;
$page = $processPageEdit->getPage();
if($this->isPageTableNextContentElement($page)) {
// headline
$headline = $this->getContentElementTitle($page);
$processPageEdit->headline($headline);
// BrowserTitle
$processPageEdit->browserTitle($headline);
// breadcrumb
/** @var Breadcrumbs $breadcrumbs */
$breadcrumbs = wire('breadcrumbs');
$reference = $page->references('include=all')->first();
if($reference && $reference->id) {
// clear and set new
$breadcrumbs->removeAll();
// add parents
foreach($reference->parents as $b) $breadcrumbs->add( new Breadcrumb('../?open=' . $b->id, $b->getText('title|name')) );
// add section reference
$breadcrumbs->add( new Breadcrumb($reference->editUrl, $reference->getText('title|name')) );
}
}
}
/**
* Find embed page for all content element templates
* and manipulate local httpurl
*
* @param HookEvent $event
* @return void
* @throws WireException
* @throws WirePermissionException
*/
public function hookContentElementPath(HookEvent $event): void {
/** @var Page $page */
$page = $event->object;
if(!$this->isPageTableNextContentElement($page)) return;
$reference = $page->references('include=unpublished')->first();
// no references found
if(!$reference || !$reference->id) return;
// build path
$event->return = $this->buildContentElementPath($page, $reference, $event->arguments(0));
}
/**
* Allow "view" for "section-" templates without template-file
* The url goes to the embed page
* @see Hooks::hookManipulateUrlForSections
*
* @param HookEvent $event
* @return void
*/
public function hookContentElementViewStatus(HookEvent $event) {
/** @var Page $page */
$page = $event->object;
if(!$this->isPageTableNextContentElement($page)) return;
$event->return = $page->hasStatus(Page::statusTemp) || $page->numReferences('include=unpublished') > 0;
}
/**
* Persist sorting on update
* Same as @see InputfieldPageTableAjax::___checkAjax()
* Add $page->save($field->name); to update sorting
*
* @param HookEvent $event
* @return void
* @throws WireException
* @throws WirePermissionException
*/
protected function hookInputfieldPageTableAjaxCheckAjax(HookEvent $event) {
/** @var InputfieldPageTableAjax $inputfieldPageTableAjax */
$inputfieldPageTableAjax = $event->object;
$event->replace = true;
$input = $this->wire('input');
$fieldName = $input->get('InputfieldPageTableField');
if(!$fieldName) return;
$processPage = $this->wire('page');
if(!in_array('WirePageEditor', wireClassImplements((string) $processPage->process))) return; // not ProcessPageEdit or compatible
$field = $this->wire('fields')->get($this->wire('sanitizer')->fieldName($fieldName));
if(!$field || !$field->type instanceof FieldtypePageTable) return; // die('field does not exist or is not FieldtypePageTable');
$pageID = (int) $input->get('id');
if(!$pageID) return; // die('page ID not specified');
$page = $this->wire('pages')->get($pageID);
if(!$page->id) return;
if(!$page->editable($field->name)) return;
$page->of(false);
$page->get($field->name); // preload, fixes issue #518 with formatted version getting loaded when it shouldn't
// check for new item that should be added
$itemID = (int) $input->get('InputfieldPageTableAdd');
if($itemID) $inputfieldPageTableAjax->addItem($page, $field, $this->wire('pages')->get($itemID));
$sort = $input->get('InputfieldPageTableSort');
if(strlen("$sort")) {
$inputfieldPageTableAjax->sortItems($page, $field, $sort);
try { $page->save($field->name); } catch(\Exception $exception) { /**/ }
}
$inputfieldPageTableAjax->renderAjax($page, $field);
}
/**
* Invalidate cache from content element referenced pages
* @param HookEvent $event
* @return void
* @throws WireException
*/
public function hookInvalidateReferencedPagesCache(HookEvent $event) {
/** @var Page $page */
$page = $event->arguments(0);
if(!$this->isPageTableNextContentElement($page)) return;
/** @var array $referenceFields */
$referenceFields = $page->references('include=all,check_access=0',true);
/**
* @see Page::___references()
* @var string $fieldName
* @var PageArray $references
*/
foreach($referenceFields as $fieldName => $references) {
/** @var Page $reference */
foreach($references as $reference) {
$reference->of(false);
$reference->save($fieldName);
}
}
}
/**
* Handle the call #reference
* @param HookEvent $event
*/
public function hookReferences(HookEvent $event) {
/** @var Page $page */
$page = $event->object;
if(!($page instanceof Page)) return;
$additionalReferences = $this->findReferences(
$page,
$event->arguments(0),
$event->arguments(1),
$event->method === 'numReferences'
);
// Add References
if($event->return instanceof PageArray) {
if($additionalReferences instanceof PageArray) $event->return->add($additionalReferences);
} else {
$event->return = $additionalReferences;
}
}
/**
* Make PageTableNext field indexable for SearchEngine
* @param HookEvent $event
* @return void
*/
public function hookSearchEngineIsRepeatable(HookEvent $event) {
$field = $event->argumentsByName('field');
if(!$event->return && $field->type instanceof FieldtypePageTableNext) $event->return = true;
}
/**
* #reference
* Return pages referencing the given $page, optionally indexed by field name
*
* The default behavior when no arguments are provided (except $page) is to simply return a PageArray of all pages
* referencing the given one (excluding hidden, unpublished, trash, no-access, etc.). Specify "include=all"
* as your $selector if you want to include all pages without filtering. If the quantity may be large,
* you should also include a "limit=100" (replacing 100 with your limit). This method supports pagination
* when specifying a limit.
*
* @param Page $page Page to get references for
* @param string|bool $selector Optionally filter/modify returned result, i.e. "limit=10, include=all", etc.
* Or boolean TRUE as shortcut for "include=all".
* @param bool|Field|null $field Optionally specify Field to limit results to (default includes all fields of this type),
* Or boolean TRUE to return array indexed by field name.
* @param bool $getCount Specify true to get a count (int) rather than a PageArray (default=false)
* @return PageArray|array|int Returns one of the following, according to the provided arguments:
* - returns PageArray as default behavior, including when given a $selector string and/or Field object.
* - returns array of PageArray objects if $field argument is TRUE ($selector may be populated string or blank string).
* - returns int if the count option (boolean true) specified for $selector.
*
*/
public function findReferences(Page $page, $selector = '', $field = false, bool $getCount = false) {
/** @var Pages $pages */
$pages = $this->wire('pages');
// modifier option defaults
$byField = false;
$includeAll = $selector === true || $selector === "include=all";
$findLimit = 200;
$fieldName = '';
// determine whether to use include=all
if($selector === true) {
$selector = "include=all";
} else if(strlen((string) $selector) && !$includeAll && strpos((string) $selector, "include=all") !== false) {
foreach(new Selectors($selector) as $s) {
if($s->field() === 'include' && $s->value() === 'all') {
$includeAll = true;
break;
}
}
}
if(is_bool($field) || is_null($field)) {
$byField = $field ? true : false;
} else if(is_string($field)) {
$fieldName = $this->wire('sanitizer')->fieldName($field);
} else if(is_int($field)) {
$field = $this->wire('fields')->get($field);
if($field) $fieldName = $field->name;
} else if($field instanceof Field) {
$fieldName = $field->name;
}
// results
$fieldNames = array(); // field names that point to $page, array of [ field_id => field_name ]
$fieldCounts = array(); // counts indexed by field name (if count mode)
$total = 0;
// first determine which fields have references to $page
foreach($this->findAdditionalReferenceFields() as $field) {
if($fieldName && $field->name != $fieldName) continue;
// get the db column
if(!$column = $this->getDbColumn($field, $page)) continue;
$table = $field->getTable();
$sql = "SELECT COUNT(*) FROM `$table` WHERE `$column`=:id";
$query = $this->wire('database')->prepare($sql);
$query->bindValue(':id', $page->id, \PDO::PARAM_INT);
$query->execute();
$cnt = (int) $query->fetchColumn();
if($cnt > 0 || true) {
$fieldNames[$field->id] = $field->name;
if($column !== 'data') $fieldNames[$field->id] .= '.' . $column;
$fieldCounts[$field->name] = $cnt;
$total += $cnt;
}
$query->closeCursor();
}
// if they just asked for the count, then we have all that we need to finish now
if($getCount && $includeAll) {
// return count or array of counts
return $byField ? $fieldCounts : $total;
}
// if there was nothing found, finish early
if(!$total) {
// no references found
if($getCount) return $total;
return $byField ? array() : $pages->newPageArray();
}
// perform another find() to filter results, and return requested result type
if($byField) {
// return array of PageArrays indexed by fieldName
$result = array();
foreach($fieldNames as $fieldName) {
$s = rtrim("$fieldName=$page->id, $selector", ', ');
if($getCount) {
$cnt = $pages->count($s);
if($cnt) $result[$fieldName] = $cnt;
} else {
if($total > $findLimit) {
$items = $pages->findMany($s);
} else {
$items = $pages->find($s);
}
if($items->count()) $result[$fieldName] = $items;
}
}
} else {
// return PageArray of all references
$selector = rtrim(implode('|', $fieldNames) . "=$page->id, $selector", ', ');
if($getCount) {
$result = $pages->count($selector);
} else if($total > $findLimit) {
$result = $pages->findMany($selector);
} else {
$result = $pages->find($selector);
}
}
return $result;
}
/**
* Find first database page column from table #reference
* @param Field $field
* @param Page $page
* @return false|int|string
*/
public function ___getDbColumn(Field $field, Page $page) {
$column = false;
if($field->type instanceof FieldtypePageTable) {
$column = 'data';
} elseif($field->type instanceof FieldtypeTable) {
$tableFields = $field->type->getColumns($field);
$column = array_search('Page', array_column($tableFields, 'valid', 'name') );
}
return $column;
}
/**
* Setup field and template, create folder page
* @param string $newFieldName
* @return void
* @throws WireException
*/
public function ___setupFieldAndTemplate(string $newFieldName = 'ptn') {
$newFieldName = $this->sanitizer->sanitize($newFieldName, 'fieldName,filename');
if(empty($newFieldName)) throw new \Exception('Empty field name');
$newFolderName = 'content-elements';
/** ************************************************** CREATE FIELD */
$ptnFieldData = $this->getData('fields')['ptn'];
$ptnFieldData['name'] = $newFieldName;
$ptnField = null;
// Check existing fields
if($foundField = $this->fields->getAll()->get($newFieldName)) {
if($foundField->type instanceof FieldtypePageTableNext) {
$ptnField = $foundField;
$this->message(sprintf($this->_('Use existing field: %s'), $foundField->name));
}
else throw new \Exception('Fieldname is already in use');
}
// Create field
else {
$ptnField = new Field();
$ptnField->setImportData($ptnFieldData);
$ptnField->save();
$this->message(sprintf($this->_('Create field: %s'), $newFieldName));
}
/** ************************************************** CREATE TEMPLATE */
$ceTemplateData = $this->getData('templates')['content-elements'];
$newTemplateName = 'content-elements';
$ceTemplate = null;
// Check existing template
if($foundTemplate = $this->templates->get($newTemplateName)) {
$ceTemplate = $foundTemplate;
$this->message(sprintf($this->_('Use existing template: %s'), $foundTemplate->name));
}
// Create field group and template
else {
$fg = new Fieldgroup();
$fg->name = $newTemplateName;
foreach ($ceTemplateData['fieldgroupFields'] as $fieldname) $fg->add($fieldname);
$fg->save();
$ceTemplate = new Template();
$ceTemplate->setImportData($ceTemplateData) ;
$ceTemplate->save();
$this->message(sprintf($this->_('Create template: %s'), $newTemplateName));
}
/** ************************************************** COPY RENDER FILE */
$renderFileName = $newFieldName;
// Check file with same name exists
if(file_exists($this->config->paths->fieldTemplates . "{$renderFileName}.php")) {
// same file
if(
hash_file('sha256', $this->config->paths->fieldTemplates . "{$renderFileName}.php") ===
hash_file('sha256', $this->config->paths->PageTableNext . "data/ptn.php")
) {
$this->message(sprintf($this->_('Render file already exists in: %s'), $this->config->urls->fieldTemplates . $renderFileName . '.php'));
}
// other file
else {
$renderFileName = '__' . $renderFileName;
$this->warning(sprintf($this->_('Please remove "__" from render file in: %s'), $this->config->urls->fieldTemplates . $renderFileName . '.php'));
}
}
else {
$this->message(sprintf($this->_('Render file are copied to: %s'), $this->config->urls->fieldTemplates . $renderFileName . '.php'));
}
$this->files->copy(
$this->config->paths->PageTableNext . 'data/ptn.php',
$this->config->paths->fieldTemplates . "{$renderFileName}.php"
);
/** ************************************************** CREATE CONTENT ELEMENT FOLDER PAGE */
$ce = $this->pages->getByPath($this->config->urls->admin . $newFolderName);
// Page already exists
if($ce->id) {
$this->message(sprintf($this->_('content elements folder already exists'), $ce->path));
}
// Create page
else {
$ce = $this->pages->newPage([
'template' => $ceTemplate,
'name' => $newFolderName,
'parent' => $this->config->urls->admin,
'title' => $this->_('Content Elements'),
'status' => Page::statusHidden
]);
$ce->save();
$this->message(sprintf($this->_('Create content elements folder'), $ce->path));
}
/** ************************************************** UPDATE FIELD */
if($ptnField instanceof Field) {
$ptnField->set('parent_id', $ce->id);
$ptnField->save();
}
}
/**
* Get field data
* @return mixed
*/
private function getData(string $data) {
$fields_json = file_get_contents(__DIR__ . "/data/{$data}.json");
return json_decode($fields_json, true);
}
}