/
minify.php
548 lines (453 loc) · 14.7 KB
/
minify.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
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
542
543
544
545
546
547
548
<?php
/**
*------------------------------------------------------------------------------
* @package T3 Framework for Joomla!
*------------------------------------------------------------------------------
* @copyright Copyright (C) 2004-2013 JoomlArt.com. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @authors JoomlArt, JoomlaBamboo, (contribute to this project at github
* & Google group to become co-author)
* @Google group: https://groups.google.com/forum/#!forum/t3fw
* @Link: http://t3-framework.org
*------------------------------------------------------------------------------
*/
// No direct access
defined('_JEXEC') or die();
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
T3::import('core/path');
/**
* T3Minify class provides extended template tools used for T3 framework
*
* @package T3
*/
class T3Minify
{
/**
* Known Valid CSS Extension Types
* @var array
*/
public static $cssexts = array('.css', '.css1', '.css2', '.css3');
/**
* Known valid js extension
* @var array
*/
public static $jsexts = array('.js');
public static $jstools = array(
'jsmin' => 'JSMin',
'closurecompiler' => 'Minify_JS_ClosureCompiler'
);
public static $jstool = 'jsmin';
public static $exclude = '';
public static function prepare($tpl){
//set the compress tool
self::$exclude = $tpl->getParam('minify_exclude', '');
self::$jstool = $tpl->getParam('minify_js_tool', 'jsmin');
if(self::$exclude){
self::$exclude = '@' . preg_replace('@[,]+@', '|', preg_quote(self::$exclude)) . '@';
}
}
/**
* @param $css
* @return string
*/
public static function minifyCss( $css ) {
//T3::import('minify/csscompressor');
$css = preg_replace( '#\s+#', ' ', $css );
$css = preg_replace( '#/\*.*?\*/#s', '', $css );
$css = str_replace( '; ', ';', $css );
$css = str_replace( ': ', ':', $css );
$css = str_replace( ' {', '{', $css );
$css = str_replace( '{ ', '{', $css );
$css = str_replace( ', ', ',', $css );
$css = str_replace( '} ', '}', $css );
$css = str_replace( ';}', '}', $css );
return trim( $css );
}
/**
* @param $js
* @return string
*/
public static function minifyJs( $js ){
T3::import('minify/' . self::$jstool);
return call_user_func_array(array(self::$jstools[self::$jstool], 'minify'), array($js));
}
/**
*
* Check and convert to css real path
* @param string $url url to check
* @return mixed the css file path or false if not exist in server
*/
public static function cssPath($url = '') {
//exclude
if(self::$exclude && preg_match(self::$exclude, $url)){
return false;
}
$url = preg_replace('#[?\#]+.*$#', '', $url);
$base = JURI::base();
$root = JURI::root(true);
$ret = false;
if(substr($url, 0, 2) === '//'){ //check and append if url is omit http
$url = JURI::getInstance()->getScheme() . ':' . $url;
}
//check for css file extensions
foreach ( self::$cssexts as $ext ) {
if (strlen($ext) <= strlen($url) && substr_compare($url, $ext, -strlen($ext), strlen($ext)) === 0) {
$ret = true;
break;
}
}
if($ret){
if (preg_match('/^https?\:/', $url)) { //is full link
if (strpos($url, $base) === false){
// external css
return false;
}
$path = JPath::clean(JPATH_ROOT . '/' . substr($url, strlen($base)));
} else {
$path = JPath::clean(JPATH_ROOT . '/' . ($root && strpos($url, $root) === 0 ? substr($url, strlen($root)) : $url));
}
return is_file($path) ? $path : false;
}
return false;
}
/**
*
* Check and convert to css real path
* @param string $url url to check
* @return mixed the css file path or false if not exist in server
*/
public static function jsPath($url = '') {
//leave any javascript file that have parameter (K2 is an example)
if(preg_match('@[?#]+.*$@', $url)){
return false;
}
//exclude
if(self::$exclude && preg_match(self::$exclude, $url)){
return false;
}
//clean
$url = preg_replace('@[?#]+.*$@', '', $url);
$base = JURI::base();
$root = JURI::root(true);
$ret = false;
if(substr($url, 0, 2) === '//'){ //check and append if url is omit http
$url = JURI::getInstance()->getScheme() . ':' . $url;
}
//check for css file extensions
foreach ( self::$jsexts as $ext ) {
if (strlen($ext) <= strlen($url) && substr_compare($url, $ext, -strlen($ext), strlen($ext)) === 0) {
$ret = true;
break;
}
}
if($ret){
if (preg_match('/^https?\:/', $url)) { //is full link
if (strpos($url, $base) === false){
// external css
return false;
}
$path = JPath::clean(JPATH_ROOT . '/' . substr($url, strlen($base)));
} else {
$path = JPath::clean(JPATH_ROOT . '/' . ($root && strpos($url, $root) === 0 ? substr($url, strlen($root)) : $url));
}
return is_file($path) ? $path : false;
}
return false;
}
/**
* @param string $url url to refine
* @return string the refined url
*/
public static function fixUrl($url = ''){
return ($url[0] === '/' || strpos($url, '://') !== false) ? $url : JURI::base(true) . '/' . $url;
}
/**
* Check if need re-minify the group
*/
public static function checkRebuild ($group, $type, $path) {
$grouptime = $group['grouptime'];
$name = substr(md5($group['groupname']), 0, 5);
$groupname = $type . '-' . $name . '-' . substr($grouptime, -5) . '.' . $type;
$groupfile = $path . '/' . $groupname;
// check need rebuild
$result['filename'] = $groupname;
$result['rebuild'] = false;
if (!is_file($groupfile)) {
$result['rebuild'] = true;
// clean old files
$files = JFolder::files($path, $type . '-' . $name . '-*.' . $type);
foreach ($files as $file) {
JFile::delete($file);
}
}
return $result;
}
/**
* @param $tpl template object
* @return bool optimize success or not
*/
public static function optimizecss($tpl)
{
$outputpath = JPATH_ROOT . '/' . $tpl->getParam('t3-assets', 't3-assets') . '/css';
$outputurl = JURI::root(true) . '/' . $tpl->getParam('t3-assets', 't3-assets') . '/css';
if (!JFile::exists($outputpath)){
JFolder::create($outputpath);
@chmod($outputpath, 0755);
}
if (!is_writeable($outputpath)) {
return false;
}
//prepare config
self::prepare($tpl);
$doc = JFactory::getDocument();
//======================= Group css ================= //
$mediagroup = array();
$cssgroups = array();
$stylesheets = array();
$ielimit = 4095;
$selcounts = 0;
$regex = '/\{.+?\}|,/s'; //selector counter
$csspath = '';
// group css into media
$mediagroup['all'] = array();
$mediagroup['screen'] = array();
foreach ($doc->_styleSheets as $url => $stylesheet) {
$media = !empty($stylesheet['media']) ? $stylesheet['media'] : 'all';
if (empty($mediagroup[$media])) {
$mediagroup[$media] = array();
}
$mediagroup[$media][$url] = $stylesheet;
}
foreach ($mediagroup as $media => $group) {
$stylesheets = array(); // empty - begin a new group
foreach ($group as $url => $stylesheet) {
$url = self::fixUrl($url);
if ((!empty($stylesheet['mime']) && $stylesheet['mime'] == 'text/css' || $stylesheet['type'] == 'text/css') && ($csspath = self::cssPath($url))) {
$stylesheet['path'] = $csspath;
$stylesheet['data'] = file_get_contents($csspath);
$selcount = preg_match_all($regex, $stylesheet['data'], $matched);
if(!$selcount) {
$selcount = 1; //just for sure
}
//if we found an @import rule or reach IE limit css selector count, break into the new group
if (preg_match('#@import\s+.+#', $stylesheet['data']) || $selcounts + $selcount >= $ielimit) {
if(count($stylesheets)){
$cssgroup = array();
$groupname = array();
$grouptime = 0;
foreach ( $stylesheets as $gurl => $gsheet ) {
$cssgroup[$gurl] = $gsheet;
$groupname[] = $gurl;
$ftime = @filemtime($gsheet['path']);
if ($ftime > $grouptime) $grouptime = $ftime;
}
$cssgroup['groupname'] = implode('', $groupname);
$cssgroup['grouptime'] = $grouptime;
$cssgroup['media'] = $media;
$cssgroups[] = $cssgroup;
}
$stylesheets = array($url => $stylesheet); // empty - begin a new group
$selcounts = $selcount;
} else {
$stylesheets[$url] = $stylesheet;
$selcounts += $selcount;
}
} else {
// first get all the stylsheets up to this point, and get them into
// the items array
if(count($stylesheets)){
$cssgroup = array();
$groupname = array();
$grouptime = 0;
foreach ( $stylesheets as $gurl => $gsheet ) {
$cssgroup[$gurl] = $gsheet;
$groupname[] = $gurl;
$ftime = @filemtime($gsheet['path']);
if ($ftime > $grouptime) $grouptime = $ftime;
}
$cssgroup['groupname'] = implode('', $groupname);
$cssgroup['grouptime'] = $grouptime;
$cssgroup['media'] = $media;
$cssgroups[] = $cssgroup;
}
//mark ignore current stylesheet
$cssgroup = array($url => $stylesheet, 'ignore' => true);
$cssgroups[] = $cssgroup;
$stylesheets = array(); // empty - begin a new group
}
}
if(count($stylesheets)){
$cssgroup = array();
$groupname = array();
$grouptime = 0;
foreach ( $stylesheets as $gurl => $gsheet ) {
$cssgroup[$gurl] = $gsheet;
$groupname[] = $gurl;
$ftime = @filemtime($gsheet['path']);
if ($ftime > $grouptime) $grouptime = $ftime;
}
$cssgroup['groupname'] = implode('', $groupname);
$cssgroup['grouptime'] = $grouptime;
$cssgroup['media'] = $media;
$cssgroups[] = $cssgroup;
}
}
//======================= Group css ================= //
$output = array();
foreach ($cssgroups as $cssgroup) {
if(isset($cssgroup['ignore'])){
unset($cssgroup['ignore']);
unset($cssgroup['groupname']);
unset($cssgroup['media']);
foreach ($cssgroup as $furl => $fsheet) {
$output[$furl] = $fsheet;
}
} else {
$rebuildCheck = self::checkRebuild($cssgroup, 'css', $outputpath);
$media = $cssgroup['media'];
unset($cssgroup['groupname']);
unset($cssgroup['grouptime']);
unset($cssgroup['media']);
$groupname = $rebuildCheck['filename'];
if($rebuildCheck['rebuild']){
$groupfile = $outputpath . '/' . $groupname;
$cssdata = array();
foreach ($cssgroup as $furl => $fsheet) {
$cssdata[] = "\n\n/*===============================";
$cssdata[] = $furl;
$cssdata[] = "================================================================================*/";
$cssmin = self::minifyCss($fsheet['data']);
$cssmin = T3Path::updateUrl($cssmin, T3Path::relativePath($outputurl, dirname($furl)));
$cssdata[] = $cssmin;
}
$cssdata = implode("\n", $cssdata);
if (!JFile::write($groupfile, $cssdata)) {
// cannot write file, ignore minify
return false;
}
$grouptime = @filemtime($groupfile);
@chmod($groupfile, 0644);
}
$output[$outputurl . '/' . $groupname] = array(
'mime' => 'text/css',
'media' => $media,
'attribs' => array()
);
}
}
//apply the change make change
$doc->_styleSheets = $output;
}
/**
* Optimize javascript
* @param $tpl
* @return bool
*/
public static function optimizejs($tpl){
$outputpath = JPATH_ROOT . '/' . $tpl->getParam('t3-assets', 't3-assets') . '/js';
$outputurl = JURI::root(true) . '/' . $tpl->getParam('t3-assets', 't3-assets') . '/js';
if (!JFile::exists($outputpath)){
JFolder::create($outputpath);
@chmod($outputpath, 0755);
}
if (!is_writeable($outputpath)) {
return false;
}
//prepare config
self::prepare($tpl);
$doc = JFactory::getDocument();
//======================= Group css ================= //
$jsgroups = array();
$scripts = array();
foreach ($doc->_scripts as $url => $script) {
$url = self::fixUrl($url);
if (((!empty($script['mime']) && $script['mime'] == 'text/javascript') || $script['type'] == 'text/javascript') && !preg_match('/tinymce/', $url) && ($jspath = self::jsPath($url))) {
$script['path'] = $jspath;
$script['data'] = file_get_contents($jspath);
$scripts[$url] = $script;
} else {
// first get all the stylsheets up to this point, and get them into
// the items array
if(count($scripts)){
$jsgroup = array();
$groupname = array();
$grouptime = 0;
foreach ( $scripts as $gurl => $gsheet ) {
$jsgroup[$gurl] = $gsheet;
$groupname[] = $gurl;
$ftime = @filemtime($gsheet['path']);
if ($ftime > $grouptime) $grouptime = $ftime;
}
$jsgroup['groupname'] = implode('', $groupname);
$jsgroup['grouptime'] = $grouptime;
$jsgroups[] = $jsgroup;
}
//mark ignore current script
$jsgroup = array($url => $script, 'ignore' => true);
$jsgroups[] = $jsgroup;
$scripts = array(); // empty - begin a new group
}
}
if(count($scripts)){
$jsgroup = array();
$groupname = array();
$grouptime = 0;
foreach ( $scripts as $gurl => $gsheet ) {
$jsgroup[$gurl] = $gsheet;
$groupname[] = $gurl;
$ftime = @filemtime($gsheet['path']);
if ($ftime > $grouptime) $grouptime = $ftime;
}
$jsgroup['groupname'] = implode('', $groupname);
$jsgroup['grouptime'] = $grouptime;
$jsgroups[] = $jsgroup;
}
//======================= Group js ================= //
$output = array();
foreach ($jsgroups as $jsgroup) {
if(isset($jsgroup['ignore'])){
unset($jsgroup['ignore']);
foreach ($jsgroup as $furl => $fsheet) {
$output[$furl] = $fsheet;
}
} else {
$rebuildCheck = self::checkRebuild($jsgroup, 'js', $outputpath);
unset($jsgroup['groupname']);
unset($jsgroup['grouptime']);
$groupname = $rebuildCheck['filename'];
if($rebuildCheck['rebuild']){
$groupfile = $outputpath . '/' . $groupname;
$jsdata = array();
foreach ($jsgroup as $furl => $fsheet) {
$jsdata[] = "\n\n/*===============================";
$jsdata[] = $furl;
$jsdata[] = "================================================================================*/;";
$jsmin = $fsheet['data'];
//already minify?
if(!preg_match('@.*\.min\.js.*@', $furl)){
$jsmin = self::minifyJs($fsheet['data']);
//$jsmin = T3Path::updateUrl($jsmin, T3Path::relativePath($outputurl, dirname($furl)));
}
$jsdata[] = $jsmin;
}
$jsdata = implode("\n", $jsdata);
if (!JFile::write($groupfile, $jsdata)) {
// cannot write file, ignore optimize
return false;
}
$grouptime = @filemtime($groupfile);
@chmod($groupfile, 0644);
}
$output[$outputurl . '/' . $groupname] = array(
'mime' => 'text/javascript',
'defer' => false,
'async' => false
);
}
}
//apply the change make change
$doc->_scripts = $output;
}
}
?>