-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdminCustomFiles.module
More file actions
541 lines (477 loc) · 16 KB
/
Copy pathAdminCustomFiles.module
File metadata and controls
541 lines (477 loc) · 16 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
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
<?php namespace ProcessWire;
use \DirectoryIterator;
/**
* Admin Custom Files (ProcessWire 3.x)
*
* This module enables you to add custom scripts and files to the admin.
*
* Admin Custom Files
* Copyright (C) 2016|2017 by Martijn Geerts
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
*/
class AdminCustomFiles extends WireData implements Module, ConfigurableModule {
/**
* Return info about this Module
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Admin Custom Files',
'version' => '0.9.62',
'author' => 'Martijn Geerts',
'summary' => 'Add custom scripts & styles to the admin with optional dependencies',
'singular' => true,
'autoload' => "template=admin",
'icon' => 'file-code-o',
'requiresVersions' => array(
'PHP' => array('>=', '5.3.6'),
'ProcessWire' => array('>=', '3.0.62'),
),
);
}
/** @var array */
const fileTypes = array('js' => 'scripts', 'css' => 'styles');
/** @var array */
const configClasses = array("AcfConfigDefault", "AcfConfigLegacy");
/** @var array */
private $index = array();
/** @var array $defaults */
private $defaults = array(
'base' => null,
'folder' => 'AdminCustomFiles',
'processes' => array(),
'theme' => null,
'hash' => null,
'js_config' => null,
'dependencies' => null,
'js_config_class' => 'AcfConfigDefault'
);
/**
* Set defaults
*
*/
public function __construct() {
foreach ($this->defaults as $key => $value) $this->set($key, $value);
if ($this->input->get('upgrade') && $this->page->process === 'ProcessModule') {
$this->___upgrade('unknown', AdminCustomFiles::getModuleInfo()['version']);
}
}
/**
* Set defaults
*
* Load scripts & styles for ProcessModule process
*
*/
public function init() {
/** @var Config */
$config = $this->wire('config');
/** @var WireInput */
$input = $this->wire('input');
/** @var Page */
$page = $this->wire('page');
/** @var string */
$className = $this->className();
/** @var array */
$base = $this->getBase();
if ($page->process === 'ProcessModule' && $input->get('name') === $className) {
require $base['modulePath'] . "AcfConfig.php";
$config->scripts->add($base['moduleUrl'] . $className . '.js');
$config->styles->add($base['moduleUrl'] . $className . '.css');
} else if ($this->js_config) {
require $base['modulePath'] . "AcfConfig.php";
}
}
/**
* API Ready
*
*/
public function ready() {
// Build ACF info array
$this->getBase();
if (isset($this->base['exists']) && $this->base['exists']) {
$this->addHookAfter('ProcessController::execute', $this, 'afterProcessExecute');
$this->addHookAfter('Page::render', $this, 'render');
}
}
/**
* After Page::render
*
* @param HookEvent $event
* @return void
*/
public function render(HookEvent $event) {
if (strpos($event->return, '<!DOCTYPE html>') === false) return;
if (!$event->object->is('admin')) return;
if ($this->wire('config')->ajax) return;
/** @var string */
$markup = $event->return;
// Stylesheets
$search = "<script type='text/javascript' src='";
$stringIndex = strpos($markup, $search);
if ($stringIndex !== false) {
$stylesMarkup = "";
foreach ($this->index['styles'] as $file) $stylesMarkup .= "\n\t<link type='text/css' href='" . $file . "' rel='stylesheet'>";
$stylesMarkup = trim($stylesMarkup);
$markup = substr_replace($markup, $stylesMarkup . "\n\t" . $search, $stringIndex, strlen($search));
}
// Scripts
$search = "</head>";
$stringIndex = strpos($markup, $search);
if ($stringIndex !== false) {
$scriptsMarkup = "";
foreach ($this->index['scripts'] as $file) $scriptsMarkup .= "\n\t<script type='text/javascript' src='" . $file . "'></script>";
$markup = substr_replace($markup, $scriptsMarkup . "\n" . $search, $stringIndex, strlen($search));
}
$event->return = $markup;
}
/**
* After Process::Execute
*
* @param HookEvent $event
* @return void
*/
public function afterProcessExecute(HookEvent $event) {
// @var Process $process The Process instance currently executing
$process = $this->wire('process');
if (!$process instanceof Process) return;
$this->buildIndex($process);
$this->jsConfig($process);
}
/**
* Set config->js
*
* Sets the config->js->AdminCustomFiles
*/
private function jsConfig(Process $process) {
if (!$this->js_config || !$this->js_config_class) return false;
$base = $this->getBase();
$name = $this->js_config_class;
$classname = __NAMESPACE__ . '\\' . $name;
$path = in_array($name, self::configClasses)
? $base['modulePath']
: $base['path'];
require_once $path . $name . ".php";
if (!class_exists($classname)) {
$this->error(sprintf('Class “%s” not found.', $name), true);
return false;
}
$jsConfig = new $classname($this);
$jsConfig->ready();
$jsConfig->setConfigJS();
}
/**
* Get theme name
*
* @return string
*/
public function getThemeName() {
return $this->wire('adminTheme')->className();
}
/**
* Build String
*
* @param string $string Relative from AdminCustomFiles or from site root
* @return mixed Associative array with URL and filetype or boolean false
*/
public function fileInfo($string) {
/** @var Config */
$config = $this->wire('config');
$string = str_replace($config->paths->root, '/', $string);
// Relative
if (!(substr($string, 0, 1) === '/')) {
$path = $this->base['path'] . $string;
} else {
$path = rtrim($config->paths->root, '/') . $string;
}
if (!is_file($path)) return false;
$ext = ltrim(strrchr($path, "."), '.');
if (!$ext) return false;
if (!isset(self::fileTypes[$ext])) return false;
$hash = $this->hash ? '?hash=' . md5_file($path) : '';
$path = '/' . str_replace($config->paths->root, '', $path) . $hash;
$type = self::fileTypes[$ext];
return array(
'url' => $path,
'type' => $type,
);
}
/**
* Build folder index
*
* @param Process $process
* @return array
*/
private function getDependencies(Process $process) {
$files = $this->dependencies;
$array = array("scripts" => array(), "styles" => array());
if (!$files) return $array;
if (is_string($files)) {
$files = json_decode($files, true);
}
if (!is_array($files)) {
$this->error('Unable to get dependencies.', true);
return $array;
}
foreach ($files as $item) {
$raw = false;
if (!$item['process']) {
$raw = $item['file'];
} else if ($process->className() === $item['process']) {
$raw = $item['file'];
}
if (!$raw) continue;
$fileInfo = (array) $this->fileInfo($raw);
$array[$fileInfo['type']][] = $fileInfo['url'];
}
return $array;
}
/**
* Build folder index
*
* @param Process $process
*/
private function buildIndex(Process $process) {
$array = (array) $this->getDependencies($process);
$base = $this->getBase();
$types = self::fileTypes;
$themeString = $base['relative'] . $this->getThemeName();
$processString = $base['relative'] . $process->className();
$directory = new DirectoryIterator($this->base['path']);
foreach ($directory as $fileinfo) {
$ext = strtolower($fileinfo->getExtension());
if (!isset($types[$ext])) continue;
$path = $fileinfo->getPathname();
$fileInfo = $this->fileInfo($path);
$type = $fileInfo['type'];
$url = $fileInfo['url'];
$loadTheme = (boolean) $this->theme && strpos($url, $themeString) !== false;
$loadProcess = strpos($url, $processString) !== false;
// When dependencies has same URL as this one
if (in_array($url, $array[$type])) continue;
if ($loadTheme || $loadProcess) $array[$type][] = $url;
}
$this->index = $array;
}
/**
* Get information about ACF folder
*
* @return array
*/
private function getBase() {
if ($this->base) return $this->base;
/** @var Config */
$config = $this->wire('config');
$base = $config->paths->templates . $this->folder . '/';
$base = preg_replace('#/+#', '/', $base);
$relative = $config->urls->templates;
$this->base = array(
'exists' => is_dir($base),
'path' => $base,
'relative' => substr($base, strpos($base, $relative)),
'clean' => substr($base, strpos($base, $relative) + strlen($relative)),
'modulePath' => $config->paths->get($this->className()),
'moduleUrl' => $config->urls->get($this->className()),
);
return $this->base;
}
/**
* Select
*
* @return Inputfield|null
*/
public function getAcfConfigInputfield() {
/** @var Modules */
$modules = $this->wire('modules');
/** @var DirectoryIterator */
$directory = new DirectoryIterator($this->base['path']);
/** @var array */
$configClasses = self::configClasses;
foreach ($directory as $fileinfo) {
if (strtolower($fileinfo->getExtension()) !== 'php') continue;
$path = $fileinfo->getPathname();
$name = $fileinfo->getBasename('.php');
include_once $path;
$classname = __NAMESPACE__ . '\\' . $name;
$configClasses[] = array(
"disabled" => !class_exists($classname),
"name" => $name,
);
}
$name = 'js_config_class';
$value = $this->get($name);
$f = $modules->get('InputfieldSelect');
$f->set('label', $this->_("Class used for building the config object."));
$f->attr('name', $name);
$f->attr('value', $value);
//$f->set('required', true);
$f->set('columnWidth', 50);
//$f->showIf("js_config='1'");
//$f->requiredIf("js_config='1'");
$f->addOption('', '');
foreach ($configClasses as $mixed) {
$label = is_array($mixed) ? $mixed['name'] : $mixed;
$disabled = is_array($mixed) ? $mixed['disabled'] : false;
$f->addOption($label, $label, array('disabled' => $disabled));
}
return $f;
}
/**
* Install
*
*/
public function ___install() {
$base = $this->getBase();
if (!$base['exists']) {
$created = $this->wire('files')->mkdir($base['path']);
if ($created) $this->message(sprintf($this->_("We created your AdminCustomFiles folder (%s)."), $base['relative']));
if (!$created) $this->warning(sprintf($this->_("We are unable to create the AdminCustomFiles folder (%s)."), $base['relative']));
} else {
$this->message(sprintf($this->_("AdminCustomFiles folder already exists (%s)."), $base['relative']));
}
}
/**
* Uninstall
*/
public function ___uninstall() {
$base = $this->getBase();
if ($base['exists']) $this->message(sprintf($this->_("You may remove the folder %s manually."), $base['relative']));
}
/**
* Upgrade module from one version to another
*
* @param int|string $fromVersion
* @param int|string $toVersion
*/
public function ___upgrade($fromVersion, $toVersion) {
/** @var array */
$base = $this->getBase();
require $base['modulePath'] . "AdminCustomFilesUpgrade.php";
$upgrade = new AdminCustomFilesUpgrade($this);
$upgrade->execute();
}
/**
* Module configuration
*
* Required for ConfigurableModule interface
*
* @param InputfieldWrapper $inputfields
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields) {
$modules = $this->wire('modules')->sort('name');
$base = $this->getBase();
$description =
$this->_("Drop JS or CSS files in the AdminCustomFiles directory starting with with a **process** name.") . "\n" .
$this->_("Then enable file injection by selecting the process under **Activate for process**.");
$name = 'folder';
$value = $this->get($name);
$f = $modules->get('InputfieldText');
$f->set('label', $this->_('AdminCustomFiles'));
$f->set('description', $description);
$f->attr('name', $name);
$f->attr('value', $value);
$f->set('required', true);
if ($base['exists']) {
$f->attr('value', $base['clean']);
$f->set('notes', sprintf($this->_('Folder exists: %s.'), $base['relative']));
} else {
$f->attr('value', $base['clean']);
$f->error($this->_("AdminCustomFiles folder does not exist, please create the folder inside your /site/templates/ folder."));
}
$inputfields->add($f);
$name = 'processes';
$value = $this->get($name);
$f = $modules->get('InputfieldAsmSelect');
$f->set('label', $this->_('Activate for process'));
$f->set('description', $this->_('Inject the files when the filename starts with the currently active process name and the process is selected.'));
foreach ($modules as $module) {
// Only process Modules
if (strpos($module->name, 'Process') !== 0) continue;
$info = $modules->getModuleInfo($module);
$label = isset($info['title']) ? "{$module->name}, ({$info['title']})" : $module->name;
$f->addOption($module->name, $label);
}
$notes = $base['exists'] && !count($value) ? $this->_('Select a process to enable file loading.') : '';
$notes = $base['exists'] && count($value) ? sprintf($this->_("Load files with prefix: %s."), implode(", ", $value)) : $notes;
$f->set('notes', $notes);
$f->attr('name', $name);
$f->attr('value', $value);
$inputfields->add($f);
$description =
$this->_("Dependencies will load before the other injected files.") . "\n" .
$this->_("Dependencies with a selected process will only run on that **Process** module.") . "\n" .
$this->_("Dependencies without a selected process will load on all **Process** modules.");
$name = 'dependencies';
$value = $this->get($name);
$value = is_array($value) ? json_encode($value, true) : $value;
$f = $modules->get('InputfieldText');
$f->set('label', $this->_('Dependencies'));
$f->set('description', $description);
$f->attr('name', $name);
$f->attr('value', $value);
$f->attr('type', 'hidden');
$f->attr('data-headers', json_encode(array(
'select' => $this->_("Process"),
'file' => $this->_("URL (Root relative start with a slash, AdminCustomFiles relative start without a slash)"),
), true));
$f->attr('data-path', $base['relative']);
$f->attr('data-messages', json_encode(array(
'notfound' => $this->_("File not found"),
'invalid' => $this->_("Invalid file"),
'exists' => $this->_("File already exists"),
)));
$inputfields->add($f);
$fs = $modules->get("InputfieldFieldset");
$fs->set('label', $this->_('Javascript Object'));
$fs->set('description', $this->_("You are able to build your own output for the JSON object, see example below."));
$fs->set('notes', $this->_("See: console.log(config.AdminCustomFiles)"));
$f = $modules->get('InputfieldMarkup');
$f->set('label', $this->_('Example'));
$f->set('value', "<pre><code class='description'>" . (file_get_contents($base['modulePath'] . "AcfConfigExample.txt")) . "</code></pre>");
$f->set('collapsed', Inputfield::collapsedYes);
$fs->add($f);
$name = 'js_config';
$value = $this->get($name);
$f = $modules->get('InputfieldCheckbox');
$f->set('skipLabel', Inputfield::skipLabelFor);
$f->set('label', $this->_('Config JS'));
$f->set('label2', $this->_('Additional JSON config data.'));
$f->set('columnWidth', 50);
$f->attr('checked', $value);
$f->attr('name', $name);
$f->attr('value', $value);
$fs->add($f);
$fs->add($this->getAcfConfigInputfield());
$inputfields->add($fs);
$name = 'theme';
$value = $this->get($name);
$f = $modules->get('InputfieldCheckbox');
$f->set('skipLabel', Inputfield::skipLabelFor);
$f->set('label', $this->_('Theme based files'));
$f->set('description', $this->_('Adds files that start with the currently active AdminTheme name.'));
$f->set('label2', $this->_('Include theme based files.'));
$notes = $base['exists'] ? sprintf($this->_('Example: %sAdminThemeRenoYourSuffix.js'), $base['relative']) : '';
$f->set('notes', $notes);
$f->attr('checked', $value);
$f->attr('name', $name);
$f->attr('value', $value);
$f->set('columnWidth', 50);
$inputfields->add($f);
$name = 'hash';
$value = $this->get($name);
$f = $modules->get('InputfieldCheckbox');
$f->set('skipLabel', Inputfield::skipLabelFor);
$f->set('label', $this->_('Cache busting'));
$f->set('description', $this->_('Adds a file hash get variable to files to force a fresh copy from the server.'));
$f->set('label2', $this->_('Enable cache busting.'));
$f->set('notes', $this->_("Uses PHP's md5_file function, thus only changed files are get uncached."));
$f->set('columnWidth', 50);
$f->attr('checked', $value);
$f->attr('name', $name);
$f->attr('value', $value);
$f->set('columnWidth', 50);
$inputfields->add($f);
}
}