-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextformatterEmbedr.module.php
More file actions
369 lines (315 loc) · 10.2 KB
/
Copy pathTextformatterEmbedr.module.php
File metadata and controls
369 lines (315 loc) · 10.2 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
<?php namespace ProcessWire;
require_once(__DIR__ . '/Embedrs.php');
/**
* Embedr Text Formatter
*
* Parses ((name)) tags and replaces them with rendered content blocks
*
* @property string $openTag
* @property string $closeTag
*/
class TextformatterEmbedr extends Textformatter implements ConfigurableModule {
public static function getModuleInfo() {
return [
'title' => 'Embedr Text Formatter',
'version' => '0.3.0',
'summary' => 'Dynamic content blocks embedding - parses ((name)) tags',
'author' => 'Maxim Semenov',
'href' => 'https://smnv.org',
'icon' => 'code',
'requires' => 'ProcessWire>=3.0.0',
];
}
/**
* Default configuration
*/
const defaultOpenTag = '((';
const defaultCloseTag = '))';
/**
* Open tag
*
* @var string
*/
protected $openTag = '';
/**
* Close tag
*
* @var string
*/
protected $closeTag = '';
/**
* Page object
*
* @var Page
*/
protected $page;
/**
* Field object
*
* @var Field
*/
protected $field;
/**
* Current value
*
* @var string
*/
protected $value;
/**
* Embedrs collection
*
* @var Embedrs|null
*/
protected $embedrs = null;
/**
* Whether ProcessEmbedr config has been loaded into this instance
*
* @var bool
*/
protected $configLoaded = false;
/**
* Cached debug mode flag
*
* @var bool
*/
protected $debugMode = false;
/**
* Construct
*/
public function __construct() {
$this->openTag = self::defaultOpenTag;
$this->closeTag = self::defaultCloseTag;
parent::__construct();
}
/**
* Set config property
*
* @param string $key
* @param mixed $value
*/
public function __set($key, $value) {
if($key === 'openTag' || $key === 'closeTag') {
$this->$key = $value;
} else if($key === 'value') {
$this->value = $value;
} else {
parent::set($key, $value);
}
}
/**
* Get config property
*
* @param string $key
* @return mixed
*/
public function __get($key) {
if($key === 'openTag') return $this->openTag;
if($key === 'closeTag') return $this->closeTag;
if($key === 'value') return $this->value;
if($key === 'page') return $this->page;
if($key === 'field') return $this->field;
return parent::__get($key);
}
/**
* Load config from ProcessEmbedr (primary source) once per instance.
* Falls back to own saved values or hard-coded defaults.
*/
protected function loadConfig() {
if($this->configLoaded) return;
try {
$config = $this->wire('modules')->getModuleConfigData('ProcessEmbedr');
if(!empty($config['openTag'])) $this->openTag = $config['openTag'];
if(!empty($config['closeTag'])) $this->closeTag = $config['closeTag'];
$this->debugMode = !empty($config['debugMode']);
} catch(\Exception $e) {
// ProcessEmbedr not available — keep own defaults
}
$this->configLoaded = true;
}
/**
* 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);
}
/**
* Format value
*
* @param Page $page
* @param Field $field
* @param string $value
*/
public function formatValue(Page $page, Field $field, &$value) {
$this->loadConfig();
$openTag = $this->openTag;
$closeTag = $this->closeTag;
if($this->debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::formatValue] Called | Page=%s, User=%s',
$page->id ? $page->path : 'unknown',
$this->wire('user')->name
));
}
if(strpos($value, $openTag) === false) return;
if(strpos($value, $closeTag) === false) return;
// Matches ((name)) with optional surrounding HTML wrapper tag
$regex = '!' .
'(?:<([a-zA-Z]+)[^>]*>[\s\r\n]*)?' .
preg_quote($openTag, '!') .
'([a-z0-9_-]+)' .
preg_quote($closeTag, '!') .
'(?:[\s\r\n]*</(\1)>)?' .
'!i';
if(!preg_match_all($regex, $value, $matches)) return;
if($this->debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::formatValue] Found %d embed(s): %s',
count($matches[2]), implode(', ', $matches[2])
));
}
$prevPage = $this->page;
$prevField = $this->field;
$prevValue = $this->value;
$this->page = $page;
$this->field = $field;
$this->value = $value;
foreach($matches[2] as $key => $name) {
$name = $this->wire('sanitizer')->name($name);
if(!$name) continue;
$replacement = $this->getReplacement($name);
if($replacement === false) continue;
$openHTML = $matches[1][$key];
$closeHTML = $matches[3][$key];
// Strip surrounding <p> wrapper if it exists
if($openHTML && $openHTML === $closeHTML && strtolower($openHTML) === 'p') {
$this->value = str_replace($matches[0][$key], $replacement, $this->value);
} else {
$this->value = str_replace("$openTag$name$closeTag", $replacement, $this->value);
}
}
$value = $this->value;
$this->value = $prevValue;
$this->page = $prevPage;
$this->field = $prevField;
}
/**
* Get replacement for embed name
*
* @param string $name
* @return string|false
*/
protected function getReplacement($name) {
$debugMode = $this->debugMode;
if($debugMode) {
$this->wire('log')->save('embedr-debug',
'[TextformatterEmbedr::getReplacement] Looking for embed: ' . $name
);
}
try {
$embedrs = $this->embedrs();
$embed = $embedrs->get($name);
if(!$embed || !$embed->id) {
if($debugMode) {
$this->wire('log')->save('embedr-debug',
'[TextformatterEmbedr::getReplacement] Embed NOT FOUND: ' . $name
);
}
return "<!-- Embedr: '{$name}' not found -->";
}
if($debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::getReplacement] Embed found | ID=%s, Name=%s, Type=%s',
$embed->id, $embed->name, $embed->type ? $embed->type->name : 'unknown'
));
}
$rendered = $embed->render();
if($debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::getReplacement] Rendered (%d chars): %s...',
strlen($rendered), substr(strip_tags($rendered), 0, 100)
));
}
return $rendered;
} catch(\Exception $e) {
if($debugMode) {
$this->wire('log')->save('embedr-debug',
'[TextformatterEmbedr::getReplacement] EXCEPTION: ' . $e->getMessage()
);
}
return "<!-- Embedr: render error -->";
}
}
/**
* Get Embedrs collection
*
* @return Embedrs
*/
protected function embedrs() {
if($this->embedrs !== null) {
return $this->embedrs;
}
$this->embedrs = $this->wire(new Embedrs());
return $this->embedrs;
}
/**
* Render embed by name (API usage)
*
* @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;
}
/**
* Module configuration
*
* @param array $data
* @return InputfieldWrapper
*/
public static function getModuleConfigInputfields(array $data) {
$inputfields = new InputfieldWrapper();
$modules = wire('modules');
// Tags are now managed exclusively in ProcessEmbedr settings
$f = $modules->get('InputfieldMarkup');
$f->label = 'Tag Configuration';
$f->value = '<p class="uk-text-meta">Opening and closing tags are configured in ' .
'<a href="../ProcessEmbedr/">Embedr module settings</a> and applied here automatically.</p>';
$inputfields->add($f);
// Usage instructions
$f = $modules->get('InputfieldMarkup');
$f->label = 'How to Use';
$f->value = '
<h3>Setup</h3>
<ol>
<li>Go to <strong>Setup → Embedr</strong> to create your embeds</li>
<li>Add this Textformatter to your textarea fields (e.g. body field)</li>
<li>Use embed tags in your content: <code>((embed-name))</code></li>
</ol>
<h3>Example</h3>
<p>In your article body:</p>
<pre>
Text about French wines...
((bordeaux-wines))
More text...
((featured-articles))
</pre>
<h3>Tips</h3>
<ul>
<li>Embed names must be lowercase with letters, numbers, hyphens or underscores</li>
<li>Embeds are reusable - create once, use many times</li>
<li>Edit embeds in Setup → Embedr - all usages update automatically</li>
</ul>
';
$inputfields->add($f);
return $inputfields;
}
}