This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProcessSetupPageName.module
executable file
·465 lines (426 loc) · 18.5 KB
/
ProcessSetupPageName.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
<?php
/**
*
* made by kixe (Christoph Thelen) 15.12.15
* Licensed under GNU/GPL v3
*
* ProcessWire 2.x
* Copyright (C) 2015 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://processwire.com
*
* @version 2.1.5
* @since 2.0.2 2017-02-15 configurable option allows to update existing pages if field values have been changed
* @since 2.0.4 2017-05-05 use datetime field output format according to field settings (allow strftime format)
* @since 2.0.5 2017-05-05 aware of LanguageSupport::_(‚C‘) translations and dateOutputFormat (language sensitive) in datetime fields
* @since 2.0.6 2017-05-05 in case of FieldtypeOptions pull pagename from value OR title if no value available
* @since 2.0.7 2017-05-06 use Languages::setLocale() instead of PHP::setlocale()
* @since 2.0.8 2017-05-06 fixed issue: call of Languages::setLocale() in single language environment and fallback to default language title
* @since 2.0.9 2017-08-14 fixed issue: changed call of WireDateTime::formatDate() from static to procedural
* @since 2.1.0 2018-03-19 prevent notice if field doesn't exist in page template line:175
* @since 2.1.1 2018-10-25 fixed issue: getting title of options field in multilanguage environment, added fallback to default language for datetime of
* @since 2.1.2 2018-10-31 fixed issue: fieldtype options
* @since 2.1.3 2018-11-01 added support for array values and options fieldtype if dotsyntax is used (e.g. fieldname.title)
* @since 2.1.4 2020-03-21 fixed bug: mentioned in forum https://processwire.com/talk/topic/8576-name-format-children/?do=findComment&comment=188014
* @since 2.1.5 2024-03-27 fixed bug: attempt to read property "childNameFormat" on null due to page move actions
* @todo disable _pw_page_name field under settings tab if updatePageName is enabled
*
*/
class ProcessSetupPageName extends Process implements Module, ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => __('Setup Page Name'),
'version' => 215,
'summary' => __("Overwrites function setupPageName() in class Pages (core), which is typically called in case of autogeneration of pages. Provides more options for 'Name Format Children' in parent template settings"),
'href' => 'https://processwire.com/talk/topic/8576-name-format-children/?p=108748',
'author' => 'kixe',
'singular' => true,
'autoload' => true,
'requires' => 'PHP>=5.4.0',
);
}
/**
* Data as used by the get/set functions
*
*/
public $data = array();
/**
* Default configuration for module
*
*/
static public function getDefaultData() {
return array(
"updatePageName" => 0
);
}
/**
* Populate the default config data
*
*/
public function __construct() {
foreach(self::getDefaultData() as $key => $value) {
$this->$key = $value;
}
}
/**
* Name for autogenerated page names when fields to generate name aren't populated
*
* @var string
*
*/
protected $untitledPageName = 'untitled';
protected $languageSupport = false;
private static $notes;
/**
* add Hooks to Pages::setupPageName, ProcessTemplate::buildEditForm and InputfieldPageTable::getConfigInputfields
*
*
*/
public function init() {
$this->addHookBefore('Pages::setupPageName', function($event) {
$page = $event->arguments[0];
$event->replace = true;
$options = count($event->arguments)==2?$event->arguments[1]:array();
$name = $this->wire('modules')->get('ProcessSetupPageName')->SetupPageName($page, $options);
$event->return = $name;
});
self::$notes = $this->_('Leave blank to disable. Enter any fieldname, subfield, property or date() function separated by space. Dot syntax allowed. Example: \'parent.title date(Y) myfield\' (without quotes) will auto-generate the name from the title of page parent, the current year and the value of pagefield \'myfield\' [More](https://processwire.com/talk/topic/8576-name-format-children/?p=108748)');
$this->addHookAfter('ProcessTemplate::buildEditForm', function($event) {
$return = $event->return;
$return->children()->get(2)->children()->first()->children()->get('childNameFormat')->set('notes',self::$notes);
$event->return = $return;
});
if ($this->wire('modules')->isInstalled('InputfieldPageTable')) {
$this->addHookAfter('InputfieldPageTable::getConfigInputfields', function($event) {
$return = $event->return;
$return->children()->get('nameFormat')->set('notes',self::$notes);
$event->return = $return;
});
}
if ($this->wire('modules')->isInstalled('LanguageSupportPageNames')||$this->updatePageName) {
if ($this->wire('modules')->isInstalled('LanguageSupportPageNames')) $this->languageSupport = true;
$this->addHookBefore('Pages::saveReady', $this, 'hookSaveReady');
}
}
/**
* create a page name based on 'Name Format Children' in settings of parent page template
*
* @param Page $page
* @param string $format use dot syntax if value has subfields or is an object
* spaces are detected as separator for properties, fields or date() function
* using space inside date() function will cause an error
* @param int $languageID
*
* @return string/ bool If a name was generated it is returned. false in case of error or warning
*/
public function createFromFormat(Page $page, $format, $languageID = null) {
$langID = null;
if ($this->languageSupport) {
if ($languageID == null) $languageID = $this->wire('languages')->getDefault()->id;
$langID = $this->wire('languages')->get($languageID)->isDefault()? null : $languageID;
$userLang = $this->wire('user')->language;
$this->wire('user')->language = $this->wire('languages')->get($languageID);
}
$format = trim($format, " \t\n\r,}{'\"");
if (!$format) return false;
$error = false;
$warning = false;
$pageName = '';
// case 1: multiple fields
if (strpos($format,' ')) {
// space not allowed in name so we can use it as separator
$formats = explode(' ',$format);
foreach ($formats as $_format) {
$_format = trim($_format, " \t\n\r,}{'\"");
if (!strlen($_format)) continue;
$_pageName = $this->createFromFormat($page, $_format, $languageID);
if ($_pageName == false) return false;
$pageName .= '-'.$_pageName;
}
}
// case 2: title default
else if ($format == 'title') {
if ($this->languageSupport && strlen($page->getLanguageValue($languageID, 'title'))) {
$pageName .= '-'.$page->getLanguageValue($languageID, 'title');
}
else $pageName .= '-'.$page->title;
}
// case 3: date()
else if (strpos($format, 'date(') === 0 ) {
// we don't allow spaces inside date()
if (preg_match('/(date\()([^)\s]+)(\))/',$format,$matches)) {
$date = date($matches[2]);
if (!strlen($date)) $error = true; // could this ever happen?
else $pageName .= '-'.$date;
}
else {
$format_error = $this->_("Error: 'Name Format Children' in settings of template '%s'. Unproper use of date() function. Missing closing bracket or unallowed space near: '%s'");
$error = true;
}
}
// case 4: value is array
else if (is_array($page->get($format))) {
$langValue = $page->get($format.$langID);
$value = implode('-', is_array($langValue) && count($langValue)? $langValue : $page->get($format));
$pageName .= '-' . $value;
}
// case 5: string could be determined with $page->get() we take this
else if (strlen($page->get($format))) {
if (wire('fields')->get($format) && wire('fields')->get($format)->type instanceof FieldtypeOptions && $num = $page->get($format)->count) {
if ($num == 1) $value = $page->get($format)->first()->get("value$langID|title$langID|value|title");
else {
$value = implode('-', $page->get($format)->each("value$langID|title$langID|value|title"));
}
}
else $value = $page->get($format);
if (is_int($value) && $page->template->hasField($format) && $this->wire('fields')->get($format)->type instanceof FieldtypeDatetime) {
// we convert timestamp to format corresponding to field settings: dateOutputFormat (language sensitive)
$dateOutputFormat = ($this->languageSupport && !$this->wire('user')->language->isDefault() && $this->wire('fields')->get($format)->{"dateOutputFormat".$languageID})? $this->wire('fields')->get($format)->{"dateOutputFormat".$languageID} : $this->wire('fields')->get($format)->dateOutputFormat;
// aware of LanguageSupport::_('C') translations
if ($this->languageSupport) {
$locale = setlocale(LC_TIME, 0); // get current locale
$this->wire('languages')->setLocale(LC_TIME , $this->wire('user')->language->getLocale());
}
$value = wire('datetime')->formatDate($value, $dateOutputFormat);
if ($this->languageSupport) setlocale(LC_TIME, $locale); // reset locale
}
$pageName .= '-'.$value;
}
// case 6: no value. check if field or subfield exists, set flag for warning or error and return false
else {
if (strpos($format,'.')) $_format = array_filter(explode('.',$format));
else $_format = array($format);
if($page->template->hasField($_format[0])) {
// one or more field values not populated
if (count($_format) == 1) $warning = true;
// field has subfields
else if (count($_format) == 2) {
$field = $this->wire('fields')->get($_format[0]);
$info = $field->type->getSelectorInfo($field);
$subfields = array_keys($info['subfields']);
if (!in_array($_format[1],$subfields)) $error = true;
else $warning = true;
}
// todo check subsubfields for now we allow only subfields
else $error = true;
// prevent to show warning twice
if (strpos($page->name, $this->untitledPageName) !== 0) $warning = false;
}
// field doesn't exist or isn't assigned to page template
else $error = true;
}
// output warning or error only in user language
if ($this->languageSupport == false || $userLang->id == $languageID) {
$format_error = isset($format_error)? $format_error : $this->_("Error: 'Name Format Children' in settings of template '%s'. Unknown property, field or subfield: '%s'");
if ($error === true) $this->error(sprintf($format_error, $page->parent->template->name, $format));
$format_warning = $this->_("SetupPageName expects value in field '%s' to autogenerate Pagename");
if ($warning === true) $this->warning(sprintf($format_warning, $format));
}
if ($this->languageSupport) $this->wire('user')->language = $userLang;
if (!$error && !$warning) return ltrim($pageName,'-');
return false;
}
/**
* Overwrites same function in Core Class Pages
* Auto-assign a page name to this page
*
* Typically this would be used only if page had no name or if it had a temporary untitled name.
*
* Page will be populated with the name given. This method will not populate names to pages that
* already have a name, unless the name is "untitled"
*
* @param Page $page
* @param array $options
* - format: Optionally specify the format to use, or leave blank to auto-determine. Use title if set or datetime string
*
* @return string If a name was generated it is returned. If no name was generated blank is returned.
*
*/
public function ___SetupPageName(Page $page, array $options = array()) {
$defaults = array(
'format' => '',
);
$options = array_merge($defaults, $options);
$format = $options['format'];
if(strlen($page->name)) {
// make sure page starts with "untitled" or "untitled-"
if($page->name != $this->untitledPageName && strpos($page->name, "$this->untitledPageName-") !== 0) {
// page already has a name and it's not a temporary/untitled one
// so we do nothing
return '';
}
// page starts with our untitled name, but is it in the exact format we use?
if($page->name != $this->untitledPageName) {
$parts = explode('-', $page->name);
array_shift($parts); // shift off 'untitled';
$parts = implode('', $parts); // put remaining back together
// if we were left with something other than digits,
// this is not an auto-generated name, so leave as-is
if(!ctype_digit($parts)) return '';
}
}
if(!strlen($format)) $format = $page->parent()->template->childNameFormat;
if(!strlen($format)) {
if(strlen($page->title)) {
// default format is title
$format = 'title';
} else {
// if page has no title, default format is date
$format = 'date(Y-m-d-H-i-s)';
}
}
// childNameFormat is set
if (strlen($format)) {
$pageName = $this->createFromFormat($page,$format);
if ($pageName == false) $pageName = $this->untitledPageName;
}
else if (strlen($page->title)) $pageName = $page->title;
else {
// no name will be assigned
$pageName = '';
}
if($pageName == $this->untitledPageName && strpos($page->name, $this->untitledPageName) === 0) {
// page already has untitled name, and there's no need to re-assign the untitled name
return '';
}
if (strlen($pageName)) {
$pageName = $this->sanitizePageName($pageName);
$page->name = $this->makeUnique($pageName, $page->id, $page->parent->id);
$page->set('_hasAutogenName', true); // for savePageQuery, provides adjustName behavior for new pages
return $page->name;
}
return '';
}
/**
* get assoc array of pages using a specific page name with an optional number appendix (-n)
*
* @param string $pageName
* @param int $parentID for local search, default global search
* @param int $excludeID exclude a specific ID from search
* @param int $parentID for local search, default global search
* @param int $languageID
* @return array (key=id) of Page names in use matching $pageName with integer appendix -n except page with id $pageID
*
*/
protected function getSameNameArray($pageName, $excludeID = 0, $parentID = 0, $languageID = null) {
// Page Name Extended which allows UTF8 Page Names doesn't work properly!
// first letter get cutted away of each item ???
// $pageName = mb_convert_encoding($pageName,'ASCII');
if ($languageID) {
if (!$this->wire('languages')->get($languageID)->id) throw new WireException("Cannot find language with ID $languageID");
else if ($this->wire('languages')->get($languageID)->isDefault()) $languageID = null;
}
$local = ($parentID && is_int($parentID))? " parent_id = $parentID AND":'';
$id = ($excludeID && is_int($excludeID))? " id != $excludeID AND":'';
$sql = "SELECT id,name$languageID FROM pages WHERE$local$id name$languageID REGEXP '^($pageName)(-([[:digit:]]+))?$' COLLATE utf8_general_ci";
try {
$query = $this->wire('database')->prepare($sql);
$this->wire('database')->execute($query, true, 2);
$result = $query->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) {
$this->error($e);
return array();
}
return $result;
}
/**
* create a unique (local or global) name with -n appendix
* index -n will be highest index of similar named pages +1
*
* @param string $pageName
* @param string $pageID
* @param int $parentID (uniquify locally under this parent)
* @param int $languageID
* @return string $pageName-n
*
*/
protected function makeUnique($pageName, $pageID = 0, $parentID = 0, $languageID = null) {
$names = $this->getSameNameArray($pageName, $pageID, $parentID, $languageID);
if (empty($names)) return $pageName;
$indexes = array(1);
foreach ($names as $name) {
$index = trim(strrchr($name,'-'),'-');
if (ctype_digit($index)) $indexes[] = (int) $index;
}
$newindex = max($indexes)+1;
if(strlen($pageName) + strlen($newindex) > Pages::nameMaxLength) $pageName = substr($pageName, 0, Pages::nameMaxLength - strlen($newindex));
return "$pageName-$newindex";
}
/**
* Sanitize page name
* @param string $pagename
* @return string $pagename
*/
public function sanitizePageName($pageName) {
if($this->wire('config')->pageNameCharset === 'UTF8') {
$pageName = $this->wire('sanitizer')->pageNameUTF8($pageName);
} else {
$pageName = $this->wire('sanitizer')->pageName($pageName, Sanitizer::translate);
}
return $pageName;
}
/**
* hook to assign language specific names and/ or update page name
* run only if property updatePageName is set to 1 OR
* values for page name not already set (NULL) AND Inputfield _pw_page_name is cleared/empty
*
*/
public function hookSaveReady($event) {
$page = $event->arguments[0];
if (!$page->parent || $page->parent instanceof NullPage) return;
$format = $page->parent()->template->childNameFormat;
if (!strlen("$format")) return;
$SetupPageName = $this->wire('modules')->get('ProcessSetupPageName');
if ($SetupPageName->languageSupport) {
foreach ($this->wire('languages') as $language) {
if (!$this->data['updatePageName'] && $language->isDefault()) continue;
$languageID = $language->isDefault()? null: $language->id;
$pageLangName = $SetupPageName->updatePageName($page, $format, $languageID);
if (!$pageLangName) continue;
$page->{"name".$languageID} = $pageLangName;
}
} else {
$pageLangName = $SetupPageName->updatePageName($page, $format);
if ($pageLangName) $page->name = $pageLangName;
}
}
/**
* Return an unique page name or false on fail
*
* @param object $page
* @param string $format
* @param int/ string $languageID
* @return bool/ string
*
*/
protected function updatePageName($page, $format, $languageID = null) {
$pageLangName = $this->sanitizePageName($this->wire('input')->post->{"_pw_page_name$languageID"});
if (!$this->updatePageName && strpos($pageLangName, $this->untitledPageName) !== 0) return false;
if (!$this->updatePageName && $page->{"name".$languageID}) return false;
$pageLangName = $this->createFromFormat($page, $format, $languageID);
if (!$pageLangName) return false; // couldn't create a language specific name from format
$pageLangName = $this->sanitizePageName($pageLangName);
$pageLangName = $this->makeUnique($pageLangName, $page->id, $page->parent->id, $languageID);
return $pageLangName;
}
/**
* Return an InputfieldsWrapper of Inputfields used to configure the class
*
* @param array $data Array of config values indexed by field name
* @return InputfieldsWrapper
*
*/
static public function getModuleConfigInputfields(array $data) {
$modules = wire('modules');
$data = array_merge(self::getDefaultData(), $data);
$fields = new InputfieldWrapper();
$f = $modules->get('InputfieldCheckbox');
$f->attr('name', 'updatePageName');
$f->label = __('Update the name of existing pages if the values of the selected fields from which the name is generated have been changed.');
$f->notes = __('Use this option with caution, because it has the potential to break links.');
$f->attr('checked', $data['updatePageName'] ? 'checked' : '' );
$fields->add($f);
return $fields;
}
}