-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathMagicPages.module.php
382 lines (343 loc) · 12.7 KB
/
MagicPages.module.php
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
<?php
namespace RockMigrations;
use ProcessWire\Debug;
use ProcessWire\HookEvent;
use ProcessWire\Module;
use ProcessWire\Page;
use ProcessWire\Paths;
use ProcessWire\RockMigrations;
use ProcessWire\WireArray;
use ProcessWire\WireData;
use ReflectionClass;
use function ProcessWire\rockmigrations;
class MagicPages extends WireData implements Module
{
public $readyClasses;
private $filePaths = [];
public static function getModuleInfo()
{
return [
'title' => 'MagicPages',
'version' => '1.0.8',
'summary' => 'Autoload module to support MagicPages',
'autoload' => true,
'singular' => true,
'icon' => 'magic',
'requires' => [
'RockMigrations>=1.6.3',
],
'installs' => [],
];
}
/** special methods */
public function __construct()
{
if ($this->wire->config->useMagicPages === 0) return;
if ($this->wire->config->useMagicPages === false) return;
$this->wire->addHookAfter("ProcessWire::init", $this, "pwInit");
}
public function init()
{
$this->wire->addHookAfter("ProcessPageEdit::buildForm", $this, "addPageAssets");
}
public function ready()
{
$ready = $this->readyClasses ?: []; // prevents error on uninstall
foreach ($ready as $p) $p->ready();
}
protected function pwInit(): void
{
// note: must be wirearray, not pagearray
// pagearray does not allow adding multiple pages with id=0
$this->readyClasses = $this->wire(new WireArray());
$rm = rockmigrations();
// get magic templates from cache
$templates = $rm->cache(
"magic-templates",
function () {
$templates = [];
foreach ($this->wire->templates as $tpl) {
$p = $this->wire->pages->newPage(['template' => $tpl]);
if (!property_exists($p, "isMagicPage")) continue;
if (!$p->isMagicPage) continue;
$templates[] = $tpl->name;
}
return $templates;
},
);
// autoload magic templates
if (!is_array($templates)) $templates = [];
foreach ($templates as $tpl) {
$p = $this->wire->pages->newPage(['template' => $tpl]);
if (!property_exists($p, "isMagicPage") || !$p->isMagicPage) {
// cache is outdated, recreate it
$this->resetCache();
continue;
}
if (method_exists($p, 'init')) $p->init();
if (method_exists($p, 'ready')) $this->readyClasses->add($p);
$this->rockmigrations()->watch($p, method_exists($p, 'migrate'));
// add magic methods
$config = $this->wire->config;
if (!$config->noMagicFieldMethods) $this->addMagicFieldMethods($p);
if (!$config->noMagicMethods) $this->addMagicMethods($p);
}
}
/** regular methods */
/**
* Attach magic field methods
* Makes it possible to access field "foo_bar_baz" as $page->baz()
* This is very useful when creating fields with long prefixed names to
* avoid name collisions. Its primary use was for RockPageBuilder but it
* was moved to MagicPages later as it turned out to be very useful.
*/
public function addMagicFieldMethods(Page $page)
{
if (!$tpl = $page->template) return;
$fields = $tpl->fields;
foreach ($fields as $field) {
$fieldname = $field->name;
$parts = explode("_", $fieldname);
$methodname = array_pop($parts);
// add the dynamic method via hook to the page
$this->wire->addHookMethod(
"Page(template=$tpl)::$methodname",
function ($event) use ($fieldname) {
// show note to indicate that this will be removed some day
$this->log('Magic fieldmethods are deprecated! See baumrock.com/rff ' . Debug::backtrace()[0]['file']);
// get field value of original field
$page = $event->object;
$raw = $event->arguments(0);
if ($raw === 2) {
$event->return = $page->getUnformatted($fieldname);
return;
}
if ($raw) {
$event->return = $page->getFormatted($fieldname);
return;
}
$val = $page->edit($fieldname);
if (is_string($val)) {
/** @var RockFrontend $rf */
$rf = $this->wire->modules->get('RockFrontend');
if ($rf) $val = $rf->html($val);
}
$event->return = $val;
},
// we attach the hook as early as possible
// that means if other hooks kick in later they have priority
// this is to make sure we don't overwrite $page->editable() etc.
['priority' => 0]
);
}
}
/**
* Add magic methods to this page object
* @param Page $magicPage
* @return void
*/
public function addMagicMethods($magicPage)
{
if (method_exists($magicPage, "editForm")) {
$this->wire->addHookAfter("ProcessPageEdit::buildForm", function ($event) use ($magicPage) {
$page = $event->object->getPage();
if ($page->className(true) !== $magicPage->className(true)) return;
$form = $event->return;
$page->editForm($form, $page);
});
}
if (method_exists($magicPage, "editFormContent")) {
$this->wire->addHookAfter("ProcessPageEdit::buildFormContent", function ($event) use ($magicPage) {
$page = $event->object->getPage();
if ($page->className(true) !== $magicPage->className(true)) return;
$form = $event->return;
$page->editFormContent($form, $page);
});
}
if (method_exists($magicPage, "editFormSettings")) {
$this->wire->addHookAfter("ProcessPageEdit::buildFormSettings", function ($event) use ($magicPage) {
$page = $event->object->getPage();
if ($page->className(true) !== $magicPage->className(true)) return;
$form = $event->return;
$page->editFormSettings($form, $page);
});
}
// execute onAdded on saved when id=0
if (method_exists($magicPage, "onAdded")) {
$this->wire->addHookAfter("Pages::added", function ($event) use ($magicPage) {
$page = $event->arguments(0);
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onAdded();
});
}
// field value changed
if (method_exists($magicPage, "onChanged")) {
$this->wire->addHookAfter("Page::changed", function ($event) use ($magicPage) {
$page = $event->object;
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onChanged(
$event->arguments(0), // fieldname
$event->arguments(1), // old value
$event->arguments(2), // new value
);
});
}
// execute onCreate on saveReady when id=0
if (method_exists($magicPage, "onCreate")) {
$this->wire->addHookAfter("Pages::saveReady", function ($event) use ($magicPage) {
$page = $event->arguments(0);
if ($page->id) return;
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onCreate();
});
}
// form processing
if (method_exists($magicPage, "onProcessInput")) {
$this->wire->addHookAfter("InputfieldForm::processInput", function ($event) use ($magicPage) {
if ($event->process != "ProcessPageEdit") return;
$page = $event->process->getPage();
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onProcessInput($event->arguments(0), $event->return);
});
}
// execute onSaved on every save
// this will also fire when id=0
if (method_exists($magicPage, "onSaved")) {
$this->wire->addHookAfter("Pages::saved", function ($event) use ($magicPage) {
$page = $event->arguments(0);
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onSaved();
});
}
// execute onSaveReady on every save
// this will also fire when id=0
if (method_exists($magicPage, "onSaveReady")) {
$this->wire->addHookAfter("Pages::saveReady", function ($event) use ($magicPage) {
$page = $event->arguments(0);
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onSaveReady();
});
}
// execute onTrashed hook
if (method_exists($magicPage, "onTrashed")) {
$this->wire->addHookAfter("Pages::trashed", function ($event) use ($magicPage) {
$page = $event->arguments(0);
if ($page->className(true) !== $magicPage->className(true)) return;
$page->onTrashed();
});
}
/**
* hook pagelist label
* This implementation is different to the core getPageListLabel()!
* When using pageListLabel() you will only modify the label in the regular
* page tree, but labels in the menu or in page reference fields will stay untouched.
*/
if (method_exists($magicPage, "pageListLabel")) {
$this->wire->addHookAfter('ProcessPageListRender::getPageLabel', function (HookEvent $event) use ($magicPage) {
$page = $event->arguments('page');
if ($page->className(true) !== $magicPage->className(true)) return;
$options = $event->arguments(1);
$noTags = $options && is_array($options) && array_key_exists('noTags', $options) && $options['noTags'];
if ($noTags) {
// noTags is active, that means we are in a menu or such
return;
}
// regular pagelist --> modify label
$icon = "";
if ($icon = $page->template->icon) $icon = "<i class='icon fa fa-fw fa-$icon'></i> ";
$event->return = $icon . $page->pageListLabel($noTags);
});
}
/**
* Set page name from callback
* Usage:
* Add this to your MagicPage class:
* public function setPageName() {
* return $this->title . " - " . date("Y");
* }
*/
if (method_exists($magicPage, "setPageName")) {
$this->wire->addHookAfter("Pages::saved(id>0)", function (HookEvent $event) use ($magicPage) {
$page = $event->arguments(0);
if ($page->className(true) !== $magicPage->className(true)) return;
$page->setName($page->setPageName());
$page->save(['noHooks' => true]);
});
$this->wire->addHookAfter("ProcessPageEdit::buildForm", function (HookEvent $event) use ($magicPage) {
$page = $event->process->getPage();
if ($page->className(true) !== $magicPage->className(true)) return;
$form = $event->return;
if ($f = $form->get('_pw_page_name')) {
$f->prependMarkup = "<style>#wrap_{$f->id} input[type=text] { display: none; }</style>";
$f->notes = $this->_("Page name will be set automatically on save.");
}
});
}
}
/**
* Add assets having the same filename as the magic page
*
* FooPage.php would load FooPage.css/.js on page edit screen
*/
public function addPageAssets(HookEvent $event): void
{
$page = $event->process->getPage();
$path = $this->getFilePath($page);
$rm = rockmigrations();
// is the asset stored in /site/classes ?
// then move it to /site/assets because /site/classes is blocked by htaccess
if (strpos($path, $this->wire->config->paths->classes) === 0) {
$cachePath = $this->wire->config->paths->assets . "MagicPages/assets/";
foreach (['css', 'js'] as $ext) {
$file = substr($path, 0, -3) . $ext;
$name = basename($file);
$cache = $cachePath . $name;
// delete file?
if (!is_file($file) and is_file($cache)) {
$this->wire->files->unlink($cache);
}
// create file?
if ($rm->filemtime($file) > $rm->filemtime($cache)) {
$this->wire->files->mkdir($cachePath, true);
$this->wire->files->copy($file, $cache);
}
// add asset to backend
if ($ext == 'css') $rm->addStyles($cache);
elseif ($ext == 'js') $rm->addScripts($cache);
}
}
// now we have an assets from a pageclass inside a module (for example)
else {
foreach (['css', 'js'] as $ext) {
// add asset to backend
$file = substr($path, 0, -3) . $ext;
if ($ext == 'css') $rm->addStyles($file);
elseif ($ext == 'js') $rm->addScripts($file);
}
}
}
/**
* Get filepath of file for given page
*/
public function getFilePath($page): string
{
// try to get filepath from cache
$tpl = (string)$page->template;
if ($tpl and array_key_exists($tpl, $this->filePaths)) {
return $this->filePaths[$tpl];
}
// otherwise get filepath from reflectionclass
$reflector = new ReflectionClass($page);
$filePath = Paths::normalizeSeparators($reflector->getFileName());
if ($tpl) $this->filePaths[$tpl] = $filePath;
return $filePath;
}
public function resetCache(): void
{
$this->wire->cache->delete('magic-templates');
}
public function rockmigrations(): RockMigrations
{
return $this->wire->modules->get('RockMigrations');
}
}