/
TextformatterHannaCode.module
534 lines (450 loc) · 13.4 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
<?php
/**
* ProcessWire Hanna Code Textformatter
*
* Based loosely on the WordPress Hana Code Insert module at: http://wordpress.org/plugins/hana-code-insert/
*
* Copyright (C) 2016 by Ryan Cramer
* Licensed under MPL 2.0
* https://processwire.com
*
*/
class TextformatterHannaCode extends Textformatter implements ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => __('Hanna Code Text Formatter', __FILE__),
'version' => 20,
'summary' => __('Easily insert any complex HTML, Javascript or PHP output in your ProcessWire content by creating your own Hanna code tags.', __FILE__),
'installs' => 'ProcessHannaCode',
'icon' => 'sun-o',
);
}
/**
* Hanna code types
*
*/
const TYPE_HTML = 0;
const TYPE_JS = 1;
const TYPE_PHP = 2;
/**
* Flag that indicates Hanna code should not consume surrounding <p> tags
*
*/
const TYPE_NOT_CONSUMING = 4;
/**
* Defaults for configuration
*
*/
const DEFAULT_OPEN_TAG = '[[';
const DEFAULT_CLOSE_TAG = ']]';
/**
* Path where we cache PHP Hanna code files
*
* @var string
*
*/
protected $cachePath = '';
/**
* Open tag setting
*
*/
protected $openTag = '';
/**
* Close tag setting
*
*/
protected $closeTag = '';
/**
* 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;
/**
* Initialize defaults
*
*/
public function __construct() {
$this->openTag = self::DEFAULT_OPEN_TAG;
$this->closeTag = self::DEFAULT_CLOSE_TAG;
$this->cachePath = $this->wire('config')->paths->cache . 'HannaCode/';
}
/**
* 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') {
$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) {
if($key == 'field') return $this->field;
else if($key == 'value') return $this->value;
else if($key == 'name') return $this->name;
else if($key == 'openTag') return $this->openTag;
else if($key == 'closeTag') return $this->closeTag;
return parent::__get($key);
}
/**
* For the Textformatter interface
*
* @param Page $page
* @param Field $field
* @param string $value
*
*/
public function formatValue(Page $page, Field $field, &$value) {
$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
$of = $this->page->of();
if(!$of) $this->page->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 = $this->wire('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 = 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) {
$database = $this->wire('database');
$sql = 'SELECT `id`, `type`, `code` FROM hanna_code WHERE `name`=:name';
$query = $database->prepare($sql);
$query->bindValue(':name', $name, PDO::PARAM_STR);
$query->execute();
if(!$query->rowCount()) return false;
list($id, $type, $code) = $query->fetch(PDO::FETCH_NUM);
$query->closeCursor();
$query = $database->prepare("UPDATE hanna_code SET accessed=:time WHERE id=:id");
$query->bindValue(":time", time());
$query->bindValue(":id", $id);
$query->execute();
unset($attrs['name']);
// set default attributes, that haven't already been set by user
$defaultAttrs = $this->extractDefaultCodeAttrs($code);
foreach($defaultAttrs as $key => $value) {
if(!array_key_exists($key, $attrs)) $attrs[$key] = $value;
}
if($type & self::TYPE_JS) $value = $this->getJS($name, $code, $attrs);
else if($type & self::TYPE_PHP) $value = $this->getPHP($name, $code, $attrs);
else $value = $code;
// Populate whether or not the surrounding tags should be consumed
$consume = !($type & self::TYPE_NOT_CONSUMING);
return $value;
}
/**
* Create the output for a JS-based Hanna code
*
* @param string $name Hanna code name
* @param string $code Code to insert
* @param array $attrs Attributes to include as variables
* @return string
*
*/
protected function getJS($name, $code, array $attrs) {
if($name) {}
$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;
if(strpos(ltrim($code), '<script') !== 0) {
// if script tag not already present, add it
$js = "<scr" . "ipt type='text/javascript'>$vars\n$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', $code, $matches);
$js = $matches[1] . $vars . $matches[2];
} else {
// script tag already present and no vars to insert
$js = $code;
}
return $js;
}
/**
* Create the output for a PHP-based Hanna code
*
* @param string $name Hanna code name
* @param string $code Code to insert
* @param array $attrs Attributes to include as variables
* @return string
* @throws WireException
*
*/
protected function getPHP($name, $code, array $attrs) {
if(!is_dir($this->cachePath)) if(!wireMkdir($this->cachePath)) {
throw new WireException("Unable to create cache path: $this->cachePath");
}
$file = $this->cachePath . $name . '.php';
$code = trim($code);
$openPHP = '<' . '?php';
$firstLine = 'if(!defined("PROCESSWIRE")) die("no direct access");';
if(substr($code, 0, strlen($openPHP)) !== $openPHP) {
// 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(!file_put_contents($file, $code, LOCK_EX)) throw new WireException("Unable to write file: $file");
if($this->wire('config')->chmodFile) chmod($file, octdec($this->wire('config')->chmodFile));
}
$t = 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();
}
/**
* Extract default attributes stored in the code block
*
* Extracts hc_attr\nkey=value\nkey2=value2\nhc_attr to array('key' => $value, 'key2' => 'value2');
* and removes the section from $code
*
* @param string $code
* @return array
*
*/
public function extractDefaultCodeAttrs(&$code) {
$pos = strpos($code, 'hc_attr*/');
if($pos === false) return array();
$attrStr = trim(substr($code, 9, $pos-9));
$code = trim(substr($code, $pos+10));
$lines = explode("\n", $attrStr);
$attrs = array();
foreach($lines as $line) {
$pos = strpos($line, '=');
$name = substr($line, 0, $pos);
$value = substr($line, $pos);
$name = trim($name, "\r\n=");
// filter out API variable names and reserved words
if(empty($name)) continue;
if(!is_null($this->wire($name)) || in_array($name, array('name', 'hanna', 'attr'))) $name = "_$name";
$value = trim($value, "\r\n=\"");
$attrs[$name] = $value;
}
return $attrs;
}
/**
* Install this module
*
*/
public function ___install() {
$sql =
"CREATE TABLE hanna_code (" .
"`id` int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, " .
"`name` varchar(128) NOT NULL, " .
"`type` tinyint NOT NULL DEFAULT 0, " .
"`code` text, " .
"`modified` int unsigned NOT NULL default 0, " .
"`accessed` int unsigned NOT NULL default 0, " .
"UNIQUE `name`(`name`)" .
")";
try {
$this->wire('database')->exec($sql);
} catch(Exception $e) {
$this->error($e->getMessage());
}
}
/**
* Uninstall this module
*
*/
public function ___uninstall() {
parent::___uninstall();
$sql = "DROP TABLE hanna_code";
try {
$this->wire('database')->exec($sql);
} catch(Exception $e) {
$this->error($e->getMessage());
}
if($this->cachePath && is_dir($this->cachePath)) {
$this->message("Removing cache path: $this->cachePath");
wireRmdir($this->cachePath, true);
}
}
/**
* Module configuration screen
*
* @param array $data
* @return InputfieldWrapper
*
*/
public static function getModuleConfigInputfields(array $data) {
$inputfields = new InputfieldWrapper();
/** @var InputfieldText $f */
$f = wire('modules')->get('InputfieldText');
$f->attr('name', 'openTag');
$f->attr('value', empty($data['openTag']) ? self::DEFAULT_OPEN_TAG : $data['openTag']);
$f->label = __('Open Tag');
$f->columnWidth = 50;
$inputfields->add($f);
$f = wire('modules')->get('InputfieldText');
$f->attr('name', 'closeTag');
$f->attr('value', empty($data['closeTag']) ? self::DEFAULT_CLOSE_TAG : $data['closeTag']);
$f->label = __('Close Tag');
$f->columnWidth = 50;
$inputfields->add($f);
return $inputfields;
}
}