-
Notifications
You must be signed in to change notification settings - Fork 80
/
Assets.php
487 lines (441 loc) · 17.2 KB
/
Assets.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
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
<?php
/*
You may not change or alter any portion of this comment or credits
of supporting developers from this source code or any supporting source code
which is considered copyrighted (c) material of the original comment or credit authors.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace Xoops\Core;
use Assetic\AssetManager;
use Assetic\FilterManager;
use Assetic\Filter;
use Assetic\Factory\AssetFactory;
use Assetic\Factory\Worker\CacheBustingWorker;
use Assetic\AssetWriter;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
use Xmf\Yaml;
/**
* Provides a standardized asset strategy
*
* @category Assets
* @package Assets
* @author Richard Griffith <[email protected]>
* @copyright 2014-2017 XOOPS Project (http://xoops.org)
* @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
* @version Release: 1.0
* @link http://xoops.org
* @since 2.6.0
*/
class Assets
{
/** @var array */
protected $assetPrefs;
/** @var boolean */
private $debug = false;
/** @var array of default filter strings - may be overridden by prefs */
private $default_filters = array(
'css' => 'cssimport,cssembed,?cssmin',
'js' => '?jsqueeze',
);
/** @var array of output locations in assets directory */
private $default_output = array(
'css' => 'css/*.css',
'js' => 'js/*.js',
);
/** @var array of asset reference definitions - may be overridden by prefs */
private $default_asset_refs = array(
array(
'name' => 'jquery',
'assets' => array('media/jquery/jquery.js'),
'filters' => null,
),
array(
'name' => 'jqueryui',
'assets' => array('media/jquery/ui/jquery-ui.js'),
'filters' => null,
),
array(
'name' => 'jgrowl',
'assets' => array('media/jquery/plugins/jquery.jgrowl.js'),
'filters' => null,
),
array(
'name' => 'fontawesome',
'assets' => array('media/font-awesome/css/font-awesome.min.css'),
'filters' => null,
),
);
/**
* @var array of file assets to copy to assets
*/
private $default_file_assets = array(
array(
'type' => 'fonts',
'path' => 'media/font-awesome/fonts',
'pattern' => '*',
),
);
/** @var AssetManager */
private $assetManager = null;
/** @var string config file with assets prefs */
private $assetsPrefsFilename = 'var/configs/system_assets_prefs.yml';
/** @var string config cache key */
private $assetsPrefsCacheKey = 'system/assets/prefs';
/** @var string string to identify Assetic filters using instanceof */
private $filterInterface = '\Assetic\Filter\FilterInterface';
/**
* __construct
*/
public function __construct()
{
$this->assetManager = new AssetManager();
if (isset($_REQUEST['ASSET_DEBUG'])) {
$this->setDebug();
}
$this->assetPrefs = $this->readAssetsPrefs();
// register any asset references
foreach ($this->default_asset_refs as $ref) {
$this->registerAssetReference($ref['name'], $ref['assets'], $ref['filters']);
}
}
/**
* readAssetsPrefs - read configured asset preferences
*
* @return array of assets preferences
*/
protected function readAssetsPrefs()
{
$xoops = \Xoops::getInstance();
try {
$assetsPrefs = $xoops->cache()->read($this->assetsPrefsCacheKey);
$file = $xoops->path($this->assetsPrefsFilename);
$mtime = filemtime($file);
if ($assetsPrefs===false || !isset($assetsPrefs['mtime']) || !$mtime
|| (isset($assetsPrefs['mtime']) && $assetsPrefs['mtime']<$mtime)) {
if ($mtime) {
$assetsPrefs = Yaml::read($file);
if (!is_array($assetsPrefs)) {
$xoops->logger()->error("Invalid config in system_assets_prefs.yml");
$assetsPrefs = array();
} else {
$assetsPrefs['mtime']=$mtime;
$xoops->cache()->write($this->assetsPrefsCacheKey, $assetsPrefs);
$this->copyBaseFileAssets();
}
} else {
// use defaults to create file
$assetsPrefs = array(
'default_filters' => $this->default_filters,
'default_asset_refs' => $this->default_asset_refs,
'default_file_assets' => $this->default_file_assets,
'mtime' => time(),
);
$this->saveAssetsPrefs($assetsPrefs);
$this->copyBaseFileAssets();
}
}
if (!empty($assetsPrefs['default_filters']) && is_array($assetsPrefs['default_filters'])) {
$this->default_filters = $assetsPrefs['default_filters'];
}
if (!empty($assetsPrefs['default_asset_refs']) && is_array($assetsPrefs['default_asset_refs'])) {
$this->default_asset_refs = $assetsPrefs['default_asset_refs'];
}
if (!empty($assetsPrefs['default_file_assets']) && is_array($assetsPrefs['default_file_assets'])) {
$this->default_file_assets = $assetsPrefs['default_file_assets'];
}
} catch (\Exception $e) {
$xoops->events()->triggerEvent('core.exception', $e);
$assetsPrefs = array();
}
return $assetsPrefs;
}
/**
* saveAssetsPrefs - record array of assets preferences in config file, and
* update cache
*
* @param array $assets_prefs array of asset preferences to save
*
* @return void
*/
protected function saveAssetsPrefs($assets_prefs)
{
if (is_array($assets_prefs)) {
$xoops = \Xoops::getInstance();
try {
Yaml::save($assets_prefs, $xoops->path($this->assetsPrefsFilename));
$xoops->cache()->write($this->assetsPrefsCacheKey, $assets_prefs);
} catch (\Exception $e) {
$xoops->events()->triggerEvent('core.exception', $e);
}
}
}
/**
* getUrlToAssets
*
* Create an asset file from a list of assets
*
* @param string $type type of asset, css or js
* @param array $assets list of source files to process
* @param string|array $filters either a comma separated list of known namsed filters
* or an array of named filters and/or filter object
* @param string $target target path, will default to assets directory
*
* @return string URL to asset file
*/
public function getUrlToAssets($type, $assets, $filters = 'default', $target = null)
{
if (is_scalar($assets)) {
$assets = array($assets); // just a single path name
}
if ($filters==='default') {
if (isset($this->default_filters[$type])) {
$filters = $this->default_filters[$type];
} else {
$filters = '';
}
}
if (!is_array($filters)) {
if (empty($filters)) {
$filters = array();
} else {
$filters = explode(',', str_replace(' ', '', $filters));
}
}
if (isset($this->default_output[$type])) {
$output = $this->default_output[$type];
} else {
$output = '';
}
$xoops = \Xoops::getInstance();
if (isset($target)) {
$target_path = $target;
} else {
$target_path = $xoops->path('assets');
}
try {
$am = $this->assetManager;
$fm = new FilterManager();
foreach ($filters as $filter) {
if (is_object($filter) && $filter instanceof $this->filterInterface) {
$filterArray[] = $filter;
} else {
switch (ltrim($filter, '?')) {
case 'cssembed':
$fm->set('cssembed', new Filter\PhpCssEmbedFilter());
break;
case 'cssmin':
$fm->set('cssmin', new Filter\CssMinFilter());
break;
case 'cssimport':
$fm->set('cssimport', new Filter\CssImportFilter());
break;
case 'cssrewrite':
$fm->set('cssrewrite', new Filter\CssRewriteFilter());
break;
case 'lessphp':
$fm->set('lessphp', new Filter\LessphpFilter());
break;
case 'scssphp':
$fm->set('scssphp', new Filter\ScssphpFilter());
break;
case 'jsmin':
$fm->set('jsmin', new Filter\JSMinFilter());
break;
case 'jsqueeze':
$fm->set('jsqueeze', new Filter\JSqueezeFilter());
break;
default:
throw new \Exception(sprintf('%s filter not implemented.', $filter));
break;
}
}
}
// Factory setup
$factory = new AssetFactory($target_path);
$factory->setAssetManager($am);
$factory->setFilterManager($fm);
$factory->setDefaultOutput($output);
$factory->setDebug($this->debug);
$factory->addWorker(new CacheBustingWorker());
// Prepare the assets writer
$writer = new AssetWriter($target_path);
// Translate asset paths, remove duplicates
$translated_assets = array();
foreach ($assets as $k => $v) {
// translate path if not a reference or absolute path
if (0 == preg_match("/^\\/|^\\\\|^[a-zA-Z]:|^@/", $v)) {
$v = $xoops->path($v);
}
if (!in_array($v, $translated_assets)) {
$translated_assets[] = $v;
}
}
// Create the asset
$asset = $factory->createAsset(
$translated_assets,
$filters
);
$asset_path = $asset->getTargetPath();
if (!is_readable($target_path . $asset_path)) {
$assetKey = 'Asset '.$asset_path;
$xoops->events()->triggerEvent('debug.timer.start', $assetKey);
$oldumask = umask(0002);
$writer->writeAsset($asset);
umask($oldumask);
$xoops->events()->triggerEvent('debug.timer.stop', $assetKey);
}
return $xoops->url('assets/' . $asset_path);
} catch (\Exception $e) {
$xoops->events()->triggerEvent('core.exception', $e);
return null;
}
}
/**
* setDebug enable debug mode, will skip filters prefixed with '?'
*
* @return true
*/
public function setDebug()
{
$this->debug = true;
return true;
}
/**
* Add an asset reference to the asset manager
*
* @param string $name the name of the reference to be added
* @param mixed $assets a string asset path, or an array of asset paths,
* may include wildcard
* @param string|array $filters either a comma separated list of known named filters
* or an array of named filters and/or filter object
*
* @return boolean true if asset registers, false on error
*/
public function registerAssetReference($name, $assets, $filters = null)
{
$xoops = \Xoops::getInstance();
$assetArray = array();
$filterArray = array();
try {
if (is_scalar($assets)) {
$assets = array($assets); // just a single path name
}
foreach ($assets as $a) {
// translate path if not a reference or absolute path
if ((substr_compare($a, '@', 0, 1) != 0)
&& (substr_compare($a, '/', 0, 1) != 0)) {
$a = $xoops->path($a);
}
if (false===strpos($a, '*')) {
$assetArray[] = new FileAsset($a); // single file
} else {
$assetArray[] = new GlobAsset($a); // wild card match
}
}
if (!is_array($filters)) {
if (empty($filters)) {
$filters = array();
} else {
$filters = explode(',', str_replace(' ', '', $filters));
}
}
foreach ($filters as $filter) {
if (is_object($filter) && $filter instanceof $this->filterInterface) {
$filterArray[] = $filter;
} else {
switch (ltrim($filter, '?')) {
case 'cssembed':
$filterArray[] = new Filter\PhpCssEmbedFilter();
break;
case 'cssmin':
$filterArray[] = new Filter\CssMinFilter();
break;
case 'cssimport':
$filterArray[] = new Filter\CssImportFilter();
break;
case 'cssrewrite':
$filterArray[] = new Filter\CssRewriteFilter();
break;
case 'lessphp':
$filterArray[] = new Filter\LessphpFilter();
break;
case 'scssphp':
$filterArray[] = new Filter\ScssphpFilter();
break;
case 'jsmin':
$filterArray[] = new Filter\JSMinFilter();
break;
case 'jsqueeze':
$filterArray[] = new Filter\JSqueezeFilter();
break;
default:
throw new \Exception(sprintf('%s filter not implemented.', $filter));
break;
}
}
}
$collection = new AssetCollection($assetArray, $filterArray);
$this->assetManager->set($name, $collection);
return true;
} catch (\Exception $e) {
$xoops->events()->triggerEvent('core.exception', $e);
return false;
}
}
public function copyBaseFileAssets()
{
foreach ($this->default_file_assets as $fileSpec) {
$this->copyFileAssets($fileSpec['path'], trim($fileSpec['pattern']), $fileSpec['type']);
}
}
/**
* copyFileAssets - copy files to the appropriate asset directory.
*
* Copying is normally only needed for fonts or images when they are referenced by a
* relative url in stylesheet, or are located outside of the web root.
*
* @param string $fromPath path to files to copy
* @param string $pattern glob pattern to match files to be copied
* @param string $output output type (css, fonts, images, js)
*
* @return mixed boolean false if target directory is not writable, otherwise
* integer count of files copied
*/
public function copyFileAssets($fromPath, $pattern, $output)
{
$xoops = \Xoops::getInstance();
$fromPath = $xoops->path($fromPath) . '/';
$toPath = $xoops->path('assets') . '/' . $output . '/';
$from = glob($fromPath . '/' . $pattern);
if (!is_dir($toPath)) {
$oldUmask = umask(0);
mkdir($toPath, 0775, true);
umask($oldUmask);
}
if (is_writable($toPath)) {
$count = 0;
$oldUmask = umask(0002);
foreach ($from as $filepath) {
$xoops->events()->triggerEvent('debug.timer.start', $filepath);
$filename = basename($filepath);
$status=copy($filepath, $toPath.$filename);
if (false===$status) {
$xoops->logger()->warning('Failed to copy asset '.$filename);
} else {
//$xoops->logger()->debug('Copied asset '.$filename);
++$count;
}
$xoops->events()->triggerEvent('debug.timer.stop', $filepath);
}
umask($oldUmask);
return $count;
} else {
$xoops->logger()->warning('Asset directory is not writable. ' . $output);
return false;
}
}
}