-
Notifications
You must be signed in to change notification settings - Fork 11
/
Core.php
3702 lines (3362 loc) · 150 KB
/
Core.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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace WebSharks\HtmlCompressor;
/**
* HTML Compressor (core class).
*
* @since 140417 Initial release.
*
* @property-read string $version Read-only access to version string.
* @property-read array $options Read-only access to current options.
* @property-read HookApi $hook_api Read-only access to hook API class.
* @property-read Benchmark $benchmark Read-only access to benchmark class.
*/
class Core // Heart of the HTML Compressor.
{
/********************************************************************************************************/
/*
* Private Properties
*/
/**
* Current product title.
*
* @since 140926 Enhance JS error reporting.
*
* @type string Current product title.
*/
protected $product_title = 'HTML Compressor';
/**
* Current version string.
*
* @since 140418 Version indicates release date.
*
* @type string Dated version string: `YYMMDD`.
*/
protected $version = '150821'; //version//
/**
* An array of class options.
*
* @since 140417 Initial release.
*
* @type array Set dynamically by class constructor.
*/
protected $options = array();
/**
* Hook API class instance.
*
* @since 150321 Adding hook API for plugins.
*
* @type HookApi Hook API class instance.
*/
protected $hook_api; // Class instance.
/**
* Benchmark class instance.
*
* @since 150315 Adding additional benchmarks.
*
* @type Benchmark Filled by various methods.
*/
protected $benchmark; // Class instance.
/**
* Compatible with PHP's `strtotime()` function.
*
* @since 140417 Initial release.
*
* @note This indicates how long cache files can live.
*
* @type string Set dynamically by class constructor.
*/
protected $cache_expiration_time = '14 days';
/**
* Vendor-specific CSS prefixes (regex).
*
* @since 140417 Initial release.
*
* @type string Set dynamically by class constructor.
*/
protected $regex_vendor_css_prefixes = '';
/**
* Default set of CSS exclusions (array).
*
* @since 140417 Initial release.
*
* @type array These are used if no option value is supplied to override them.
*/
protected $default_vendor_css_prefixes = array(
'moz',
'webkit',
'khtml',
'ms',
'o',
);
/**
* CSS exclusions (regex).
*
* @since 140417 Initial release.
*
* @type string Set dynamically by class constructor.
*/
protected $regex_css_exclusions = '';
/**
* Default set of CSS exclusions (array).
*
* @since 140417 Initial release.
*
* @type array These are used if no option value is supplied to override them.
*/
protected $default_css_exclusions = array();
/**
* Built-in CSS exclusions (regex).
*
* @since 140422 Changing the way CSS exclusions operate.
*
* @type string Set dynamically by class constructor.
*/
protected $built_in_regex_css_exclusions = '';
/**
* A set of built-in CSS exclusions (regex patterns).
*
* @since 140422 Changing the way CSS exclusions operate.
*
* @type array These are on at all times; UNLESS options dictate otherwise.
* To disable these built-in CSS exclusions pass the option
* `disable_built_in_css_exclusions` as TRUE.
*
* @note These get converted to a regex pattern by the class constructor.
* Reference {@link $built_in_regex_css_exclusions}.
*/
protected $built_in_regex_css_exclusion_patterns = array(
'\W#post\-[0-9]+\W',
);
/**
* JS exclusions (regex).
*
* @since 140417 Initial release.
*
* @type string Set dynamically by class constructor.
*/
protected $regex_js_exclusions = '';
/**
* Default set of JS exclusions (array).
*
* @since 140417 Initial release.
*
* @type array These are used if no option value is supplied to override them.
*/
protected $default_js_exclusions = array(
'.php?',
);
/**
* Built-in JS exclusions (regex).
*
* @since 140422 Changing the way JS exclusions operate.
*
* @type string Set dynamically by class constructor.
*/
protected $built_in_regex_js_exclusions = '';
/**
* A set of built-in JS exclusions (regex patterns).
*
* @since 140422 Changing the way JS exclusions operate.
*
* @type array These are on at all times; UNLESS options dictate otherwise.
* To disable these built-in JS exclusions pass the option
* `disable_built_in_js_exclusions` as TRUE.
*
* @note These get converted to a regex pattern by the class constructor.
* Reference {@link $built_in_regex_js_exclusions}.
*/
protected $built_in_regex_js_exclusion_patterns = array(
'\.js#.',
'\.google\-analytics\.com\/',
'\Wga\s*\(',
'\W_gaq\.push\s*\(',
);
/**
* Current base HREF value.
*
* @since 140417 Initial release.
*
* @type string Set by various routines that work together.
*/
protected $current_base = '';
/**
* Current CSS `@media` value.
*
* @since 140519 Improving CSS `@media` query support.
*
* @type string Set by various routines that work together.
*/
protected $current_css_media = '';
/**
* Static cache array for this class.
*
* @since 140417 Initial release.
*
* @type array Used by various routines for optimization.
*/
protected static $static = array();
/**
* Data cache for this class instance.
*
* @since 140417 Initial release.
*
* @type array Used by various routines for optimization.
*/
protected $cache = array();
/********************************************************************************************************/
/*
* Constructor (Accepts Options)
*/
/**
* Class Constructor.
*
* Full instructions and all `$options` are listed in the
* [README.md](http://github.com/WebSharks/HTML-Compressor) file.
* See: <http://github.com/WebSharks/HTML-Compressor>
*
* @since 140417 Initial release.
*
* @api Constructor is available for public use.
*
* @param array $options Optional array of instance options.
* Check README.md for a list of all possible option keys.
* See: <http://github.com/websharks/html-compressor>
*/
public function __construct(array $options = array())
{
# Set Options
$this->options = $options; // Config.
# Benchmark and Hook API instances.
$this->benchmark = new Benchmark(); // Instance.
$this->hook_api = new HookApi(); // Instance.
# Product Title; i.e., White-Label HTML Compressor
if (!empty($this->options['product_title']) && is_string($this->options['product_title'])) {
$this->product_title = (string) $this->options['product_title'];
}
# Cache Expiration Time Configuration
if (!empty($this->options['cache_expiration_time']) && is_string($this->options['cache_expiration_time'])) {
$this->cache_expiration_time = (string) $this->options['cache_expiration_time'];
}
# Vendor-Specific CSS Prefixes
if (isset($this->options['vendor_css_prefixes']) && is_array($this->options['vendor_css_prefixes'])) {
$this->regex_vendor_css_prefixes = implode('|', $this->pregQuoteDeep($this->options['vendor_css_prefixes'], '/'));
} else {
$this->regex_vendor_css_prefixes = implode('|', $this->pregQuoteDeep($this->default_vendor_css_prefixes, '/'));
}
# CSS Exclusions (If Applicable)
if (isset($this->options['regex_css_exclusions']) && is_string($this->options['regex_css_exclusions'])) {
$this->regex_css_exclusions = $this->options['regex_css_exclusions'];
} elseif (isset($this->options['css_exclusions']) && is_array($this->options['css_exclusions'])) {
if ($this->options['css_exclusions']) {
$this->regex_css_exclusions = '/'.implode('|', $this->pregQuoteDeep($this->options['css_exclusions'], '/')).'/i';
}
} elseif ($this->default_css_exclusions) {
$this->regex_css_exclusions = '/'.implode('|', $this->pregQuoteDeep($this->default_css_exclusions, '/')).'/i';
}
if ($this->built_in_regex_css_exclusion_patterns && empty($this->options['disable_built_in_css_exclusions'])) {
$this->built_in_regex_css_exclusions = '/'.implode('|', $this->built_in_regex_css_exclusion_patterns).'/i';
}
# JavaScript Exclusions (If Applicable)
if (isset($this->options['regex_js_exclusions']) && is_string($this->options['regex_js_exclusions'])) {
$this->regex_js_exclusions = $this->options['regex_js_exclusions'];
} elseif (isset($this->options['js_exclusions']) && is_array($this->options['js_exclusions'])) {
if ($this->options['js_exclusions']) {
$this->regex_js_exclusions = '/'.implode('|', $this->pregQuoteDeep($this->options['js_exclusions'], '/')).'/i';
}
} elseif ($this->default_js_exclusions) {
$this->regex_js_exclusions = '/'.implode('|', $this->pregQuoteDeep($this->default_js_exclusions, '/')).'/i';
}
if ($this->built_in_regex_js_exclusion_patterns && empty($this->options['disable_built_in_js_exclusions'])) {
$this->built_in_regex_js_exclusions = '/'.implode('|', $this->built_in_regex_js_exclusion_patterns).'/i';
}
}
/********************************************************************************************************/
/*
* Public API Methods
*/
/**
* Handles compression. The heart of this class.
*
* Full instructions and all `$options` are listed in the
* [README.md](http://github.com/WebSharks/HTML-Compressor) file.
* See: <http://github.com/WebSharks/HTML-Compressor>
*
* @since 140417 Initial release.
*
* @api This method is available for public use.
*
* @param string $input The input passed into this routine.
*
* @return string Compressed HTML code (if at all possible). Note that `$input` must be HTML code.
* i.e. It must contain a closing `</html>` tag; otherwise no compression will occur.
*/
public function compress($input)
{
if (!($input = trim((string) $input))) {
return $input; // Nothing to do.
}
if (stripos($input, '</html>') === false) {
return $input; // Not an HTML doc.
}
if (($benchmark = !empty($this->options['benchmark']))) {
$time = microtime(true);
}
$html = &$input; // Let's call this HTML now.
$html = $this->maybeCompressCombineHeadBodyCss($html);
$html = $this->maybeCompressCombineHeadJs($html);
$html = $this->maybeCompressCombineFooterJs($html);
$html = $this->maybeCompressInlineJsCode($html);
$html = $this->maybeCompressInlineJsonCode($html);
$html = $this->maybeCompressHtmlCode($html);
if (!isset($this->options['cleanup_cache_dirs']) || $this->options['cleanup_cache_dirs']) {
if (mt_rand(1, 20) === 1) {
$this->cleanupCacheDirs();
}
}
if ($benchmark && !empty($time)) {
$time = number_format(microtime(true) - $time, 5, '.', '');
if ($this->benchmark->times) {
$html .= "\n";
}
foreach ($this->benchmark->times as $_benchmark_time) {
$html .= "\n".'<!-- '.sprintf(
'%1$s took %2$s seconds %3$s.',
htmlspecialchars($this->product_title),
htmlspecialchars($_benchmark_time['time']),
htmlspecialchars($_benchmark_time['task'])
).' -->';
}
unset($_benchmark_time); // Housekeeping.
$html .= "\n\n".'<!-- '.sprintf(
'%1$s took %2$s seconds (overall).',
htmlspecialchars($this->product_title),
htmlspecialchars($time)
).' -->';
}
return $html; // HTML markup.
}
/********************************************************************************************************/
/*
* Other API/Magic Methods
*/
/**
* Magic method for access to read-only properties.
*
* @since 140418 Initial release.
*
* @param string $property Propery by name.
*
* @throws \Exception If `$property` does not exist for any reason.
*
* @return mixed Property value.
*
* @internal For internal magic use only.
*/
public function __get($property)
{
$property = (string) $property;
if (property_exists($this, $property)) {
return $this->{$property};
}
throw new \Exception(sprintf('Undefined property: `%1$s`.', $property));
}
/********************************************************************************************************/
/*
* CSS-Related Methods
* ~ See also: CSS Compression Utilities
*/
/**
* Handles possible compression of head/body CSS.
*
* @since 140417 Initial release.
*
* @param string $html Input HTML code.
*
* @return string HTML code, after possible CSS compression.
*/
protected function maybeCompressCombineHeadBodyCss($html)
{
if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) {
$time = microtime(true);
}
$html = (string) $html; // Force string value.
if (isset($this->options['compress_combine_head_body_css'])) {
if (!$this->options['compress_combine_head_body_css']) {
$disabled = true; // Disabled flag.
}
}
if (!$html || !empty($disabled)) {
goto finale; // Nothing to do.
}
if (($html_frag = $this->getHtmlFrag($html)) && ($head_frag = $this->getHeadFrag($html))) {
if (($css_tag_frags = $this->getCssTagFrags($html_frag)) && ($css_parts = $this->compileCssTagFragsIntoParts($css_tag_frags, 'head'))) {
$css_tag_frags_all_compiled = $this->compileKeyElementsDeep($css_tag_frags, 'all');
$html = $this->replaceOnce($head_frag['all'], '%%htmlc-head%%', $html);
$html = $this->replaceOnce($css_tag_frags_all_compiled, '', $html);
$cleaned_head_contents = $this->replaceOnce($css_tag_frags_all_compiled, '', $head_frag['contents']);
$cleaned_head_contents = $this->cleanupSelfClosingHtmlTagLines($cleaned_head_contents);
$compressed_css_tags = array(); // Initialize.
foreach ($css_parts as $_css_part) {
if (isset($_css_part['exclude_frag'], $css_tag_frags[$_css_part['exclude_frag']]['all'])) {
$compressed_css_tags[] = $css_tag_frags[$_css_part['exclude_frag']]['all'];
} else {
$compressed_css_tags[] = $_css_part['tag'];
}
}
unset($_css_part); // Housekeeping.
$compressed_css_tags = implode("\n", $compressed_css_tags);
$compressed_head_parts = array($head_frag['open_tag'], $cleaned_head_contents, $compressed_css_tags, $head_frag['closing_tag']);
$html = $this->replaceOnce('%%htmlc-head%%', implode("\n", $compressed_head_parts), $html);
if ($benchmark) {
$this->benchmark->addData(
__FUNCTION__,
compact(
'head_frag',
'css_tag_frags',
'css_parts',
'cleaned_head_contents',
'compressed_css_tags',
'compressed_head_parts'
)
);
}
}
}
finale: // Target point; finale/return value.
if ($html) {
$html = trim($html);
} // Trim it up now!
if ($benchmark && !empty($time) && $html && empty($disabled)) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compressing/combining head/body CSS in checksum: `%1$s`', md5($html))
);
}
return $html; // With possible compression having been applied here.
}
/**
* Compiles CSS tag fragments into CSS parts with compression.
*
* @since 140417 Initial release.
*
* @param array $css_tag_frags CSS tag fragments.
* @param string $for Where will these parts go? One of `head`, `body`, `foot`.
*
* @throws \Exception If unable to cache CSS parts.
*
* @return array Array of CSS parts, else an empty array on failure.
*/
protected function compileCssTagFragsIntoParts(array $css_tag_frags, $for)
{
if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) {
$time = microtime(true);
}
$for = (string) $for; // Force string.
$css_parts = array(); // Initialize.
$css_parts_checksum = ''; // Initialize.
if (!$css_tag_frags) {
goto finale; // Nothing to do.
}
$css_parts_checksum = $this->getTagFragsChecksum($css_tag_frags);
$public_cache_dir = $this->cacheDir($this::DIR_PUBLIC_TYPE, $css_parts_checksum);
$private_cache_dir = $this->cacheDir($this::DIR_PRIVATE_TYPE, $css_parts_checksum);
$public_cache_dir_url = $this->cacheDirUrl($this::DIR_PUBLIC_TYPE, $css_parts_checksum);
$cache_parts_file = $css_parts_checksum.'-compressor-parts.css-cache';
$cache_parts_file_path = $private_cache_dir.'/'.$cache_parts_file;
$cache_parts_file_path_tmp = $cache_parts_file_path.'.'.uniqid('', true).'.tmp';
// Cache file creation is atomic; i.e. tmp file w/ rename.
$cache_part_file = '%%code-checksum%%-compressor-part.css';
$cache_part_file_path = $public_cache_dir.'/'.$cache_part_file;
$cache_part_file_url = $public_cache_dir_url.'/'.$cache_part_file;
if (is_file($cache_parts_file_path) && filemtime($cache_parts_file_path) > strtotime('-'.$this->cache_expiration_time)) {
if (is_array($cached_parts = unserialize(file_get_contents($cache_parts_file_path)))) {
$css_parts = $cached_parts; // Use cached parts.
goto finale; // Using the cache; all done here.
}
}
$_css_part = 0; // Initialize part counter.
$_last_css_tag_frag_media = 'all'; // Initialize.
foreach ($css_tag_frags as $_css_tag_frag_pos => $_css_tag_frag) {
if ($_css_tag_frag['exclude']) {
if ($_css_tag_frag['link_href'] || $_css_tag_frag['style_css']) {
if ($css_parts) {
++$_css_part; // Starts new part.
}
$css_parts[$_css_part]['tag'] = '';
$css_parts[$_css_part]['exclude_frag'] = $_css_tag_frag_pos;
++$_css_part; // Always indicates a new part in the next iteration.
}
} elseif ($_css_tag_frag['link_href']) {
if (($_css_tag_frag['link_href'] = $this->resolveRelativeUrl($_css_tag_frag['link_href']))) {
if (($_css_code = $this->stripUtf8Bom($this->remote($_css_tag_frag['link_href'])))) {
$_css_code = $this->resolveCssRelatives($_css_code, $_css_tag_frag['link_href']);
$_css_code = $this->resolveResolvedCssImports($_css_code, $_css_tag_frag['media']);
if ($_css_code) {
if ($_css_tag_frag['media'] !== $_last_css_tag_frag_media) {
++$_css_part; // Starts new part; different `@media` spec here.
} elseif (!empty($css_parts[$_css_part]['code']) && stripos($css_parts[$_css_part]['code'], '@import') !== false) {
++$_css_part; // Starts new part; existing code contains an @import.
}
$css_parts[$_css_part]['media'] = $_css_tag_frag['media'];
if (!empty($css_parts[$_css_part]['code'])) {
$css_parts[$_css_part]['code'] .= "\n\n".$_css_code;
} else {
$css_parts[$_css_part]['code'] = $_css_code;
}
}
}
}
} elseif ($_css_tag_frag['style_css']) {
$_css_code = $_css_tag_frag['style_css'];
$_css_code = $this->stripUtf8Bom($_css_code);
$_css_code = $this->resolveCssRelatives($_css_code);
$_css_code = $this->resolveResolvedCssImports($_css_code, $_css_tag_frag['media']);
if ($_css_code) {
if ($_css_tag_frag['media'] !== $_last_css_tag_frag_media) {
++$_css_part; // Starts new part; different `@media` spec here.
} elseif (!empty($css_parts[$_css_part]['code']) && stripos($css_parts[$_css_part]['code'], '@import') !== false) {
++$_css_part; // Starts new part; existing code contains an @import.
}
$css_parts[$_css_part]['media'] = $_css_tag_frag['media'];
if (!empty($css_parts[$_css_part]['code'])) {
$css_parts[$_css_part]['code'] .= "\n\n".$_css_code;
} else {
$css_parts[$_css_part]['code'] = $_css_code;
}
}
}
$_last_css_tag_frag_media = $_css_tag_frag['media'];
}
unset($_css_part, $_last_css_tag_frag_media, $_css_tag_frag_pos, $_css_tag_frag, $_css_code);
foreach (array_keys($css_parts = array_values($css_parts)) as $_css_part) {
if (!isset($css_parts[$_css_part]['exclude_frag']) && !empty($css_parts[$_css_part]['code'])) {
$_css_media = 'all'; // Default media value; i.e., `all` media queries.
if (!empty($css_parts[$_css_part]['media'])) {
$_css_media = $css_parts[$_css_part]['media'];
}
$_css_code = $css_parts[$_css_part]['code'];
$_css_code = $this->moveSpecialCssAtRulesToTop($_css_code);
$_css_code = $this->stripPrependCssCharsetUtf8($_css_code);
$_css_code = $this->forceAbsRelativePathsInCss($_css_code);
$_css_code_cs = md5($_css_code); // Before compression.
$_css_code = $this->maybeCompressCssCode($_css_code);
$_css_code_path = str_replace('%%code-checksum%%', $_css_code_cs, $cache_part_file_path);
$_css_code_url = str_replace('%%code-checksum%%', $_css_code_cs, $cache_part_file_url);
$_css_code_url = $this->hook_api->applyFilters('part_url', $_css_code_url, $for);
$_css_code_path_tmp = $_css_code_path.'.'.uniqid('', true).'.tmp';
// Cache file creation is atomic; i.e. tmp file w/ rename.
if (!(file_put_contents($_css_code_path_tmp, $_css_code) && rename($_css_code_path_tmp, $_css_code_path))) {
throw new \Exception(sprintf('Unable to cache CSS code file: `%1$s`.', $_css_code_path));
}
$css_parts[$_css_part]['tag'] = '<link type="text/css" rel="stylesheet" href="'.htmlspecialchars($_css_code_url, ENT_QUOTES).'" media="'.htmlspecialchars($_css_media, ENT_QUOTES).'" />';
unset($css_parts[$_css_part]['code']); // Ditch this; no need to cache this code too.
}
}
unset($_css_part, $_css_media, $_css_code, $_css_code_cs, $_css_code_path, $_css_code_path_tmp, $_css_code_url);
if (!(file_put_contents($cache_parts_file_path_tmp, serialize($css_parts)) && rename($cache_parts_file_path_tmp, $cache_parts_file_path))) {
throw new \Exception(sprintf('Unable to cache CSS parts into: `%1$s`.', $cache_parts_file_path));
}
finale: // Target point; finale/return value.
if ($benchmark && !empty($time) && $css_parts_checksum) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('building parts based on CSS tag frags in checksum: `%1$s`', $css_parts_checksum)
);
}
return $css_parts;
}
/**
* Parses and returns an array of CSS tag fragments.
*
* @since 140417 Initial release.
*
* @param array $html_frag An HTML tag fragment array.
*
* @return array An array of CSS tag fragments (ready to be converted into CSS parts).
* Else an empty array (i.e. no CSS tag fragments in the HTML fragment array).
*
* @see http://css-tricks.com/how-to-create-an-ie-only-stylesheet/
* @see http://stackoverflow.com/a/12102131
*/
protected function getCssTagFrags(array $html_frag)
{
if (($benchmark = !empty($this->options['benchmark']) && $this->options['benchmark'] === 'details')) {
$time = microtime(true);
}
$css_tag_frags = array(); // Initialize.
if (!$html_frag) {
goto finale; // Nothing to do.
}
$regex = '/(?P<all>'.// Entire match.
'(?P<if_open_tag>\<\![^[>]*?\[if\W[^\]]*?\][^>]*?\>\s*)?'.
'(?:(?P<link_self_closing_tag>\<link(?:\s+[^>]*?)?\>)'.// Or a <style></style> tag.
'|(?P<style_open_tag>\<style(?:\s+[^>]*?)?\>)(?P<style_css>.*?)(?P<style_closing_tag>\<\/style\>))'.
'(?P<if_closing_tag>\s*\<\![^[>]*?\[endif\][^>]*?\>)?'.
')/is'; // Dot matches line breaks.
if (!empty($html_frag['contents']) && preg_match_all($regex, $html_frag['contents'], $_tag_frags, PREG_SET_ORDER)) {
foreach ($_tag_frags as $_tag_frag) {
$_link_href = $_style_css = $_media = ''; // Initialize.
if (($_link_href = $this->getLinkCssHref($_tag_frag, true))) {
$_media = $this->getLinkCssMedia($_tag_frag, false);
} elseif (($_style_css = $this->getStyleCss($_tag_frag, true))) {
$_media = $this->getStyleCssMedia($_tag_frag, false);
}
if ($_link_href || $_style_css) {
$css_tag_frags[] = array(
'all' => $_tag_frag['all'],
'if_open_tag' => isset($_tag_frag['if_open_tag']) ? $_tag_frag['if_open_tag'] : '',
'if_closing_tag' => isset($_tag_frag['if_closing_tag']) ? $_tag_frag['if_closing_tag'] : '',
'link_self_closing_tag' => isset($_tag_frag['link_self_closing_tag']) ? $_tag_frag['link_self_closing_tag'] : '',
'link_href_external' => ($_link_href) ? $this->isUrlExternal($_link_href) : false,
'link_href' => $_link_href, // This could also be empty.
'style_open_tag' => isset($_tag_frag['style_open_tag']) ? $_tag_frag['style_open_tag'] : '',
'style_css' => $_style_css, // This could also be empty.
'style_closing_tag' => isset($_tag_frag['style_closing_tag']) ? $_tag_frag['style_closing_tag'] : '',
'media' => $_media ? $_media : 'all', // Default value.
'exclude' => false, // Default value.
);
$_tag_frag_r = &$css_tag_frags[count($css_tag_frags) - 1];
if ($_tag_frag_r['if_open_tag'] || $_tag_frag_r['if_closing_tag']) {
$_tag_frag_r['exclude'] = true;
} elseif ($_tag_frag_r['link_href'] && $_tag_frag_r['link_href_external'] && isset($this->options['compress_combine_remote_css_js']) && !$this->options['compress_combine_remote_css_js']) {
$_tag_frag_r['exclude'] = true;
} elseif ($this->regex_css_exclusions && preg_match($this->regex_css_exclusions, $_tag_frag_r['link_href'].$_tag_frag_r['style_css'])) {
$_tag_frag_r['exclude'] = true;
} elseif ($this->built_in_regex_css_exclusions && preg_match($this->built_in_regex_css_exclusions, $_tag_frag_r['link_href'].$_tag_frag_r['style_css'])) {
$_tag_frag_r['exclude'] = true;
}
}
}
}
unset($_tag_frags, $_tag_frag, $_tag_frag_r, $_link_href, $_style_css, $_media);
finale: // Target point; finale/return value.
if ($benchmark && !empty($time) && $html_frag) {
$this->benchmark->addTime(
__FUNCTION__,
$time, // Caller, start time, task performed.
sprintf('compiling CSS tag frags in checksum: `%1$s`', md5(serialize($html_frag)))
);
}
return $css_tag_frags;
}
/**
* Test a tag fragment to see if it's CSS.
*
* @since 140922 Improving tag tests.
*
* @param array $tag_frag A tag fragment.
*
* @return bool TRUE if it contains CSS.
*/
protected function isLinkTagFragCss(array $tag_frag)
{
if (empty($tag_frag['link_self_closing_tag'])) {
return false; // Nope; missing tag.
}
$type = $rel = ''; // Initialize.
if (stripos($tag_frag['link_self_closing_tag'], 'type') !== 0) {
if (preg_match('/\stype\s*\=\s*(["\'])(?P<value>.+?)\\1/i', $tag_frag['link_self_closing_tag'], $_m)) {
$type = $_m['value'];
}
}
unset($_m); // Just a little housekeeping.
if (stripos($tag_frag['link_self_closing_tag'], 'rel') !== 0) {
if (preg_match('/\srel\s*\=\s*(["\'])(?P<value>.+?)\\1/i', $tag_frag['link_self_closing_tag'], $_m)) {
$rel = $_m['value'];
}
}
unset($_m); // Just a little housekeeping.
if ($type && stripos($type, 'css') === false) {
return false; // Not CSS.
}
if ($rel && stripos($rel, 'stylesheet') === false) {
return false; // Not CSS.
}
return true; // Yes, this is CSS.
}
/**
* Test a tag fragment to see if it's CSS.
*
* @since 140922 Improving tag tests.
*
* @param array $tag_frag A tag fragment.
*
* @return bool TRUE if it contains CSS.
*/
protected function isStyleTagFragCss(array $tag_frag)
{
if (empty($tag_frag['style_open_tag']) || empty($tag_frag['style_closing_tag'])) {
return false; // Nope; missing open|closing tag.
}
$type = ''; // Initialize.
if (stripos($tag_frag['style_open_tag'], 'type') !== 0) {
if (preg_match('/\stype\s*\=\s*(["\'])(?P<value>.+?)\\1/i', $tag_frag['style_open_tag'], $_m)) {
$type = $_m['value'];
}
}
unset($_m); // Just a little housekeeping.
if ($type && stripos($type, 'css') === false) {
return false; // Not CSS.
}
return true; // Yes, this is CSS.
}
/**
* Get a CSS link href value from a tag fragment.
*
* @since 140417 Initial release.
*
* @param array $tag_frag A CSS tag fragment.
* @param bool $test_for_css Defaults to a TRUE value.
* If TRUE, we will test tag fragment to make sure it's CSS.
*
* @return string The link href value if possible; else an empty string.
*/
protected function getLinkCssHref(array $tag_frag, $test_for_css = true)
{
if ($test_for_css && !$this->isLinkTagFragCss($tag_frag)) {
return ''; // This tag does not contain CSS.
}
if (preg_match('/\shref\s*\=\s*(["\'])(?P<value>.+?)\\1/i', $tag_frag['link_self_closing_tag'], $_m)) {
return trim($this->nUrlAmps($_m['value']));
}
unset($_m); // Just a little housekeeping.
return ''; // Unable to find an `href` attribute value.
}
/**
* Get a CSS link media rule from a tag fragment.
*
* @since 140417 Initial release.
*
* @param array $tag_frag A CSS tag fragment.
* @param bool $test_for_css Defaults to a TRUE value.
* If TRUE, we will test tag fragment to make sure it's CSS.
*
* @return string The link media value if possible; else an empty string.
*/
protected function getLinkCssMedia(array $tag_frag, $test_for_css = true)
{
if ($test_for_css && !$this->isLinkTagFragCss($tag_frag)) {
return ''; // This tag does not contain CSS.
}
if (preg_match('/\smedia\s*\=\s*(["\'])(?P<value>.+?)\\1/i', $tag_frag['link_self_closing_tag'], $_m)) {
return trim(strtolower($_m['value']));
}
unset($_m); // Just a little housekeeping.
return ''; // Unable to find a `media` attribute value.
}
/**
* Get a CSS style media rule from a tag fragment.
*
* @since 140417 Initial release.
*
* @param array $tag_frag A CSS tag fragment.
* @param bool $test_for_css Defaults to a TRUE value.
* If TRUE, we will test tag fragment to make sure it's CSS.
*
* @return string The style media value if possible; else an empty string.
*/
protected function getStyleCssMedia(array $tag_frag, $test_for_css = true)
{
if ($test_for_css && !$this->isStyleTagFragCss($tag_frag)) {
return ''; // This tag does not contain CSS.
}
if (preg_match('/\smedia\s*\=\s*(["\'])(?P<value>.+?)\\1/i', $tag_frag['style_open_tag'], $_m)) {
return trim(strtolower($_m['value']));
}
unset($_m); // Just a little housekeeping.
return ''; // Unable to find a `media` attribute value.
}
/**
* Get style CSS from a CSS tag fragment.
*
* @since 140417 Initial release.
*
* @param array $tag_frag A CSS tag fragment.
* @param bool $test_for_css Defaults to a TRUE value.
* If TRUE, we will test tag fragment to make sure it's CSS.
*
* @return string The style CSS code (if possible); else an empty string.
*/
protected function getStyleCss(array $tag_frag, $test_for_css = true)
{
if (empty($tag_frag['style_css'])) {
return ''; // Not possible; no CSS code.
}
if ($test_for_css && !$this->isStyleTagFragCss($tag_frag)) {
return ''; // This tag does not contain CSS.
}
return trim($tag_frag['style_css']); // CSS code.
}
/**
* Strip existing charset rules from CSS code.
*
* @since 140417 Initial release.
*
* @param string $css CSS code.
*
* @return string CSS after having stripped away existing charset rules.
*/
protected function stripExistingCssCharsets($css)
{
if (!($css = (string) $css)) {
return $css; // Nothing to do.
}
$css = preg_replace('/@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?charset(?:\s+[^;]*?)?;/i', '', $css);
if ($css) {
$css = trim($css);
}
return $css;
}
/**
* Strip existing charsets and add a UTF-8 `@charset` rule.
*
* @since 140417 Initial release.
*
* @param string $css CSS code.
*
* @return string CSS code (possibly with a prepended UTF-8 charset rule).
*/
protected function stripPrependCssCharsetUtf8($css)
{
if (!($css = (string) $css)) {
return $css; // Nothing to do.
}
$css = $this->stripExistingCssCharsets($css);
if ($css) {
$css = '@charset "UTF-8";'."\n".$css;
}
return $css;
}
/**
* Moves special CSS `@rules` to the top.
*
* @since 140417 Initial release.
*
* @param string $css CSS code.
* @param int $___recursion Internal use only.
*
* @return string CSS code after having moved special `@rules` to the top.
*
* @see <https://developer.mozilla.org/en-US/docs/Web/CSS/@charset>
* @see <http://stackoverflow.com/questions/11746581/nesting-media-rules-in-css>
*/
protected function moveSpecialCssAtRulesToTop($css, $___recursion = 0)
{
if (!($css = (string) $css)) {
return $css; // Nothing to do.
}
$max_recursions = 2; // `preg_match_all()` calls.
if ($___recursion >= $max_recursions) {
return $css; // All done.
}
if (stripos($css, 'charset') === false && stripos($css, 'import') === false) {
return $css; // Save some time. Nothing to do here.
}
if (preg_match_all('/(?P<rule>@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?charset(?:\s+[^;]*?)?;)/i', $css, $rules, PREG_SET_ORDER)
|| preg_match_all('/(?P<rule>@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import(?:\s+[^;]*?)?;)/i', $css, $rules, PREG_SET_ORDER)
) { // Searched in a specific order. Recursion dictates a precise order.
$top_rules = array(); // Initialize.
foreach ($rules as $_rule) {
$top_rules[] = $_rule['rule'];
}
unset($_rule); // Just a little housekeeping.
$css = $this->replaceOnce($top_rules, '', $css);
$css = $this->moveSpecialCssAtRulesToTop($css, $___recursion + 1);
$css = implode("\n\n", $top_rules)."\n\n".$css;
}
return $css; // With special `@rules` to the top.
}
/**
* Resolves `@import` rules in CSS code recursively.
*
* @since 140417 Initial release.
*
* @param string $css CSS code.
* @param string $media Current media specification.
* @param bool $___recursion Internal use only.
*
* @return string CSS code after all `@import` rules have been resolved recursively.
*/
protected function resolveResolvedCssImports($css, $media, $___recursion = false)
{
if (!($css = (string) $css)) {
return $css; // Nothing to do.
}
$media = $this->current_css_media = (string) $media;
if (!$media) {
$media = $this->current_css_media = 'all';
}
$import_media_without_url_regex = '/@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import\s*(["\'])(?P<url>.+?)\\1(?P<media>[^;]*?);/i';
$import_media_with_url_regex = '/@(?:\-(?:'.$this->regex_vendor_css_prefixes.')\-)?import\s+url\s*\(\s*(["\']?)(?P<url>.+?)\\1\s*\)(?P<media>[^;]*?);/i';
$css = preg_replace_callback($import_media_without_url_regex, array($this, 'resolveResolvedCssImportsCb'), $css);
$css = preg_replace_callback($import_media_with_url_regex, array($this, 'resolveResolvedCssImportsCb'), $css);