-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextformatterFunkyFunctions.module
539 lines (426 loc) · 15.9 KB
/
TextformatterFunkyFunctions.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
<?php namespace ProcessWire;
/**
* TextformatterFunkyFunctions
*
* @author Steffen Henschel
*
*/
class TextformatterFunkyFunctions extends Textformatter implements ConfigurableModule {
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Funky Functions',
'version' => '1.2.0',
'summary' => 'Textformatter to create custom tags.',
'href' => 'http://www.steffenhenschel.com',
'author' => 'Steffen Henschel'
);
}
/**
* isSingular
*
* Hack: override standard Textformatter method to allow multiple instances
* (e.g. loading as API variable as well as adding to textformatters list on texfields)
*
* @return boolean
*/
public function isSingular() {
return false;
}
/**
* Data as used by the get/set functions
*
*/
protected $data = array();
/**
* getDefaultConfig
*
* define and return default configuration
*
* @return array
*/
static public function getDefaultConfig() {
return array(
'leftBrace' => '[[',
'rightBrace' => ']]',
'functionsFolder' => 'templates/funkys',
'useAccessOffset' => true
);
}
/**
* constructor
*
*/
public function __construct() {
foreach(self::getDefaultConfig() as $key => $value) {
$this->$key = $value;
}
}
/**
* format
*
* Text formatting function as used by the Textformatter interface
*
*/
public function format(&$str) {
if (isset($this->data)) {
// perform a strpos fast check before performing regex check
if (strpos($str, $this->leftBrace) !== false) $this->processTags($str);
}
}
/**
* render
*
* render function which returns the output string
* use in template or whereever
*
* @param string $str any string which is suppoesed to contain a valid funky tag
* @return string output
*/
public function ___render($str) {
$this->format($str);
return $str;
}
protected function processTags(&$str) {
$funkyFunctionTags = [];
preg_match_all("/" . preg_quote($this->leftBrace) . "([a-zA-Z0-9\_\-\.]+)(?:.*)" . preg_quote($this->rightBrace) . "/m", $str, $funkyFunctionTags);
// exit if no match was found
if(!isset($funkyFunctionTags[0][0])) return;
$fullTags = $funkyFunctionTags[0];
$tagNames = $funkyFunctionTags[1];
$page = wire('page');
foreach ($fullTags as $i => $tagContent) {
$tagName = $tagNames[$i];
$tagIsField = $page->hasField($tagName);
$tagRenderScriptFile = $this->getRenderScript($tagName, $tagIsField);
$tagAttributesAndValues = [];
// remove unused tag when no script file was found
if(!$tagRenderScriptFile) {
$str = str_replace($fullTags[$i], '', $str);
continue;
}
// find tag attributes
$tagAttrMatches = [];
preg_match_all("/([a-zA-Z0-9\-\_]+)=(?:([0-9a-zA-Z\-\,\:]+)|((?:\"(?:.*?)\")|(?:\'(?:.*?)\')))/m", $tagContent, $tagAttrMatches);
$attrNames = $tagAttrMatches[1];
$attrSimpleVals = $tagAttrMatches[2];
$attrQuotedVals = $tagAttrMatches[3];
foreach($attrNames as $j => $attrName) {
$attrValue = null;
if($attrSimpleVals[$j]) {
$valueProbe = $attrSimpleVals[$j];
$attrValue = $this->pullAnyValue($page, $attrName, $valueProbe, ['simple' => true]);
} elseif($attrQuotedVals[$j]) {
$valueProbe = $attrQuotedVals[$j];
$attrValue = $this->pullAnyValue($page, $attrName, $valueProbe, ['quoted' => true]);
}
$tagAttributesAndValues[$attrName] = $attrValue;
}
// supply value parameter if funky function is also a field of page
if($tagIsField) $tagAttributesAndValues['value'] = $tagAttributesAndValues[$attrName] ?: $page->$attrName;
// suppy itself for "arguments" key
$tagAttributesAndValues['arguments'] = $tagAttributesAndValues;
$out = "";
$out = $this->renderMarkup($tagRenderScriptFile, $tagAttributesAndValues, false);
$str = str_replace($fullTags[$i], $out, $str);
}
}
/**
* render
*
* hookable render function to allow override for templating engines, etc ...
*
* @return string
*/
public function ___renderMarkup($funkyScriptFile, $data, $override = false) {
if($override === false) {
$out = wire('files')->render($funkyScriptFile, $data);
}
return $out;
}
/**
* getRenderScript
*
* @param string $tagName
* @param boolean $isField
* @return string|null
*/
protected function getRenderScript($tagName, $isField = false) {
$funkyName = $tagName;
$page = wire('page');
$pageTemplateName = $page->template->name;
$sitePath = wire('config')->paths->root . 'site/';
$fieldsPath = $sitePath . 'templates/fields';
$funkyPath = $sitePath . ltrim($this->functionsFolder, '/');
$fieldScriptFile = '';
$funkyScriptFile = '';
if($isField) {
if(is_file($fieldScriptFile = "$fieldsPath/$funkyName/$pageTemplateName.php")) goto findFunkyScript;
if(is_file($fieldScriptFile = "$fieldsPath/$funkyName.$pageTemplateName.php")) goto findFunkyScript;
if(is_file($fieldScriptFile = "$fieldsPath/$pageTemplateName/$funkyName.php")) goto findFunkyScript;
if(is_file($fieldScriptFile = "$fieldsPath/$funkyName.php")) goto findFunkyScript;
$fieldScriptFile = '';
}
findFunkyScript:
if(is_file($funkyScriptFile = "$funkyPath/$funkyName/$pageTemplateName.php")) goto goOn;
if(is_file($funkyScriptFile = "$funkyPath/$funkyName.$pageTemplateName.php")) goto goOn;
if(is_file($funkyScriptFile = "$funkyPath/$pageTemplateName/$funkyName.php")) goto goOn;
if(is_file($funkyScriptFile = "$funkyPath/$funkyName.php")) goto goOn;
$funkyScriptFile = '';
goOn:
if(!$fieldScriptFile && !$funkyScriptFile) {
user_error("No script file was found for \"$funkyName\". Current search folders: \"{$this->functionsFolder}/...\" and \"templates/fields/...\". Funky tag was removed.");
return null;
}
// prefer funky file over field script
return $funkyScriptFile ?: $fieldScriptFile;
}
/**
* filterByIndices
*
* Helper to filter array like objects and arrays by given indices.
* Indices are defined in a comma-separated list. Ranges like "2-8" are possible.
*
* Shall return null on fail
*
* @param mixed $arrayLike an array or WireArrray derived object
* @param string $indices a comma separated list like "1,2,3,6-9"
*
* @return mixed|null
*/
protected function filterByIndices($arrayLike, $indices) {
$arrayCount = 0;
if(gettype($arrayLike) == 'array') {
$arrayCount = count($arrayLike);
} elseif($arrayLike instanceof WireArray) {
$arrayCount = $arrayLike->count;
}
if($arrayCount === 0) {
return null;
}
// prepare indices string, expand given ranges (eg. 4-35)
$indices = explode(',', $indices);
$newIndices = [];
foreach ($indices as $k => $index) {
if(strpos($index, '-') !== false) {
// expand ranges
$range = explode('-', $index);
$from = intval($range[0] === '' ? 1 : $range[0]);
$to = intval($range[1] === '' ? $arrayCount : $range[1]);
$n = $to - $from;
for($i = 0; $i <= $n; $i++) {
$newIndices[] = intval($from + $i);
}
} else {
$newIndices[] = intval($index);
}
}
// remove duplicates
$newIndices = array_unique($newIndices);
// apply "access offset"
// ~> "array=1,2,3" to array=0,1,2
if($this->useAccessOffset) {
foreach($newIndices as $i => $indexVal) {
$newIndices[$i] = --$indexVal;
}
}
$newArray = null;
// return for WireArray derived
if($arrayLike instanceof WireArray) {
$newArray = $arrayLike->makeNew();
} elseif($arrayLike instanceof WireData) {
$newArray = new WireData();
} else {
$newArray = [];
foreach ($newIndices as $key => $index) {
$newArray[] = $arrayLike[$index];
}
return $newArray;
}
// else, return for std array
foreach ($newIndices as $key => $index) {
$newArray->add($arrayLike->eq($index));
}
return $newArray;
}
/**
* filterBySelector
*
* filter by selector
*
* Shall return null on fail
*
* @return null|mixed
*/
protected function filterBySelector($wireDataLike, $selector) {
if($wireDataLike instanceof WireData || $wireDataLike instanceof WireArray) {
$filterResult = null;
try {
// ProcessWire throws a WireException if selector is not proper
$filterResult = $wireDataLike->find($selector);
} catch(WireException $e) {
// filterResult stays null
}
return $filterResult;
} else {
return null;
}
}
/**
* pullAnyValue new
*
*/
// private function pullAnyValue(Page $page, string $keyProbe, string $valProbe, $options = []) {
// // merge helper options
// $defaults = ['quoted' => false, 'simple' => false, 'inner' => false];
// $options = array_merge($defaults, $options);
// // strip quotes
// if($options['quoted'] == true) {
// $probeLen = strlen($probe);
// $probe = substr($probe, 1, $probeLen - 2);
// }
// $fieldExists = $page->hasField($keyProbe);
// }
/**
* pullAnyValue
*
*
*
* @param [type] $page
* @param [type] $fieldName
* @param [type] $probe aka filter/selector/...
* @return void
*/
private function pullAnyValue($page, $keyProbe, $probe, $options = []) {
// merge helper options
$defaults = ['quoted' => false, 'simple' => false, 'inner' => false];
$options = array_merge($defaults, $options);
// strip quotes
if($options['quoted'] == true) {
$probeLen = strlen($probe);
$probe = substr($probe, 1, $probeLen - 2);
}
// * //
// 1 // attribute name is field? attribute value has inner field reference?
$fieldExists = $page->hasField($keyProbe);
$innerFieldReference = $this->getInnerFieldReference($page, $probe);
$valueProbe = null;
// 1.1 // If there is an inner field reference, just return this one. Priority.
if($innerFieldReference !== null) {
return $this->pullAnyValue($page, $innerFieldReference[0], $innerFieldReference[1], ['inner' => true]);
}
// 1.2 // If the attribute name does not correspond to a field, just return the value probe.
if($fieldExists === false) {
return $probe;
}
// else // get field value for further filter trials
$valueProbe = $page->get($keyProbe);
// 2 // probe matches "access-indices pattern" like "1,2,5-7,10,14-" --> filter by indices, return value
$accessIndices = [];
preg_match("/(?:[0-9\-],?)+/", $probe, $accessIndices);
if(isset($accessIndices[0]) && $accessIndices[0] == $probe) {
return $this->filterByIndices($valueProbe, $probe);
}
// 4 // no data? assume probe is selector --> filter by selector, value? return value
$fieldValueBySelector = $this->filterBySelector($valueProbe, $probe);
if($fieldValueBySelector === null) {
// go on, assume probe is an actual value
} else {
return $fieldValueBySelector;
}
// 5 // still no data? return probe as value
return $probe;
}
/**
* getInnerFieldReference
*
* checks if field on page exists defined by 'field:'
* example: "fieldName:selector=criteria"
*
* returns fieldname with the rest of the string as a new probe
*
* @param Page $page
* @param string $attrValStr
* @return array|null on success, return array as [fieldname => probe]
*/
private function getInnerFieldReference($page, $attrValStr) {
$delimiterPos = strpos($attrValStr, ':');
$innerFieldName = substr($attrValStr, 0, $delimiterPos);
if($page->hasField($innerFieldName)) {
$probe = substr($attrValStr, $delimiterPos + 1);
return [$innerFieldName, $probe];
} else {
return null;
}
}
/**
* Module configuration screen
*
*/
public static function getModuleConfigInputfields(array $data) {
$modules = wire('modules');
$defaults = self::getDefaultConfig();
$data = array_merge($defaults, $data);
// this is a container for fields, basically like a fieldset
$form = new InputfieldWrapper();
$field = $modules->get("InputfieldText");
$field->name = "leftBrace";
$field->label = __("Opening brace");
$field->description = __("");
$field->value = $data['leftBrace'];
$field->checked = $data['leftBrace'];
$field->with = 50;
$form->add($field);
$field = $modules->get("InputfieldText");
$field->name = "rightBrace";
$field->label = __("Closing brace");
$field->description = __("");
$field->value = $data['rightBrace'];
$field->checked = $data['rightBrace'];
$field->with = 50;
$form->add($field);
$field = $modules->get("InputfieldText");
$field->name = "functionsFolder";
$field->label = __("Default folder for funky functions");
$field->description = __("");
$field->value = $data['functionsFolder'];
$field->checked = $data['functionsFolder'];
$field->with = 50;
$form->add($field);
$field = $modules->get("InputfieldCheckbox");
$field->name = "useAccessOffset";
$field->label = __("Access Offset");
$field->description = __("When accessing items of field data: If checked, access index starts at 1 instead of 0");
$field->notes = __("default: checked");
$field->value = $data['useAccessOffset'];
$field->checked = $data['useAccessOffset'];
$field->with = 50;
$form->add($field);
return $form;
}
/**
* The following functions are to support the ConfigurableModule interface
* since Textformatter does not originate from WireData
*
*/
public function set($key, $value) {
$this->data[$key] = $value;
return $this;
}
public function get($key) {
$value = Wire::getFuel($key);
if($value) return $value;
return isset($this->data[$key]) ? $this->data[$key] : null;
}
public function __set($key, $value) {
$this->set($key, $value);
}
public function __get($key) {
return $this->get($key);
}
}