-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathTextformatterHannaCode.module
551 lines (467 loc) · 12.9 KB
/
TextformatterHannaCode.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
<?php namespace ProcessWire;
require_once(__DIR__ . '/HannaCodes.php');
/**
* ProcessWire Hanna Code Textformatter
*
* Based loosely on the WordPress Hana Code Insert module at: http://wordpress.org/plugins/hana-code-insert/
*
* Copyright (C) 2022 by Ryan Cramer
* Licensed under MPL 2.0
* https://processwire.com
*
* @property string $openTag
* @property string $closeTag
* @property string $cachePath
* @property bool|int $noAccessed
* @property Field $field
* @property string $value
* @property string $name
*
*/
class TextformatterHannaCode extends Textformatter implements ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => __('Hanna Code Text Formatter', __FILE__),
'version' => 32,
'summary' => __('Easily insert any complex HTML, Javascript or PHP output in your ProcessWire content by creating your own Hanna code tags.', __FILE__),
'installs' => 'ProcessHannaCode',
'requires' => 'ProcessWire>=3.0.133',
'icon' => 'sun-o',
);
}
/**
* Defaults for configuration
*
*/
const defaultOpenTag = '[[';
const defaultCloseTag = ']]';
/**
* Open tag setting
*
*/
protected $openTag = '';
/**
* Close tag setting
*
*/
protected $closeTag = '';
/**
* Disable tracking of last accessed time?
*
* @var bool
*
*/
protected $noAccessed = true;
/**
* Page object passed to the Textformatter's formatValue() function
*
* @var Page
*
*/
protected $page;
/**
* Field object passed to the Textformatter's formatValue() function
*
* @var Field
*
*/
protected $field;
/**
* $value passed to the Textformatter's formatValue() function
*
* @var string
*
*/
protected $value;
/**
* $name of the current Hanna code
*
* @var string
*
*/
protected $name;
/**
* @var HannaCodes|null
*
*/
protected $hannaCodes = null;
/**
* Initialize defaults
*
*/
public function __construct() {
$this->openTag = self::defaultOpenTag;
$this->closeTag = self::defaultCloseTag;
parent::__construct();
}
/**
* For the ConfigurableModule interface
*
* @param string $key
* @param mixed $value
* @return void
*
*/
public function __set($key, $value) {
// so that Hanna code can modify the original full value
if($key === 'value') {
$this->value = $value;
} else if($key === 'openTag' || $key === 'closeTag' || $key === 'noAccessed') {
// module config properties with dedicated variables
$this->$key = $value;
} else {
parent::set($key, $value);
}
}
/**
* Values that can be retrieved from the $hanna variable passed to all Hanna codes
*
* @param string $key
* @return mixed
*
*/
public function __get($key) {
switch($key) {
case 'field': return $this->field;
case 'value': return $this->value;
case 'name': return $this->name;
case 'openTag': return $this->openTag;
case 'closeTag': return $this->closeTag;
case 'noAccessed': return $this->noAccessed;
}
return parent::__get($key);
}
/**
* Format value when Page/Field not known
*
* @param string $str
*
*/
public function format(&$str) {
$page = new NullPage();
$field = new NullField();
$this->formatValue($page, $field, $str);
}
/**
* For the Textformatter interface
*
* @param Page $page
* @param Field $field
* @param string $value
*
*/
public function formatValue(Page $page, Field $field, &$value) {
$sanitizer = $this->wire()->sanitizer;
$openTag = $this->openTag;
$closeTag = $this->closeTag;
// exit early when possible
if(strpos($value, $openTag) === false) return;
if(strpos($value, $closeTag) === false) return;
$regx = '!' .
'(?:<([a-zA-Z]+)' . // 1=optional HTML open tag
'[^>]*>[\s\r\n]*)?' . // HTML open tag attributes and whitespace, if present
preg_quote($openTag, '!') . // Hanna Code open tag
'(.+?)' . // 2=tag contents
preg_quote($closeTag, '!') .// Hanna Code close tag
'(?:[\s\r\n]*</(\1)>)?' . // 3=optional close HTML tag
'!';
if(!preg_match_all($regx, $value, $matches)) return;
$prevPage = $this->page;
$prevField = $this->field;
$prevValue = $this->value;
$this->page = $page;
$this->field = $field;
$this->value = $value;
// save output formatting state and then ensure it is ON
if($this->page->id) {
$of = $this->page->of();
if(!$of) $this->page->of(true);
} else {
$of = true;
}
foreach($matches[2] as $key => $expression) {
if(strpos($expression, '=')) {
// expression with attrs
$attrs = $this->getAttributes($expression);
if(!isset($attrs['name'])) continue;
} else {
// no attribute expression
$attrs = array('name' => $expression);
}
$name = $sanitizer->name($attrs['name']);
$this->name = $name;
unset($attrs['name']);
$consume = true;
$replacement = $this->getReplacement($name, $attrs, $consume);
if($replacement === false) continue;
$openHTML = $matches[1][$key];
$closeHTML = $matches[3][$key];
if($consume && $openHTML == $closeHTML) {
$this->value = str_replace($matches[0][$key], $replacement, $this->value);
} else {
$this->value = str_replace("$openTag$expression$closeTag", $replacement, $this->value);
}
}
// restore output formatting state
if(!$of) $this->page->of(false);
$value = $this->value;
$this->value = $prevValue;
$this->page = $prevPage;
$this->field = $prevField;
}
/**
* Process $value to render any Hanna tags within it (for API use)
*
* @param string $value
* @param Page|null $page
* @param field|null $field
* @return string
*
*/
public function render($value, Page $page = null, Field $field = null) {
if(is_null($page)) $page = $this->wire()->page;
if(is_null($field)) $field = $this->wire(new Field());
$this->formatValue($page, $field, $value);
return $value;
}
/**
* Find an return an array of all attributes in string $expression
*
* @param string $expression
* @return array
*
*/
protected function getAttributes($expression) {
$attrs = array();
$regx =
'!(?:^|\b)' . // beginning or boundary
'([-_a-z0-9]+)' . // 1. attribute name
'\s*=\s*' . // Equals
'(' . // 2. attribute value, possibly with quotes
'(["\']|")' . // 3. open quote
'.*?' . // attribute value unquoted
'\3' . // close quote
'|' . // OR
'[^\'",\s]*' . // unquoted value...
'),?' . // optional comma, per PW selector style
'!i';
if(!preg_match_all($regx, $expression, $matches)) {
return $attrs;
}
foreach($matches[1] as $key => $name) {
$attrs[$name] = trim($matches[2][$key], "'\"");
}
if(empty($attrs['name'])) {
// allow for optional [[name_here attrs]] expression
// where the 'name' isn't specifically called out as an attribute
// but is the first symbol in the expression
if(preg_match('!^([-_a-z0-9]+)([\s,]|$)!i', $expression, $matches)) {
$attrs['name'] = $matches[1];
}
}
return $attrs;
}
/**
* Given the Hanna code name and attributes, retrieve the replacement
*
* @param string $name
* @param array $attrs
* @param bool $consume Whether it should consume surrounding tags or not
* @return string
*
*/
protected function getReplacement($name, array $attrs, &$consume) {
$h = $this->hannaCodes()->get($name);
if(!$h->id) return '';
$this->hannaCodes()->touch($h);
unset($attrs['name']);
// set default attributes, that haven't already been set by user
$defaultAttrs = $h->attrs;
foreach($defaultAttrs as $key => $value) {
if(!array_key_exists($key, $attrs)) $attrs[$key] = $value;
}
if($h->type & HannaCode::typeJS) {
$value = $this->getJS($h, $attrs);
} else if($h->type & HannaCode::typePHP) {
$value = $this->getPHP($h, $attrs);
} else {
$value = $h->code;
}
// Populate whether or not the surrounding tags should be consumed
$consume = $h->isConsuming();
return $value;
}
/**
* Create the output for a JS-based Hanna code
*
* @param HannaCode $h
* @param array $attrs Attributes to include as variables
* @return string
*
*/
protected function getJS(HannaCode $h, array $attrs) {
$vars = '';
$attr = 'var attr = { ';
// build a series of $js var statements to represent the attribute name=values
foreach($attrs as $key => $value) {
$value = str_replace('"', '\\"', $value);
$attr .= "$key: \"$value\", ";
$vars .= "\nvar $key=attr.$key;";
}
$attr = rtrim($attr, ", ") . " }; ";
$vars = $attr . $vars;
$script = 'script';
if(strpos(ltrim($h->code), "<$script") !== 0) {
// if script tag not already present, add it
$js = "<$script type='text/javascript'>$vars\n$h->code\n</$script>";
} else if(strlen($vars)) {
// script tag is already present
// if we have vars to insert, put them after the opening script, but before the code
preg_match('/\s*(<script[^>]*>)(.*)/si', $h->code, $matches);
$js = $matches[1] . $vars . $matches[2];
} else {
// script tag already present and no vars to insert
$js = $h->code;
}
return $js;
}
/**
* Create the output for a PHP-based Hanna code
*
* @param HannaCode $h
* @param array $attrs Attributes to include as variables
* @return string
* @throws WireException
*
*/
protected function getPHP(HannaCode $h, array $attrs) {
$files = $this->wire()->files;
$cachePath = $this->cachePath(true);
$file = $cachePath . basename($h->name . '.php');
$code = trim($h->code);
$php = '<' . '?php';
$openPHP = $php;
$openPHPNS = "$php namespace ProcessWire;";
$firstLine = 'if(!defined("PROCESSWIRE")) die("no direct access");';
if(strpos($code, 'namespace') && preg_match('/(namespace\s+ProcessWire(?:;|\s*;))/', $code, $matches)) {
$openPHP = $openPHPNS;
$code = str_replace($matches[1], '', $code);
}
if(strpos($code, $openPHP) !== 0 && strpos($code, $php) !== 0) {
// prepend open PHP tag to code if not already present
$code = "$openPHP\n$firstLine\n$code";
} else {
// otherwise insert our $firstLine security check
$code = str_replace($openPHP, "$openPHP\n$firstLine\n", $code);
}
if(is_file($file) && file_get_contents($file) === $code) {
// file already there and same as what's in the DB
} else {
// write new file or overwrite existing
if(!$files->filePutContents($file, $code, LOCK_EX)) {
throw new WireException("Unable to write file: $file");
}
}
/** @var TemplateFile $t */
$t = $this->wire(new TemplateFile($file));
// populate user specified attrs
foreach($attrs as $key => $value) $t->set($key, $value);
// also populate them all into an $attrs array, if preferred
$t->set('attr', $attrs);
// populate API variables
foreach($this->wire('all') as $key => $value) {
if($key != 'page') $t->set($key, $value);
}
// populate $page and $hanna variables that are context specific
// note $page may be different from wire('page')
$t->set('page', $this->page);
$t->set('hanna', $this);
return $t->render();
}
/**
* @return HannaCodes
*
*/
public function hannaCodes() {
if(!$this->hannaCodes) $this->hannaCodes = $this->wire(new HannaCodes());
return $this->hannaCodes;
}
/**
* @param bool $create
* @return string
* @throws WireException
*
*/
public function cachePath($create = false) {
$cachePath = $this->wire()->config->paths->cache . 'HannaCode/';
if($create && !is_dir($cachePath)) {
if(!$this->wire()->files->mkdir($cachePath)) {
throw new WireException("Unable to create cache path: $cachePath");
}
}
return $cachePath;
}
/**
* Install this module
*
*/
public function ___install() {
$this->hannaCodes()->install();
}
/**
* Uninstall this module
*
*/
public function ___uninstall() {
parent::___uninstall();
$this->hannaCodes()->uninstall();
$cachePath = $this->cachePath();
if($cachePath && is_dir($cachePath)) {
$this->message("Removing cache path: $cachePath");
$this->wire()->files->rmdir($cachePath, true);
}
}
/**
* Module configuration screen
*
* @param array $data
* @return InputfieldWrapper
*
*/
public function getModuleConfigInputfields(array $data) {
$modules = $this->wire()->modules;
$inputfields = new InputfieldWrapper();
$this->wire($inputfields);
/** @var InputfieldText $f */
$f = $modules->get('InputfieldText');
$f->attr('name', 'openTag');
$f->attr('value', empty($data['openTag']) ? self::defaultOpenTag : $data['openTag']);
$f->label = $this->_('Open Tag');
$f->columnWidth = 50;
$inputfields->add($f);
/** @var InputfieldText $f */
$f = $modules->get('InputfieldText');
$f->attr('name', 'closeTag');
$f->attr('value', empty($data['closeTag']) ? self::defaultCloseTag : $data['closeTag']);
$f->label = $this->_('Close Tag');
$f->columnWidth = 50;
$inputfields->add($f);
return $inputfields;
}
/**
* @deprecated
*/
const TYPE_HTML = 0;
/**
* @deprecated
*/
const TYPE_JS = 1;
/**
* @deprecated
*/
const TYPE_PHP = 2;
/**
* @deprecated use
*/
const TYPE_NOT_CONSUMING = 4;
}