/
Subs-Cache.php
2028 lines (1722 loc) · 73.8 KB
/
Subs-Cache.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
/**
* This file handles all caching data in Wedge: regular data (cache_get/put_data), CSS and JavaScript.
* It also ensures that CSS and JS files are properly parsed and compressed by Wess before they're cached.
*
* Wedge (http://wedge.org)
* Copyright © 2010 René-Gilles Deberdt, wedge.org
* License: http://wedge.org/license/
*/
if (!defined('WEDGE'))
die('Hacking attempt...');
/**
* This function adds a string to the footer JavaScript that relies on jQuery and script.js being loaded.
* Several strings can be passed as parameters, allowing for easier conversion from an "echo" to an "add_js()" call.
*/
function add_js()
{
global $context, $footer_coding;
if (empty($footer_coding))
{
$footer_coding = true;
$context['footer_js'] .= '
<script>';
}
$args = func_get_args();
$context['footer_js'] .= implode('', $args);
}
/**
* Alias to add_js that will keep track of possible duplicates and ignore them.
*/
function add_js_unique($code)
{
static $uniques = array();
if (isset($uniques[$code]))
return;
$uniques[$code] = true;
add_js($code);
}
/**
* This function adds a string to the footer JavaScript. Because this will be shown before jQuery or script.js are loaded,
* you must not use any of the functions provided by default in Wedge. This is only good for quick snippets that manipulate document IDs.
*/
function add_js_inline()
{
global $context;
$args = func_get_args();
$context['footer_js_inline'] .= implode('', $args);
}
/**
* This function adds one or more minified, gzipped files to the footer JavaScript. It takes care of everything. Good boy.
*
* @param mixed $files A filename or an array of filenames, with a relative path set to the theme root folder.
* @param boolean $is_direct_url Set to true if you want to add complete URLs (e.g. external libraries), with no minification and no gzipping.
* @param boolean $is_out_of_flow Set to true if you want to get the URL immediately and not put it into the JS flow. Used for jQuery/script.js.
* @return string The generated code for direct inclusion in the source code, if $out_of_flow is set. Otherwise, nothing.
*/
function add_js_file($files = array(), $is_direct_url = false, $is_out_of_flow = false, $ignore_files = array())
{
global $context, $settings, $footer_coding;
static $done_files = array();
if (!is_array($files))
$files = (array) $files;
// Delete all duplicates and already cached files.
$files = array_diff(array_keys(array_flip($files)), $done_files);
$done_files = array_merge($done_files, $files);
if (empty($files))
return;
if ($is_direct_url || strpos($files[0], '://') !== false || strpos($files[0], '//') === 0)
{
if (!empty($footer_coding))
{
$footer_coding = false;
$context['footer_js'] .= '
</script>';
}
$context['footer_js'] .= '
<script src="' . implode('"></script>
<script src="', $files) . '"></script>';
return;
}
$id = '';
$latest_date = 0;
foreach ($files as $fid => $file)
{
if (!file_exists($add = ROOT_DIR . '/core/javascript/' . $file)) // !! Temp?
{
unset($files[$fid]);
continue;
}
// Turn name.min.js into 'name' for the final filename. We won't add keywords
// that are always in the final filename, to save a few bytes on all pages.
if (!isset($ignore_files[$file]))
$id .= str_replace('/', '_', substr(strpos($file, '/') !== false ? substr(strrchr($file, '/'), 1) : $file, 0, strpos($file, '.min.js') !== false ? -7 : -3)) . '-';
$latest_date = max($latest_date, filemtime($add));
}
// If no files were found, don't waste more time.
if (empty($files))
return;
// Add the 'm' keyword for member files -- using 'member' would add an extra couple of bytes per page for no reason.
$id .= (we::$is_member && !we::$is_admin ? 'm-' : '');
$id .= (we::$is_admin ? 'a-' : '');
$id = !empty($settings['obfuscate_filenames']) ? md5(substr($id, 0, -1)) . '-' : $id;
$latest_date %= 1000000;
$lang_name = !empty($settings['js_lang'][$id]) && !empty(we::$user['language']) && we::$user['language'] != $settings['language'] ? we::$user['language'] . '-' : '';
$can_gzip = !empty($settings['enableCompressedData']) && function_exists('gzencode') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
$ext = $can_gzip ? (we::is('safari[-5.1]') ? '.jgz' : '.js.gz') : '.js';
// jQuery never gets updated, so let's be bold and shorten its filename to... The version number!
$is_jquery = count($files) == 1 && reset($files) == 'jquery-' . $context['jquery_version'] . '.min.js';
$final_name = $is_jquery ? $context['jquery_version'] : $id . $lang_name . $latest_date;
if (!file_exists(CACHE_DIR . '/js/' . $final_name . $ext))
{
wedge_cache_js($id, $lang_name, $latest_date, $ext, $files, $can_gzip);
if ($is_jquery)
@rename(CACHE_DIR . '/js/' . $id . $lang_name . $latest_date . $ext, CACHE_DIR . '/js/' . $final_name . $ext);
}
$final_script = CACHE . '/js/' . $final_name . $ext;
// Do we just want the URL?
if ($is_out_of_flow)
return $final_script;
if (!empty($footer_coding))
{
$footer_coding = false;
$context['footer_js'] .= '
</script>';
}
$context['footer_js'] .= '
<script src="' . $final_script . '"></script>';
}
/**
* This function adds one or more minified, gzipped files to the footer JavaScript, specifically for plugins to use.
*
* @param string $plugin_name The name of the plugin in question, e.g. Arantor:MyPlugin.
* @param mixed $files A filename or an array of filenames, with a relative path set to the plugin's folder.
* @param boolean $is_direct_url Set to true if you want to add complete URLs (e.g. external libraries), with no minification and no gzipping.
* @param boolean $is_out_of_flow Set to true if you want to get the URL immediately and not put it into the JS flow. Used for jQuery/script.js.
* @return string The generated code for direct inclusion in the source code, if $out_of_flow is set. Otherwise, nothing.
*/
function add_plugin_js_file($plugin_name, $files = array(), $is_direct_url = false, $is_out_of_flow = false)
{
global $context, $settings, $footer_coding;
static $done_files = array();
if (empty($context['plugins_dir'][$plugin_name]))
return;
if (!is_array($files))
$files = (array) $files;
// Direct URL may as well reuse the main handler once we provide the right (full) URLs for it.
if ($is_direct_url)
{
foreach ($files as $k => $v)
$files[$k] = $context['plugins_url'][$plugin_name] . '/' . $v;
return add_js_file($files, true, $is_out_of_flow);
}
// OK, we're going to be caching files.
if (empty($done_files[$plugin_name]))
$done_files[$plugin_name] = array_flip(array_flip($files));
else
{
$files = array_diff(array_keys(array_flip($files)), $done_files[$plugin_name]);
$done_files[$plugin_name] = array_merge($done_files[$plugin_name], $files);
}
$id = '';
$latest_date = 0;
foreach ($files as $k => &$file)
{
$file = $context['plugins_dir'][$plugin_name] . '/' . $file;
if (!file_exists($file))
unset($files[$k]);
// Turn plugin/other.js into 'plugin_other' for the final filename.
$id .= str_replace('/', '_', substr(strrchr($file, '/'), 1, strpos($file, '.min.js') !== false ? -7 : -3)) . '-';
$latest_date = max($latest_date, filemtime($file));
}
if (empty($files))
return;
$id = substr(strrchr($context['plugins_dir'][$plugin_name], '/'), 1) . '-' . $id;
$id .= (we::$is_member && !we::$is_admin ? 'm-' : '');
$id .= (we::$is_admin ? 'a-' : '');
$id = !empty($settings['obfuscate_filenames']) ? md5(substr($id, 0, -1)) . '-' : $id;
$latest_date %= 1000000;
$lang_name = !empty($settings['js_lang'][$id]) && !empty(we::$user['language']) && we::$user['language'] != $settings['language'] ? we::$user['language'] . '-' : '';
$can_gzip = !empty($settings['enableCompressedData']) && function_exists('gzencode') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
$ext = $can_gzip ? (we::is('safari[-5.1]') ? '.jgz' : '.js.gz') : '.js';
if (!file_exists(CACHE_DIR . '/js/' . $id . $lang_name . $latest_date . $ext))
wedge_cache_js($id, $lang_name, $latest_date, $ext, $files, $can_gzip, true);
$final_script = CACHE . '/js/' . $id . $lang_name . $latest_date . $ext;
// Do we just want the URL?
if ($is_out_of_flow)
return $final_script;
if (!empty($footer_coding))
{
$footer_coding = false;
$context['footer_js'] .= '
</script>';
}
$context['footer_js'] .= '
<script src="' . $final_script . '"></script>';
}
/**
* This function adds a string to the header's inline CSS.
* Several strings can be passed as parameters, allowing for easier conversion from an "echo" to an "add_css()" call.
* Please note that, obviously, this function will do nothing if you call wetem::hide() or generally don't output the HTML head.
*/
function add_css()
{
global $context;
if (empty($context['header_css']))
$context['header_css'] = '';
$args = func_get_args();
$context['header_css'] .= ($args[0][0] !== "\n" ? "\n" : '') . implode('', $args);
}
/**
* This function adds one or more minified, gzipped files to the header stylesheets. It takes care of everything. Good boy.
*
* @param mixed $original_files A filename or an array of filenames, with a relative path set to the theme root folder. Just specify the filename, like 'index', if it's a file from the current skin.
* @param boolean $add_link Set to false if you want Wedge to return the URL instead of automatically adding the link to your page header.
* @param boolean $is_main Determines whether this is the primary CSS file list (index.css and other files), which gets special treatment.
* @return string The generated code for direct inclusion in the source code, if $out_of_flow is set. Otherwise, nothing.
*/
function add_css_file($original_files = array(), $add_link = true, $is_main = false, $ignore_files = array())
{
global $settings, $context, $db_show_debug, $files;
static $cached_files = array(), $paths_done = array();
// Set hardcoded paths aside, e.g. plugin CSS.
$latest_date = 0;
$hardcoded_css = array();
$original_files = (array) $original_files;
foreach ($original_files as $key => $path)
{
if (isset($paths_done[$path]))
{
unset($original_files[$key]);
continue;
}
if (strpos($path, '/') !== false)
{
unset($original_files[$key]);
if (file_exists($path))
{
$hardcoded_css[] = $path;
$latest_date = max($latest_date, filemtime($path));
}
}
$paths_done[$path] = true;
}
// No files left to handle..?
if (empty($original_files) && empty($hardcoded_css))
return false;
// Delete all duplicates and ensure $original_files is an array.
$original_files = array_merge(array('common' => 0), array_flip($original_files));
$files = array_keys($original_files);
// If we didn't go through the regular theme initialization flow, get the skin options.
if (!isset($context['skin_folders']))
wedge_get_skin_options();
$fallback_folder = rtrim(SKINS_DIR . '/' . reset($context['css_folders']), '/') . '/';
$deep_folder = rtrim(SKINS_DIR . '/' . end($context['css_folders']), '/') . '/';
$found_suffixes = array();
$found_files = array();
$css = array();
// Pre-cache a special keyword that always returns true.
we::$cache['global'] = 'global';
// !! @todo: the following is quite resource intensive... Maybe we should cache the results somehow?
// !! e.g. cache for several minutes, but delete cache if the filemtime for current folder or its parent folders was updated.
foreach ($context['skin_folders'] as $fold)
{
if ($fold === $fallback_folder)
$fallback_folder = '';
if (empty($cached_files[$fold]))
$cached_files[$fold] = array_diff((array) @scandir($fold ? $fold : '', 1), array('.', '..', '.htaccess', 'index.php', 'skin.xml', 'custom.xml'));
// A 'local' suffix means the file should only be parsed if it's in the same folder as the current skin.
we::$cache['local'] = $fold == $deep_folder ? 'local' : false;
foreach ($cached_files[$fold] as $file)
{
if (substr($file, -4) !== '.css')
continue;
$radix = substr($file, 0, strpos($file, '.'));
if (!isset($original_files[$radix]))
continue;
// Get the list of suffixes in the file name.
$suffix = substr(strstr($file, '.'), 1, -4);
// If we find a replace suffix, delete any parent skin file with the same radix.
// !! This is a work in progress. Needs some extra fine-tuning.
if (!empty($suffix) && strpos($suffix, 'replace') !== false)
{
$suffix = preg_replace('~[,&| ]*replace[,&| ]*~', '', $suffix);
foreach ($css as $key => $val)
if (strpos($val, '/' . $radix . '.' . ($suffix ? $suffix . '.' : '')) !== false)
unset($css[$key]);
}
// If our suffix isn't valid, then skip the file.
if (!empty($suffix) && !($found_suffix = we::is($suffix)))
continue;
$css[] = $fold . $file;
// If a suffix-less file was found, make sure we tell Wedge.
if (empty($suffix))
$found_files[] = $radix;
// Otherwise, add suffix to our list of keywords. If it was a list of AND-separated suffixes, add them all.
else
$found_suffixes[] = $found_suffix;
if (!empty($db_show_debug))
$context['debug']['sheets'][] = $file . ' (' . basename(TEMPLATES) . ')';
$latest_date = max($latest_date, filemtime($fold . $file));
}
}
// We can no longer be locals from this point on.
we::$cache['local'] = false;
// The following code is only executed if parsing a replace-type skin and one of the files wasn't found.
if (!empty($fallback_folder))
{
$not_found = array_flip(array_diff($files, $found_files));
$fold = $fallback_folder;
if (empty($cached_files[$fold]))
$cached_files[$fold] = array_diff((array) @scandir($fold ? $fold : '', 1), array('.', '..', '.htaccess', 'index.php', 'skin.xml', 'custom.xml'));
foreach ($cached_files[$fold] as $file)
{
if (substr($file, -4) !== '.css')
continue;
$radix = substr($file, 0, strpos($file, '.'));
if (!isset($original_files[$radix], $not_found[$radix]))
continue;
$css[] = $fold . $file;
if (!empty($db_show_debug))
$context['debug']['sheets'][] = $file . ' (' . basename(TEMPLATES) . ')';
$latest_date = max($latest_date, filemtime($fold . $file));
}
}
// Now that we have our final CSS file list, sort it in this order:
// skins/index, skins/index.suffix.css, skins/SubSkin/index.css,
// skins/sections.css, skins/SubSkin/sections.suffix.css, etc.
usort($css, 'sort_skin_files');
$folder = end($context['css_folders']);
$id = $folder;
$latest_date %= 1000000;
$can_gzip = !empty($settings['enableCompressedData']) && function_exists('gzencode') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
$ext = $can_gzip ? (we::is('safari[-5.1]') ? '.cgz' : '.css.gz') : '.css';
// And the language. Only do it if the skin allows for multiple languages and we're not in English mode.
if (isset($context['skin_available_languages']) && we::$user['language'] !== 'english')
$found_suffixes[] = we::$user['language'];
// Build the target folder from our skin's folder names and main file name. We don't need to show 'common-index-sections-extra-custom' in the main filename, though!
$target_folder = trim($id . '-' . implode('-', array_filter(array_diff($files, (array) 'common', $ignore_files))), '-');
// Cache final file and retrieve its name.
$final_script = CACHE . '/css/' . wedge_cache_css_files($target_folder . ($target_folder ? '/' : ''), $found_suffixes, $latest_date, array_merge($css, $hardcoded_css), $can_gzip, $ext);
if ($final_script == CACHE . '/css/')
return false;
if ($is_main)
return $context['cached_css'] = $final_script;
// Do we just want the URL?
if (!$add_link)
return $final_script;
$context['header'] .= '
<link rel="stylesheet" href="' . $final_script . '">';
}
function add_plugin_css_file($plugin_name, $original_files = array(), $add_link = false, $ignore_files = array())
{
global $context, $settings;
if (empty($context['plugins_dir'][$plugin_name]))
return;
if (!is_array($original_files))
$original_files = (array) $original_files;
// Delete all duplicates.
$files = array_keys(array_flip($original_files));
$basefiles = array();
// Plugin CSS files don't support suffixes for now.
// Use @if tests inside them, they should work.
foreach ($files as $file)
{
if (substr($file, -4) === '.css')
$file = substr($file, 0, -4);
$basefiles[] = substr(strrchr($file, '/'), 1);
$files[] = $file;
}
$latest_date = 0;
foreach ($files as $i => &$file)
{
$full_path = $context['plugins_dir'][$plugin_name] . '/' . $file . '.css';
if (!file_exists($full_path))
{
unset($files[$i]);
continue;
}
$file = $full_path;
$latest_date = max($latest_date, filemtime($full_path));
}
$pluginurl = '..' . str_replace(ROOT, '', $context['plugins_url'][$plugin_name]);
// We need to cache different versions for different browsers, even if we don't have overrides available.
// This is because Wedge also transforms regular CSS to add vendor prefixes and the like.
$id = array_filter(array_merge(
array($context['enabled_plugins'][$plugin_name]),
$basefiles,
we::$user['language'] !== 'english' ? (array) we::$user['language'] : array()
));
$latest_date %= 1000000;
$can_gzip = !empty($settings['enableCompressedData']) && function_exists('gzencode') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
$ext = $can_gzip ? (we::is('safari[-5.1]') ? '.cgz' : '.css.gz') : '.css';
// Build the target folder from our plugin's file names. We don't need to show 'common-index-sections-extra-custom' in the main filename, though!
$target_folder = trim(str_replace(array('/', ':'), '-', strtolower($plugin_name) . '-' . implode('-', array_filter(array_diff($original_files, (array) 'common', $ignore_files)))), '-');
// Cache final file and retrieve its name.
$final_script = CACHE . '/css/' . wedge_cache_css_files($target_folder . ($target_folder ? '/' : ''), $id, $latest_date, $files, $can_gzip, $ext, array('$plugindir' => $context['plugins_url'][$plugin_name]));
if ($final_script == CACHE . '/css/')
return false;
// Do we just want the URL?
if (!$add_link)
return $final_script;
$context['header'] .= '
<link rel="stylesheet" href="' . $final_script . '">';
}
function sort_skin_files($a, $b)
{
global $context, $files;
$c = strrchr($a, '/'); // 3x faster than basename()!
$d = strrchr($b, '/');
$i = substr($c, 1, strpos($c, '.') - 1);
$j = substr($d, 1, strpos($d, '.') - 1);
// Same main file name?
if ($i == $j)
{
// Most top-level folder wins.
foreach ($context['css_folders'] as $folder)
{
$root = SKINS_DIR . ($folder ? '/' . $folder : '');
$is_a = $a === $root . $c;
$is_b = $b === $root . $d;
if ($is_a && !$is_b)
return -1;
elseif (!$is_a && $is_b)
return 1;
}
// Same folder, same starting name? Shortest suffix wins.
$x = strlen($c);
$y = strlen($d);
if ($x > $y)
return 1;
if ($x < $y)
return -1;
return 0;
}
// Different file names? First in $files wins.
foreach ($files as $file)
if ($i === $file)
return -1;
elseif ($j === $file)
return 1;
return 0;
}
/**
* Retrieve a full, final set of dash-separated suffixes for the filename.
*/
function wedge_get_css_filename($add)
{
global $settings;
$suffix = array_flip(array_filter(array_map('we::is', is_array($add) ? $add : explode('|', $add))));
if (isset($suffix['m' . MID]))
unset($suffix['member'], $suffix['admin']);
if (isset($suffix['admin']))
unset($suffix['member']);
if (isset($suffix[we::$os['os']]))
$suffix = array(str_replace('dows', '', we::$os['os'] . we::$os['version']) => true) + array_diff_key($suffix, array(we::$os['os'] => 1));
if (!empty(we::$browser['agent']))
$suffix = array(we::$browser['agent'] . (!empty(we::$browser['version']) ? we::$browser['version'] : '') => 1) + $suffix;
$id = implode('-', array_keys($suffix));
return $id ? (empty($settings['obfuscate_filenames']) ? $id : md5($id)) : '';
}
/**
* Create a compact CSS file that concatenates, pre-parses and compresses a list of existing CSS files.
*
* @param mixed $folder The target folder (relative to the cache folder.)
* @param mixed $ids An array of filename radixes, such as array('index', 'member', 'extra').
* @param integer $latest_date The most recent filedate (Unix timestamp format), to be used to differentiate the latest copy from expired ones.
* @param string $css The CSS file to process, or an array of CSS files to process, in order, with complete path names.
* @param boolean $gzip Set to true if you want the final file to be compressed with gzip.
* @param string $ext The extension for the final file. Default is '.css', some browsers may have problems with '.css.gz' if gzipping is enabled.
* @return array $additional_vars An array of key-pair values to associate custom CSS variables with their intended replacements.
*/
function wedge_cache_css_files($folder, $ids, $latest_date, $css, $gzip = false, $ext = '.css', $additional_vars = array())
{
global $css_vars, $context, $settings, $time_start;
$final_folder = substr(CACHE_DIR . '/css/' . $folder, 0, -1);
$cachekey = 'css_files-' . $folder . implode('-', $ids);
// Get the list of tests that shall be done within the CSS files,
// and quickly run them to get relevant suffixes. MAGIC!
if (($add = cache_get_data($cachekey, 'forever')) !== null)
{
$id = wedge_get_css_filename($add);
$full_name = ($id ? $id . '-' : '') . $latest_date . $ext;
$final_file = $final_folder . '/' . $full_name;
if (file_exists($final_file))
return $folder . $full_name;
}
$sleep_time = microtime(true);
we::$user['extra_tests'] = array();
if (!empty($folder) && $folder != '/' && !file_exists($final_folder))
{
@mkdir($final_folder, 0755);
@copy(CACHE_DIR . '/css/index.php', $final_folder . '/index.php');
}
$final = '';
$discard_dir = strlen(ROOT_DIR) + 1;
// Load Wess, our sweet, short and fast CSS parser :)
loadSource('Class-CSS');
$plugins = array(
new wess_dynamic(), // Dynamic replacements through callback functions
new wess_if(), // CSS conditions, first pass (browser tests)
new wess_mixin(), // CSS mixins (mixin hello($world: 0))
new wess_var(), // CSS variables ($hello_world)
new wess_color(), // CSS color transforms
new wess_func(), // Various CSS functions
new wess_math(), // Math function (math(1px + 3px), math((4*$var)/2em)...)
new wess_if(true), // CSS conditions, second pass (variable tests)
new wess_nesting(), // Nested selectors (.hello { .world { color: 0 } }) + selector inheritance (.hello { base: .world })
new wess_prefixes(), // Automatically adds browser prefixes for many frequent elements, or manually through -prefix.
);
// rgba to rgb conversion for IE 6-8, and a hack for IE9.
if (we::is('ie[-9]'))
$plugins[] = new wess_rgba();
// No need to start the Base64 plugin if we can't gzip the result or the browser can't see it...
// (Probably should use more specific browser sniffing.)
// Note that this is called last, mostly to avoid conflicts with the semicolon character.
if ($gzip && !we::is('ie6,ie7'))
$plugins[] = new wess_base64($folder);
// Default CSS variables (paths are absolute or, if forum is in a sub-folder, relative to the CSS cache folder)
// !!! If subdomains are allowed, should we use absolute paths instead?
$languages = isset($context['skin_available_languages']) ? $context['skin_available_languages'] : array('english');
$css_vars = array(
'$language' => isset(we::$user['language']) && in_array(we::$user['language'], $languages) ? we::$user['language'] : $languages[0],
'$images_dir' => ASSETS_DIR,
'$theme_dir' => SKINS_DIR,
'$root_dir' => ROOT_DIR,
'$images' => ASSETS,
'$root' => ROOT,
);
if (!empty($additional_vars))
foreach ($additional_vars as $key => $val)
$css_vars[$key] = $val;
if (!empty($context['plugins_dir']))
foreach ($context['plugins_dir'] as $key => $val)
$css_vars['$plugins_dir[\'' . $key . '\']'] = str_replace(ROOT_DIR, '', $val);
if (!empty($context['plugins_url']))
foreach ($context['plugins_url'] as $key => $val)
$css_vars['$plugins[\'' . $key . '\']'] = str_replace(ROOT, '', $val);
// Our deepest skin folder is the one for which 'local' keywords will return true.
$deep_folder = rtrim(SKINS_DIR . '/' . end($context['css_folders']), '/');
// Load all CSS files in order, replace $here with the current folder while we're at it, and mark local sections.
foreach ((array) $css as $file)
{
$local = file_get_contents($file);
if (dirname($file) === $deep_folder && strpos(strtolower($local), 'local') !== false)
$local = preg_replace('~@(is\h+\([^),]*|(?:else)?if\h+[^\n]*)\blocal\b~i', '@$1true', $local);
$final .= str_replace('$here', str_replace(ROOT_DIR, ROOT, dirname($file)), $local);
}
unset($local);
if (empty($final)) // Nothing loaded...?
{
cache_put_data($cachekey, '', 'forever');
return false;
}
// Resolve references to some common Wedge variables.
$final = preg_replace_callback('~\$(context|settings|theme|txt)\[([\'"])(.*?)\2]~', 'wedge_replace_theme_vars', $final);
// CSS is always minified. It takes just a sec' to do, and doesn't impair anything.
$final = str_replace(array("\r\n", "\r"), "\n", $final); // Always use \n line endings.
$final = preg_replace('~/\*(?!!).*?\*/~s', '', $final); // Strip comments except for copyrights.
// And this is where we preserve some of the comments.
preg_match_all('~\n?/\*!(.*?)\*/\n?~s', $final, $comments);
$final = preg_replace('~/\*!.*?\*/~s', '.wedge_comment_placeholder{border:0}', $final);
$final = preg_replace('~\n\t*//[^\n]*~', "\n", $final); // Strip comments at the beginning of lines.
$final = preg_replace('~//[ \t][^\n]*~', '', $final); // Strip remaining comments like me. OMG does this mean I'm gonn
// Just like comments, we're going to preserve content tags.
preg_match_all('~(?<=\s)content\s*:([^\n]+)~', $final, $contags);
$context['reset_content_counter'] = true;
$final = preg_replace_callback('~(?<=\s)content\s*:[^\n]+~', 'wedge_hide_content', $final);
foreach ($plugins as $plugin)
$plugin->process($final);
if (we::$user['extra_tests'])
{
// Okay, so there are better ways to handle these... For instance, a test on android[-4.0] will store
// a keyword if you're on Android, even 4.1+. But right now, it's better than what we had before.
preg_match_all('~[bcm][0-9]+|[a-z]+~i', preg_replace('~".*?"~', '', implode(' ', array_flip(array_flip(array_merge($ids, we::$user['extra_tests']))))), $matches);
$add = array_diff(array_flip(array_flip($matches[0])), array_keys(we::$browser), array('global', 'local', 'true'));
}
// Cache all tests.
cache_put_data($cachekey, empty($add) ? $ids : $add, 'forever');
// And we've finally got our full, working filename...
$id = wedge_get_css_filename(isset($add) ? $add : array());
$full_name = ($id ? $id . '-' : '') . $latest_date . $ext;
$final_file = $final_folder . '/' . $full_name;
// Delete cached versions, unless they have the same timestamp (i.e. up to date.)
if (is_array($files = glob($final_folder . '/' . ($id ? $id . '-*' : '[0-9]*') . $ext, GLOB_NOSORT)))
foreach ($files as $del)
if (($id || preg_match('~/\d+\.~', $del)) && strpos($del, (string) $latest_date) === false)
@unlink($del);
// Remove the 'final' keyword.
$final = preg_replace('~\s+final\b~', '', $final);
// Remove extra whitespace. Note that this breaks additions and substractions in calc(), as they need their own whitespace.
// I'll be fixing this, eventually. But needs more regexes, more CPU time, and this means more kitties getting slaughtered. :(
$final = preg_replace('~\s*([][+:;,>{}\s])\s*~', '$1', $final);
// This is a bit quirky, like me, as we want to simplify paths but may still break non-path strings in the process.
// At this point in the code, thought, strings should be hidden from view so it sounds okay to do that.
while (preg_match('~/(?:\.[^.]*|[^.:*?"<>|/][^:*?"<>|/]*)/\.\./~', $final, $relpath))
$final = str_replace($relpath[0], '/', $final);
// Remove double quote hacks, remaining whitespace, and no-base64 tricks.
$final = str_replace(
array('#wedge-quote#', "\n\n", ';;', ';}', "}\n", "\t", ' !important', 'raw-url('),
array('"', "\n", ';', '}', '}', ' ', '!important', 'url('),
$final
);
// Group as many matches as we can, into a :matches() selector. This is new in CSS4 and implemented
// in WebKit and Firefox as of this writing. Because I couldn't find a clean source indicating when
// support was added, I'll stick to MDN's list, and use :any until :matches is officialized.
$selector = '([abipqsu]|[!+>&#*@:.a-z0-9][^{};,\n"()\~+> ]+?)'; // like $selector_regex, but lazy (+?) and without compounds (\~+> ).
if (we::is('chrome[12-],firefox[4-],safari[5.2-]') && preg_match_all('~(?:^|})' . $selector . '([>+: ][^,{]+)(?:,' . $selector . '\2)+(?={)~', $final, $matches, PREG_SET_ORDER))
{
$magic = we::$browser['webkit'] ? ':-webkit-any' : ':-moz-any';
foreach ($matches as $m)
{
// The spec says pseudo-elements aren't allowed INSIDE :matches, but implementations seem to also refuse them NEXT to :matches.
if (strpos($m[0], ':') !== false && strhas($m[0], array(':before', ':after', ':first-letter', ':first-line', ':selection')))
continue;
$final = str_replace(
$m[0],
($m[0][0] === '}' ? '}' : '') . $magic . '(' . str_replace(
array($m[2] . ',', $m[2] . '{', '}'),
array(',', '', ''),
$m[0] . '{'
) . ')' . $m[2],
$final
);
}
}
// We may want to apply page replacements to CSS files as well.
$rep = array();
if (isset($settings['page_replacements']))
$rep = unserialize($settings['page_replacements']);
if (isset($context['ob_replacements']))
$rep = array_merge($rep, $context['ob_replacements']);
if (!empty($rep))
$final = str_replace(array_keys($rep), array_values($rep), $final);
// Turn url(ROOT/image) into url(/image), but *only* if the CSS file is served from inside ROOT!
// We're going to go through page replacements to ensure mydomain/gz/css/ isn't turned into something else.
$set_relative = true;
if (!empty($rep))
foreach ($rep as $key => $val)
$set_relative &= strpos($key, 'gz/css') === false;
if ($set_relative)
{
preg_match('~.*://[^/]+~', ROOT, $root_root);
if (!empty($root_root))
$final = str_replace('url(' . $root_root[0], 'url(', $final);
}
// Restore comments as requested.
if (!empty($comments))
wedge_replace_placeholders('.wedge_comment_placeholder{border:0}', $comments[0], $final);
// And do the same for content tags.
if (!empty($contags))
wedge_replace_numbered_placeholders('content:wedge', $contags[0], $final);
$final = ltrim($final, "\n");
// If we find any empty rules, we should be able to remove them.
if (strpos($final, '{}') !== false)
$final = preg_replace('~(?<=[{}])[^{}]*{}~', '', $final);
if ($gzip)
$final = gzencode($final, 9);
@file_put_contents($final_file, $final);
// Don't take generation times into account for our stats. It's only done once in a while anyway...
$time_start += microtime(true) - $sleep_time;
return $folder . $full_name;
}
function wedge_hide_content()
{
global $context;
static $i;
if (!empty($context['reset_content_counter']))
{
$i = 0;
unset($context['reset_content_counter']);
}
return 'content: wedge' . $i++;
}
function wedge_replace_theme_vars($match)
{
global ${$match[1]};
return isset(${$match[1]}[$match[3]]) ? '"' . (is_array(${$match[1]}[$match[3]]) ? count(${$match[1]}[$match[3]]) : ${$match[1]}[$match[3]]) . '"' : '""';
}
// This will replace {$str}, {$str}, ... in $final with successive entries in $arr
// $add_nl can be used to add newlines around the replacements.
function wedge_replace_placeholders($str, $arr, &$final, $add_nl = false)
{
$i = 0;
$len = strlen($str);
while (($pos = strpos($final, $str)) !== false)
$final = substr_replace($final, $add_nl ? "\n" . $arr[$i++] . "\n" : $arr[$i++], $pos, $len);
}
// This will replace {$str}0, {$str}1, {$str}2... in $final with the corresponding index in $arr
function wedge_replace_numbered_placeholders($str, $arr, &$final)
{
$len = strlen($str);
while (($pos = strpos($final, $str)) !== false)
{
$index = intval(substr($final, $pos + $len));
$final = substr_replace($final, $arr[$index], $pos, $len + strlen($index));
}
}
// Dynamic function to cache language flags into index.css
function dynamic_language_flags()
{
global $context;
if (empty($context['languages']) || count($context['languages']) < 2)
return;
$rep = '';
foreach ($context['languages'] as $language)
{
$icon = str_replace(ROOT_DIR, '', LANGUAGES_DIR) . $language['folder'] . '/Flag.' . $language['filename'] . '.gif';
$rep .= '
.flag_' . $language['filename'] . ' mixes .inline-block("")
background: url($root'. $icon . ') no-repeat 0 center
padding-left: math(width($root_dir'. $icon . ') + 6px)
min-height: height($root_dir'. $icon . ')px';
}
return $rep;
}
// Dynamic function to cache group colors into index.css
function dynamic_group_colors()
{
// If the database isn't ready yet, skip this...
if (defined('WEDGE_INSTALLER'))
return '';
$bius = array('b', 'i', 'u', 's');
$rep = '';
$request = wesql::query('
SELECT id_group, online_color, format
FROM {db_prefix}membergroups AS g
WHERE g.online_color != {string:blank} OR g.format != {string:blank}',
array(
'blank' => '',
)
);
while ($row = wesql::fetch_assoc($request))
{
$rep .= '
.group' . $row['id_group'];
if (!empty($row['online_color']))
$rep .= '
color: ' . $row['online_color'];
if (!empty($row['format']))
{
$row['format'] = explode('|', $row['format']);
// Actually faster than foreaching+switch.
if (in_array('b', $row['format']))
$rep .= '
font-weight: bold';
if (in_array('i', $row['format']))
$rep .= '
font-style: italic';
// Now we do underline and strikethrough which nest.
$text_decoration = array();
if (in_array('u', $row['format']))
$text_decoration[] = 'underline';
if (in_array('s', $row['format']))
$text_decoration[] = 'line-through';
if (!empty($text_decoration))
$rep .= '
text-decoration: ' . implode(' ', $text_decoration);
// Lastly freeformat. As in... anything left?
$row['format'] = array_diff($row['format'], $bius);
if (!empty($row['format']))
{
// Users get a single line textbox, they expect to use ; as a separator.
$row['format'] = explode(';', implode('', $row['format']));
array_walk($row['format'], 'trim');
foreach ($row['format'] as $item)
$rep .= '
' . $item;
}
}
}
return $rep;
}
// Dynamic function to cache admin menu icons into admenu.css
function dynamic_admin_menu_icons()
{
global $admin_areas, $ina;
function array_search_key($needle, &$arr)
{
global $ina;
foreach ($arr as $key => &$val)
{
if (!is_array($val))
continue;
if (isset($val[$needle]))
$ina[] = array($key, $val[$needle]);
else
array_search_key($needle, $val);
}
}
$ina = array();
array_search_key('icon', $admin_areas);
$rep = '';
foreach ($ina as $val)
{
$is_abs = isset($val[1]) && ($val[1][0] == '/' || strpos($val[1], '://') !== false);
$icon = $is_abs ? $val[1] : '/admin/' . $val[1];
$rep .= '
.admenu_icon_' . $val[0] . ' mixes .inline-block
background: url('. ($is_abs ? $icon : '$images' . $icon) . ') no-repeat
width: width('. ($is_abs ? $icon : '$images_dir' . $icon) . ')px
height: height('. ($is_abs ? $icon : '$images_dir' . $icon) . ')px';
}
unset($ina);
return $rep;
}
/**
* Create a compact JS file that concatenates and compresses a list of existing JS files.
*
* @param string $id Name of the file to create, minus the date and extension.
* @param string $lang_name Name of the user's language, if needed.
* @param int $latest_date Date of the most recent JS file in the list, used to force recaching.
* @param string $ext The file extension to use.
* @param array $js List of all JS files to concatenate.
* @param bool $gzip Should we gzip the resulting file?
* @param bool $full_path Whether or not the file list provided is using a full physical path or not, typically not (so it falls to the theme directory instead)
* @return int Returns the current timestamp, for use in caching.
*/
function wedge_cache_js($id, &$lang_name, $latest_date, $ext, $js, $gzip = false, $full_path = false)
{
global $settings, $comments, $txt, $time_start;
static $closure_failed = false;
$sleep_time = microtime(true);
$final = '';
$dir = $full_path ? '' : ROOT_DIR . '/core/javascript/';
$no_packing = array();
// Delete cached versions, unless they have the same timestamp (i.e. up to date.)
if (is_array($files = glob(CACHE_DIR . '/js/' . $id. '*' . $ext, GLOB_NOSORT)))
foreach ($files as $del)