-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFieldtypePageWithLabels.module
More file actions
555 lines (455 loc) · 17.6 KB
/
FieldtypePageWithLabels.module
File metadata and controls
555 lines (455 loc) · 17.6 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
<?php
/**
* ProcessWire Page With Labels Fieldtype
*
* Field that stories references to one or more ProcessWire pages adding the ability to use custom labels for page selection via the InputfieldPageLabeler module
* This module was created from ProcessWire's core FieldtypePage module as the foundation with modifications by Hani AbuGhazaleh (http://processwire.com/talk/user/68-hani/)
*
* ProcessWire 2.3.0
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://www.processwire.com
* https://github.com/Hani79/Processwire_FieldtypePageWithLabels
*
*/
class FieldtypePageWithLabels extends FieldtypeMulti {
public static function getModuleInfo() {
return array(
'title' => 'Page Reference With Custom Labels',
'version' => 100,
'summary' => 'Field that stores one or more references to ProcessWire pages and allows you customize the labels when selecting the page via the InputfieldPageLabeler module',
'permanent' => false,
'requires' => 'InputfieldPageLabeler',
'installs' => 'InputfieldPageLabeler'
);
}
const derefAsPageArray = 0;
const derefAsPageOrFalse = 1;
const derefAsPageOrNullPage = 2;
/**
* Subfield names that will match to the 'pages' table, rather than custom fields
*
*/
protected $nativeNames = array(
'name',
'template',
'templates_id',
'parent',
'parent_id',
'created',
'modified',
);
/**
* Setup a hook to Pages::delete so that we can remove references when pages are deleted
*
*/
public function init() {
$pages = $this->getFuel('pages');
$pages->addHookAfter('delete', $this, 'hookPagesDelete');
}
/**
* FieldtypePageWithLabels instances are only compatible with other FieldtypePage derived classes.
*
*/
public function ___getCompatibleFieldtypes(Field $field) {
$fieldtypes = parent::___getCompatibleFieldtypes($field);
foreach($fieldtypes as $type) if(!$type instanceof FieldtypePage && !$type instanceof FieldtypePageWithLabels) $fieldtypes->remove($type);
return $fieldtypes;
}
/**
* Delete any records that are referencing the page that was deleted
*
*/
public function hookPagesDelete($event) {
if(!$event->return) return; // if delete failed, then don't continue
$page_id = $event->arguments[0]->id;
foreach($this->fuel('fields') as $field) {
if(!$field->type instanceof FieldtypePageWithLabels) continue;
$sql = "DELETE FROM `{$field->table}` WHERE data='$page_id'";
$this->db->query($sql);
}
}
/**
* We want FieldtypePageWithLabels to autoload so that it can monitor page deletes
*
*/
public function isAutoload() {
return true;
}
/**
* Return an InputfieldPage of the type configured
*
*/
public function getInputfield(Page $page, Field $field) {
$inputfield = $this->fuel('modules')->get("InputfieldPageLabeler");
$inputfield->class = $this->className();
return $inputfield;
}
/**
* Given a raw value (value as stored in DB), return the value as it would appear in a Page object
*
* @param Page $page
* @param Field $field
* @param string|int|array $value
* @return string|int|array|object $value
*
*/
public function ___wakeupValue(Page $page, Field $field, $value) {
$template = null;
$parent_id = null;
if($field->template_id) $template = $this->fuel('templates')->get($field->template_id);
if($field->parent_id) $parent_id = $field->parent_id;
// handle $value if it's blank, Page, or PageArray
if($field->derefAsPage > 0) {
// value will ultimately be a single Page
if(!$value) return $this->getBlankValue($page, $field);
// if it's already a Page, then we're good: return it
if($value instanceof Page) return $value;
// if it's a PageArray and should be a Page, determine what happens next
if($value instanceof PageArray) {
// if there's a Page in there, return the first one
if(count($value) > 0) return $value->first();
// it's an empty array, so return whatever our default is
return $this->getBlankValue($page, $field);
}
} else {
// value will ultimately be multiple pages
// if it's already a PageArray, great, just return it
if($value instanceof PageArray) return $value;
// setup our default/blank value
$pageArray = $this->getBlankValue($page, $field);
// if $value is blank, then return our default/blank value
if(empty($value)) return $pageArray;
}
// if we made it this far, then we know that the value was not empty
// so it's going to need to be populated from one type to the target type
// we're going to be dealing with $value as an array this point forward
// this is for compatibility with the Pages::getById function
if(!is_array($value)) $value = array($value);
if($field->derefAsPage > 0) {
// we're going to return a single page, NullPage or false
$pg = false;
if(count($value)) {
// get the first value in a PageArray, using $template and parent for optimization
$pageArray = $this->fuel('pages')->getById(array((int) reset($value)), $template);
if(count($pageArray)) $pg = $pageArray->first();
}
if(!$pg || ($pg && $pg->status >= Page::statusUnpublished)) $pg = $this->getBlankValue($page, $field);
return $pg;
} else {
// we're going to return a PageArray
$pageArray = $this->fuel('pages')->getById($value, $template);
foreach($pageArray as $pg) {
// remove any pages that have an unpublished status
if($pg->status >= Page::statusUnpublished) $pageArray->remove($pg);
}
$pageArray->resetTrackChanges();
return $pageArray;
}
}
/**
* Given an 'awake' value, as set by wakeupValue, convert the value back to a basic type for storage in DB.
*
* @param Page $page
* @param Field $field
* @param string|int|array|object $value
* @return string|int
*
*/
public function ___sleepValue(Page $page, Field $field, $value) {
$sleepValue = array();
if($field->derefAsPage > 0) {
// if the $value isn't specifically a Page, make it a blank array for storage
if(!$value instanceof Page || !$value->id) return $sleepValue;
// if $value is a Page (not a NullPage) then place it's ID in an array for storage
$sleepValue[] = $value->id;
} else {
// if $value isn't a PageArray then we'll store a blank array
if(!$value instanceof PageArray) return $sleepValue;
// iterate through the array and place each Page ID
foreach($value as $pg) {
if(!$pg->id) continue;
$sleepValue[] = $pg->id;
}
}
return $sleepValue;
}
/**
* Return either a blank Page or a blank PageArray
*
*/
public function getBlankValue(Page $page, Field $field) {
if($field->derefAsPage == FieldtypePageWithLabels::derefAsPageArray) {
// multi page blank value
$pageArray = new PageArray();
$pageArray->setTrackChanges(true);
return $pageArray;
} else if($field->derefAsPage == FieldtypePageWithLabels::derefAsPageOrFalse) {
// single page possible blank values
return false;
} else if($field->derefAsPage == FieldtypePageWithLabels::derefAsPageOrNullPage) {
// single page possible blank values
return new NullPage();
}
}
/**
* Given a string value return either a Page or PageArray
*
* @param Page $page
* @param Field $field
* @param string $value
* return Page|PageArray
*
*/
protected function sanitizeValueString(Page $page, Field $field, $value) {
$selector = '';
$result = false;
if(Selectors::stringHasOperator($value)) {
// selector string
$selector = $value;
$inputfield = $field->getInputfield($page);
$selectablePages = $inputfield->getSelectablePages($page);
$result = $selectablePages->filter($selector);
} else if(ctype_digit("$value")) {
// page ID
$result = $this->pages->get("id=" . $value);
} else if(strpos($value, '|') !== false && ctype_digit(str_replace('|', '', $value))) {
$result = $this->pages->getById(explode('|', $value));
} else if(strpos($value, '|') !== false && ctype_digit(str_replace('|', '', $value))) {
// CSV string separated by '|' characters
$result = $this->pages->getById(explode('|', $value));
} else if(strlen($value) && $value[0] == '/') {
// path to page
$result = $this->pages->get($value);
}
return $result;
}
/**
* Given a value of unknown type, return a Page or PageArray (depending on $field->derefAsPage setting)
*
* @param Page $page
* @param Field $field
* @param Page|PageArray|string|int $value
* @return Page|PageArray|bool Returns false if value can't be converted to the proper object type.
*
*/
public function sanitizeValue(Page $page, Field $field, $value) {
if($field->derefAsPage > 0) return $this->sanitizeValuePage($page, $field, $value);
return $this->sanitizeValuePageArray($page, $field, $value);
}
/**
* Handles the sanitization of values when target is a single Page
*
*/
protected function sanitizeValuePage(Page $page, Field $field, $value) {
if(!$value) return $this->getBlankValue($page, $field);
if($value instanceof Page) return $value;
if($value instanceof PageArray) $value = $value->first();
if(is_string($value) || is_int($value)) {
$value = $this->sanitizeValueString($page, $field, $value);
if($value instanceof PageArray) $value = $value->first();
}
return (($value instanceof Page) && $value->id) ? $value : $this->getBlankValue($page, $field);
}
/**
* Handles the sanitization of values when target is a PageArray
*
*/
protected function sanitizeValuePageArray(Page $page, Field $field, $value) {
// if they are setting it to a PageArray, then we'll take it
if($value instanceof PageArray) return $value;
// otherwise, lets get the current value so we can add to it or return it
$pageArray = $page->get($field->name);
// if no value was provided, then return the existing value already in the page
if(!$value) return $pageArray;
// if it's a string, see if we can convert it to a Page or PageArray
if(is_string($value)) $value = $this->sanitizeValueString($page, $field, $value);
// if it's a Page, and not NullPage, add it to the existing PageArray
if($value instanceof Page) {
if($value->id) return $pageArray->add($value);
else return $pageArray;
}
// if it's a new PageArray, combine it with the existing PageArray
if($value instanceof PageArray) {
foreach($value as $pg) {
if(!$pg->id) continue;
$pageArray->add($pg);
}
return $pageArray;
}
if(!is_array($value)) $value = array($value);
foreach($value as $pg) $pageArray->add($pg);
return $pageArray;
}
/**
* Update a DatabaseSelectQuery object to match a Page
*
* @param DatabaseSelectQuery $query
* @param string $table
* @param string $subfield
* @param string $operator
* @param string $value
* @return DatabaseSelectQuery
*
*/
public function getMatchQuery($query, $table, $subfield, $operator, $value) {
$names = array(
'id',
'data',
'pages_id',
'path',
'url',
'sort',
);
// if subfield is 'data' (meaning no subfield specified) and it's in the format of 'some-string',
// then we assume this to be a page name
if($subfield == 'data' && !ctype_digit("$value") && strlen($value) && strpos($value, '/') === false) {
$subfield = 'name';
}
// let the FieldtypeMulti base class handle count queries
if($subfield == 'count') {
return parent::getMatchQuery($query, $table, $subfield, $operator, $value);
} else if(in_array($subfield, $names)) {
if(!$this->fuel('db')->isOperator($operator)) throw new WireException("Operator '$operator' is not implemented in {$this->classname}");
if(in_array($subfield, array('id', 'path', 'url'))) $subfield = 'data';
// if a page path rather than page ID was provided, then we translate the path to an ID for API syntax convenience
if(!ctype_digit("$value")) {
if(substr(trim($value), 0, 1) == '/') {
// path from root
$v = $this->pages->get($value);
if($v && $v->id) $value = $v->id;
}
}
$value = $this->fuel('db')->escape_string($value);
if($operator == '!=') {
$t = $query->field->getTable();
$query->where("(SELECT COUNT(*) FROM $t WHERE $t.pages_id=pages.id AND $t.$subfield='$value')=0");
} else {
$query->where("($table.{$subfield}{$operator}'$value')"); // pages.id AND $table.pages_id{$operator}'$value')");
}
} else if($this->getMatchQueryNative($query, $table, $subfield, $operator, $value)) {
// great
} else if($this->getMatchQueryCustom($query, $table, $subfield, $operator, $value)) {
// wonderful as well
} else {
// we were unable to determine what subfield is
throw new WireException("Unknown subfield: $subfield");
}
return $query;
}
/**
* Update a DatabaseSelectQuery object to match a Page with a subfield native to pages table
*
* @param DatabaseSelectQuery $query
* @param string $table
* @param string $subfield
* @param string $operator
* @param string $value
* @return bool True if used, false if not
*
*/
protected function getMatchQueryNative($query, $table, $subfield, $operator, $value) {
if(!in_array($subfield, $this->nativeNames)) return false;
// we let the custom field query matcher handle the '!=' scenario
if($operator == '!=') return $this->getMatchQueryCustom($query, $table, $subfield, $operator, $value);
if($subfield == 'created' || $subfield == 'modified') {
if(!ctype_digit($value)) $value = strtotime($value);
$value = (int) $value;
} else if(in_array($subfield, array('template', 'templates_id'))) {
$template = $this->templates->get($subfield);
$value = $template ? $template->id : 0;
$subfield = 'templates_id';
} else if(in_array($subfield, array('parent', 'parent_id'))) {
if(!ctype_digit("$value")) $value = $this->pages->get($value)->id;
$subfield = 'parent_id';
} else if($subfield == 'name') {
$value = $this->sanitizer->pageName($value);
} else $value = (int) $value;
static $n = 0;
$table2 = "_fieldtypepage" . (++$n);
$value = $this->fuel('db')->escape_string($value);
$query->join("pages AS $table2 ON $table2.$subfield$operator'$value'");
$query->where("($table.data=$table2.id)");
return true;
}
/**
* Update a DatabaseSelectQuery object to match a Page containing a matching custom subfield
*
* @param DatabaseSelectQuery $query
* @param string $table
* @param string $subfield
* @param string $operator
* @param string $value
* @return bool true if used, false if not
*
*/
protected function getMatchQueryCustom($query, $table, $subfield, $operator, $value) {
if(in_array($subfield, $this->nativeNames)) {
// fine then, we can handle that here when needed (like !=)
} else {
$subfield = wire('fields')->get($subfield);
if(!$subfield) return false; // not a custom field
$subfield = $subfield->name;
}
$field = $query->field;
// perform a separate find() operation for the subfield
$pageFinder = new PageFinder();
$value = wire('sanitizer')->selectorValue($value);
// build a selector to find matching pagerefs
// @todo should $selector include check_access=0 or even include=all?
$selector = 'include=hidden, ';
if($field->findPagesSelector) $selector .= $field->findPagesSelector . ", ";
if($field->parent_id) $selector .= "parent_id={$field->parent_id}, ";
if($field->template_id) $selector .= "templates_id={$field->template_id}, ";
// @todo note $field->findPagesCode is not implemented
if($operator == '!=') {
$selector .= "{$subfield}=$value, ";
$matches = $pageFinder->find(new Selectors(trim($selector, ', ')));
if(count($matches)) {
$ids = array();
foreach($matches as $match) $ids[$match['id']] = $match['id'];
static $xcnt = 0;
$t = 'x_' . $field->table . (++$xcnt);
$query->leftjoin("{$field->table} AS $t ON $t.pages_id=pages.id AND $t.data IN(" . implode(',', $ids) . ")");
$query->parentQuery->where("$t.data IS NULL");
}
} else {
$selector .= "{$subfield}$operator$value, ";
$matches = $pageFinder->find(new Selectors(trim($selector, ', ')));
// use the IDs found from the separate find() as our getMatchQuery
if(count($matches)) {
$ids = array();
foreach($matches as $match) $ids[$match['id']] = $match['id'];
$query->where("$table.data IN(" . implode(',', $ids) . ")");
} else $query->where("1>2"); // forced non-match
}
return true;
}
/**
* Return the database schema in predefined format
*
*/
public function getDatabaseSchema(Field $field) {
$schema = parent::getDatabaseSchema($field);
$schema['data'] = 'int NOT NULL';
$schema['keys']['data'] = 'KEY data (data, pages_id, sort)';
return $schema;
}
/**
* Return configuration fields definable for each FieldtypePageWithLabels
*
*/
public function ___getConfigInputfields(Field $field) {
$inputfields = parent::___getConfigInputfields($field);
$select = $this->modules->get("InputfieldRadios");
$select->attr('name', 'derefAsPage');
$select->label = $this->_('Dereference in API as');
$select->description = $this->_('If your field will contain multiple pages, then you should select the first option (PageArray). If your field only needs to contain a single page, then select one of the single Page options (if you are not sure which, select the last option).'); // Long description for: dereference in API
$select->addOption(FieldtypePageWithLabels::derefAsPageArray, $this->_('Multiple pages (PageArray)'));
$select->addOption(FieldtypePageWithLabels::derefAsPageOrFalse, $this->_('Single page (Page) or boolean false when none selected'));
$select->addOption(FieldtypePageWithLabels::derefAsPageOrNullPage, $this->_('Single page (Page) or empty page (NullPage) when none selected'));
$select->attr('value', (int) $field->derefAsPage);
$inputfields->append($select);
return $inputfields;
}
}