-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextformatterEmbedr.module.php
More file actions
380 lines (327 loc) · 11.1 KB
/
TextformatterEmbedr.module.php
File metadata and controls
380 lines (327 loc) · 11.1 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
370
371
372
373
374
375
376
377
378
379
380
<?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.2.13',
'summary' => 'Dynamic content blocks embedding - parses ((name)) tags',
'author' => 'Maxim Alex',
'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;
/**
* 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);
}
/**
* 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) {
$openTag = $this->openTag;
$closeTag = $this->closeTag;
// Get debug mode safely without loading Process module
$debugMode = false;
try {
$config = $this->wire('modules')->getModuleConfigData('ProcessEmbedr');
$debugMode = !empty($config['debugMode']);
} catch(\Exception $e) {
// Config not accessible, continue without debug
}
if($debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::formatValue] Called | Page=%s, User=%s',
$page->id ? $page->path : 'unknown',
$this->wire('user')->name
));
}
// Exit early when possible
if(strpos($value, $openTag) === false) return;
if(strpos($value, $closeTag) === false) return;
// Build regex pattern
// Matches: ((name)) with optional surrounding HTML tags
$regex = '!' .
'(?:<([a-zA-Z]+)' . // 1=optional HTML open tag
'[^>]*>[\s\r\n]*)?' . // HTML open tag attributes and whitespace
preg_quote($openTag, '!') . // Embedr open tag ((
'([a-z0-9_-]+)' . // 2=embed name
preg_quote($closeTag, '!') .// Embedr close tag ))
'(?:[\s\r\n]*</(\1)>)?' . // 3=optional close HTML tag
'!i';
if(!preg_match_all($regex, $value, $matches)) return;
if($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;
// Process each match
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];
// Consume surrounding <p> tags if they match
if($openHTML && $openHTML === $closeHTML && strtolower($openHTML) === 'p') {
$this->value = str_replace($matches[0][$key], $replacement, $this->value);
} else {
// Just replace the tag itself
$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) {
// Get debug mode safely without loading Process module
$debugMode = false;
try {
$config = $this->wire('modules')->getModuleConfigData('ProcessEmbedr');
$debugMode = !empty($config['debugMode']);
} catch(\Exception $e) {
// Config not accessible, continue without debug
}
if($debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::getReplacement] Looking for embed: %s',
$name
));
}
try {
$embedrs = $this->embedrs();
$embed = $embedrs->get($name);
if(!$embed || !$embed->id) {
if($debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::getReplacement] Embed NOT FOUND: %s',
$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) {
$renderedPreview = substr(strip_tags($rendered), 0, 100);
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::getReplacement] Rendered (%d chars): %s...',
strlen($rendered),
$renderedPreview
));
}
return $rendered;
} catch(\Exception $e) {
// Log error if debug enabled
if($debugMode) {
$this->wire('log')->save('embedr-debug', sprintf(
'[TextformatterEmbedr::getReplacement] EXCEPTION: %s',
$e->getMessage()
));
}
// Return error comment instead of throwing
return "<!-- Embedr Error: {$e->getMessage()} -->";
}
}
/**
* 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');
// Open tag
$f = $modules->get('InputfieldText');
$f->attr('name', 'openTag');
$f->label = 'Opening Tag';
$f->description = 'Tag that starts an embed';
$f->notes = 'Default: ((';
$f->value = isset($data['openTag']) ? $data['openTag'] : self::defaultOpenTag;
$f->columnWidth = 50;
$inputfields->add($f);
// Close tag
$f = $modules->get('InputfieldText');
$f->attr('name', 'closeTag');
$f->label = 'Closing Tag';
$f->description = 'Tag that ends an embed';
$f->notes = 'Default: ))';
$f->value = isset($data['closeTag']) ? $data['closeTag'] : self::defaultCloseTag;
$f->columnWidth = 50;
$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;
}
}