forked from kaltura/mwEmbed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResourceLoader.php
1303 lines (1167 loc) · 41.2 KB
/
ResourceLoader.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 core ResourceLoader provides the resource loader functionality
* @file
*/
//Setup the script local script cache directory
// Check if being used in mediaWiki ( ResourceLoader.php is NOT an entry point )
if( is_file ( dirname( __FILE__ ) .'../mwResourceLoader.php' )
&& !defined( 'SCRIPTLOADER_MEDIAWIKI') ) {
die( 'ResourceLoader.php is not an entry point when used with the JS2 extension' );
}
// Check if we are an entry point or being used as part of MEDIAWIKI:
if ( !defined( 'MEDIAWIKI' ) && !defined( 'SCRIPTLOADER_MEDIAWIKI') ) {
// Include settings ( will include LocalSettings.php in the root mwEmbed folder
require_once( dirname( __FILE__ ) . '/includes/DefaultSettings.php' );
// Load stand alone Resource Loader config
// ( if running as a remote, mediaWiki variables / functions are already included as part of mediaWiki )
require_once( realpath( dirname( __FILE__ ) ) . '/includes/noMediaWikiConfig.php' );
$myResourceLoader = new ResourceLoader();
if( $myResourceLoader->outputFromCache() ) {
exit();
}
$myResourceLoader->doResourceLoader();
}
class ResourceLoader {
// The list of named javascript & css files
private $namedFileList = array();
// The language code for the script-loader request
var $langCode = '';
// The output string
var $output = '';
// Special prepend js var to be added to the top of minification output.
// useful for special comment tags in minification output
var $notMinifiedTopOutput = '';
// The request Key for the js
var $requestKey = '';
// Error msg
var $errorMsg = '';
// Output format is either 'js' or 'css' or 'messages' for exclusively msg text;
var $outputFormat = 'js';
// Debug flag
var $debug = false;
// The raw requested class
private static $rawClassList = '';
// The includeAllModuleMessages string regular expression
private static $includeAllMsgsRegEx = "/mw\.includeAllModuleMessages\s*\(\s*\)\;?/";
//Temporary store for message js
private static $addMessageJs = '';
/**
* Output the javascript from cache
*
* @return {Boolean} true on success, false on failure
*/
function outputFromCache(){
// Process the request
$this->requestKey = $this->preProcRequestVars();
// Setup file cache object
$this->sFileCache = new simpleFileCache( $this->requestKey );
if ( $this->sFileCache->isFileCached() ) {
// Output headers
$this->outputHeaders();
// Output cached file
$this->sFileCache->outputFile();
return true;
}
return false;
}
/**
* Core resourceLoader driver:
*
* get request key
* builds javascript string
* optionally gzips the output
* checks for errors
* sends the headers
* outputs js
*/
function doResourceLoader() {
global $wgResourceLoaderNamedPaths, $IP, $wgUseFileCache;
// Load the resource paths:
require_once( realpath( dirname( __FILE__ ) ) . "/includes/NamedResourceLoader.php");
try {
NamedResourceLoader::loadResourcePaths();
} catch( Exception $e ) {
$this->errorMsg .= "loadResourcePaths:" . $e->getMessage() ;
}
// Reset the requestKey:
$this->requestKey = '';
// Do the post proc request with configuration vars:
$this->postProcRequestVars();
// Update the filename (if gzip is on)
$this->sFileCache->getCacheFileName();
// Setup script loader header ( to easy identify file data )
if( $this->outputFormat == 'js' ) {
$this->output .= 'var mwResourceLoaderDate = "' .
xml::escapeJsString( date( 'c' ) ) . '";' . "\n";
$this->output .= 'var mwResourceLoaderRequestKey = "' .
xml::escapeJsString( $this->requestKey ) . '";' . "\n";
}
// Build the output
// Swap in the appropriate language per js_file
foreach ( $this->namedFileList as $resourceName => $filePath ) {
// Check if we are exclusively getting messages
if( $this->outputFormat == 'messages' ) {
// Get only the message code
$this->output .= $this->getResourceMessageJS( $resourceName );
} else {
// Process the full class
$this->output .= $this->getLocalizedScriptText( $resourceName );
}
// MwEmbed is a core component so it includes loaders and other styles
if( $resourceName == 'mwEmbed' && $this->outputFormat != 'messages' ){
// Output core components ( parts of core mwEmbed that are in different files )
$coreComponentsList = NamedResourceLoader::getComponentsList();
foreach( $coreComponentsList as $componentClassName ) {
// Output the core component via the script loader:
$this->output .= $this->getLocalizedScriptText( $componentClassName );
}
// Output the loaders js
$loaderJS = NamedResourceLoader::getCombinedLoaderJs();
// Transform the loader text to remove debug statements and
// update language msgs if any are present
$this->output .= $this->transformScriptText( $loaderJS , 'mwEmbed');
// Output the current language resource js
$this->output .= NamedResourceLoader::getLanguageJs( $this->langCode );
// Output the localSettings.js
$localSettingsJsPath = realpath( dirname( __FILE__ ) ) . '/localSettings.js';
if( is_file( $localSettingsJsPath ) ){
wfSuppressWarnings();
$this->output .= file_get_contents( $localSettingsJsPath );
wfRestoreWarnings();
}
// Add the required core mwEmbed style sheets
// removed for now because when creating stand alone packages js package with css
// the paths get messed up.
/*if( !isset( $this->namedFileList[ 'mw.style.mwCommon' ] ) ) {
$this->output .= $this->getResourceText( 'mw.style.mwCommon' );
}*/
// Output "special" IE comment tag to support "special" mwEmbed tags.
$this->notMinifiedTopOutput .='/*@cc_on@if(@_jscript_version<9){\'video audio source itext playlist\'.replace(/\w+/g,function(n){document.createElement(n)})}@end@*/'."\n";
}
}
/**
* Add a mw.loadDone resource callback if there was no "error" in getting any of the classes
*/
if ( $this->errorMsg == '' && $this->outputFormat == 'js' ){
$this->output .= self::getOnDoneCallback( );
}
// Check if we should minify the whole thing:
if ( !$this->debug && $this->outputFormat == 'js' ) {
$this->output = self::getMinifiedJs( $this->output , $this->requestKey );
$this->output = $this->notMinifiedTopOutput . $this->output;
}
// Save to the file cache
if ( $wgUseFileCache && !$this->debug ) {
$status = $this->sFileCache->saveToFileCache( $this->output );
if ( $status !== true ) {
$this->errorMsg .= "Could not save file to cache::" . $status;
}
}
// Check for an error msg
if ( $this->errorMsg != '' ) {
//just set the content type (don't send cache header)
header( 'Content-Type: text/javascript' );
echo 'if( typeof console !=\'undefined\' && console.log)console.log(\'Error With ResourceLoader ::' .
str_replace( "\n", '\'+"\n"+' . "\n'",
xml::escapeJsString( $this->errorMsg )
) . '\');'."\n";
echo trim( $this->output );
} else {
// All good, let's output "cache" headers
$this->outputJsWithHeaders();
}
}
/**
* Get the loadDone javascript callback for a given resource list
*
* Enables a done loading callback for browsers like older safari
* that did not consistently support the <script>.onload call
* or IE that sometimes gets undefined symbols at onload
* call time for associated script content
*
* @return String javascript to tell mwEmbed that the requested resource set is loaded
*/
static private function getOnDoneCallback( ){
return "\n" . 'if( typeof mw !=\'undefined\' && mw.loadDone ){ mw.loadDone(\'' .
htmlspecialchars( self::$rawClassList ) . '\')};';
}
/**
* Get Minified js
*
* @param {String} $js_string Javascript string to be minified
* @param {String} $requestKey Unique key for minification
* @return minified javascript value
*/
static function getMinifiedJs( & $js_string, $requestKey='' ){
global $wgJavaPath, $wgClosureCompilerPath, $wgClosureCompilerLevel;
// Check if google closure compiler is enabled and we can get its output
if( $wgJavaPath && $wgClosureCompilerPath ){
$jsMinVal = self::getClosureMinifiedJs( $js_string, $requestKey );
if( $jsMinVal ){
return $jsMinVal;
}else{
wfDebug( 'Closure compiler failed to produce code for:' . $requestKey);
}
}
// Do the minification using php JSMin
return JSMin::minify( $js_string );
}
/**
* Optional function to use the goggle closer compiler to minify js
* @param {String} $js_string Javascript string to be minified
* @param {String} $requestKey request key used for temporary name in closure compile
* @return minified js, or false if minification failed.
*/
static function getClosureMinifiedJs( & $js_string, $requestKey=''){
global $wgClosureCompilerPath, $wgJavaPath, $wgClosureCompilerLevel;
// Check the paths
if( !is_file( $wgJavaPath ) || ! is_file( $wgClosureCompilerPath ) ){
return false;
}
// Update the requestKey with a random value if not provided
// requestKey is used for the temporary file
// ( There are problems with using standard output and Closure compile )
if( $requestKey == '') {
$requestKey = rand() + microtime();
}
// Write the grouped javascript to a temporary file:
// ( closure compiler does not support reading from standard in pipe )
$td = wfTempDir();
$jsFileName = $td . '/' . md5( $requestKey ) . '.tmp.js';
file_put_contents( $jsFileName, $js_string );
$retval = '';
$cmd = $wgJavaPath . ' -jar ' . $wgClosureCompilerPath;
$cmd.= ' --js ' . $jsFileName;
if( $wgClosureCompilerLevel )
$cmd.= ' --compilation_level ' . wfEscapeShellArg( $wgClosureCompilerLevel );
// only output js ( no warnings )
$cmd.= ' --warning_level QUIET';
// Run the command:
$jsMinVal = wfShellExec($cmd , $retval);
// Clean up ( remove temporary file )
wfSuppressWarnings();
unlink( $jsFileName );
wfRestoreWarnings();
if( strlen( $jsMinVal ) != 0 && $retval === 0){
//die( "used closure" );
return $jsMinVal;
}
return false;
}
/**
* Get the javascript or css text content from a given classKey
*
* @param {String} $resourceName Resource Key to grab text for
* @param {String} [$filePath] Optional file path to get js text
* @return unknown
*/
function getResourceText( $resourceName ){
$output = '';
// Special case: title classes
if ( substr( $resourceName, 0, 3 ) == 'WT:' ) {
global $wgUser;
// Get just the title part
$titleBlock = substr( $resourceName, 3 );
if ( $titleBlock[0] == '-' ) {
// Special case of "-" title
$parts = explode( '|', $titleBlock );
$title = array_shift( $parts );
$titleParams = array ();
foreach ( $parts as $titleParam ) {
list( $key, $val ) = explode( '=', $titleParam );
$titleParams[ $key ] = $val;
}
/*
* The "-" is a special key to user / site js system sucks
* here is some code to handle it ... but it really
* should be depreciated for some more logical system
* like directly referencing the titles that we have a script-loader
*/
$sk = $wgUser->getSkin();
if( isset( $titleParams[ 'useskin' ] ) ) {
// Make sure the skin name is valid
$skinNames = Skin::getSkinNames();
$skinNames = array_keys( $skinNames );
if ( in_array( strtolower( $titleParams[ 'useskin' ] ), $skinNames ) ) {
if( $titleParams['gen' ] == 'css' ){
return $sk->generateUserStylesheet();
}
// If in debug mode, add a comment with wiki title and rev:
if ( $this->debug ) {
$output .= "\n/**\n* GenerateUserJs: \n*/\n";
}
return $sk->generateUserJs( $titleParams[ 'useskin' ] ) . "\n";
}
} else if( isset( $titleParams['gen' ] ) && $titleParams['gen' ] == 'css' ) {
return $sk->generateUserStylesheet();
}
} else {
$ext = substr($titleBlock, strrpos($titleBlock, '.') + 1);
// Make sure the wiki title ends with .js or .css
if ( self::validFileExtension( $ext ) ) {
$this->errorMsg .= 'WikiTitle includes should end with .js or .css';
return false;
}
// It's a wiki title, append the output of the wikitext:
$t = Title::newFromText( $titleBlock );
$a = new Article( $t );
// Only get the content if the page is not empty:
if ( $a->getID() !== 0 ) {
// If in debug mode, add a comment with wiki title and rev:
if ( $this->debug ) {
$output .= "\n/**\n* ScriptLoader WikiPage: " . xml::escapeJsString( $titleBlock ) . " rev: " . $a->getID() . " \n*/\n";
}
$fileContents = $a->getContent() . "\n";
// transform the output if the file is of type css:
$output.= ( $ext == 'css' ) ?
$this->transformCssOutput( $resourceName, $fileContents ) :
$fileContents;
return $output;
}
}
}
// Deal with the classKey as a file:
$filePath = self::getPathFromClass( $resourceName );
if( ! $filePath ) {
$this->errorMsg .= "\nError could not get file path: ". xml::escapeJsString( $resourceName ) ."\n";
return false;
}
// Get the file extension:
$ext = substr( $filePath, strrpos( $filePath, '.' ) + 1 );
// Dealing with files
if ( trim( $filePath ) != '' ) {
$fileContents = $this->getFileContents( $filePath ) . "\n";
if( $fileContents ){
// Add the file name if debug is enabled
if ( $this->debug ){
$output .= "\n\n/**\n* File: " . xml::escapeJsString( $filePath ) . "\n*/\n";
}
// Transform the css output if the file is css
$output.= ( $ext == 'css' ) ?
$this->transformCssOutput( $resourceName, $fileContents, $filePath ) :
$fileContents;
return $output;
}else{
$this->errorMsg .= "\nError could not read file: ". xml::escapeJsString( $filePath ) ."\n";
return false;
}
}
// If we did not return some js
$this->errorMsg .= "\nUnknown error in getting scriptText for key: " . xml::escapeJsString( $resourceName ) . "\n";
return false;
}
/**
* Special function to transform css output and wrap in js call
*/
private function transformCssOutput( $resourceName, $cssString , $path ='') {
global $wgScriptLoaderRelativeCss;
// Minify and update paths on cssString:
$cssOptions = array();
// Set comments preservation based on debug state
$cssOptions[ 'preserveComments' ] = ( $this->debug );
// Check for the two ResourceLoader entry points:
if( $wgScriptLoaderRelativeCss ) {
// Using the local mediaWiki entry point we should have our $wgScriptPath global
global $wgScriptPath;
$prePendPath = ( $wgScriptPath == '' ) ? '' : $wgScriptPath . '/';
$cssOptions[ 'prependRelativePath' ] = $prePendPath . dirname( $path ) . '/';
} else {
// Get the server URL
$serverUri = $this->getResourceLoaderUri();
$cssOptions[ 'prependRelativePath' ] = str_replace('ResourceLoader.php', '', $serverUri)
. dirname( $path ) . '/';
}
// We always run minify to update css image urls
$cssString = Minify_CSS::minify( $cssString, $cssOptions);
// Check output format ( if format is "css" ) return the css string directly
if( $this->outputFormat == 'css' ) {
return $cssString;
}
// Output Format is "javascript" return the string in an addStyleString call
// CSS classes should be of form mw.style.{className}
$cssStyleName = str_replace('mw.style.', '', $resourceName );
return 'mw.addStyleString("' . Xml::escapeJsString( $cssStyleName )
. '", "' . Xml::escapeJsString( $cssString ) . '");' . "\n";
}
/**
* Get the URI of the scriptLoader
*/
private function getResourceLoaderUri() {
// protocol is http or https
$protocol = 'http';
if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {
$protocol .= 's';
$protocol_port = $_SERVER['SERVER_PORT'];
} else {
$protocol_port = 80;
}
// $port will be "" or something like ":8100"
$port = ( $_SERVER['SERVER_PORT'] == $protocol_port ) ? '' : ':' . $_SERVER['SERVER_PORT'];
// php_self is the URL that invoked this script, without CGI parameters or fragment.
//return $protocol . '://' . $_SERVER['HTTP_HOST'] . $port . $_SERVER['PHP_SELF'];
global $wgCDNAssetPath;
return $wgCDNAssetPath. $port .$_SERVER['PHP_SELF'];
}
/**
* Outputs the script headers
*/
function outputHeaders() {
// Output MIME type:
if( $this->outputFormat == 'css' ){
header( 'Content-Type: text/css' );
} else if ( $this->outputFormat == 'js' || $this->outputFormat == 'messages' ) {
header( 'Content-Type: text/javascript' );
}
header( 'Pragma: public' );
if( $this->debug ){
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
}else{
// Cache for 30 days ( we update the request urid so this has a long expire delay )
$max_age = 86400 * 30;
header("Cache-Control: private, max-age=$max_age, max-stale=0");
header("Expires: " . gmdate( "D, d M Y H:i:s", time() + $max_age ) . " GMT" );
header("Last-Modified: " . gmdate('D, d M Y H:i:s', time()) . ' GMT');
}
}
/**
* Outputs the javascript text with script headers
*/
function outputJsWithHeaders() {
global $wgUseGzip;
$this->outputHeaders();
if ( $wgUseGzip ) {
if ( $this->clientAcceptsGzip() ) {
header( 'Content-Encoding: gzip' );
echo gzencode( $this->output );
} else {
echo $this->output;
}
} else {
echo $this->output;
}
}
/**
* Checks if client Accepts Gzip response
*
* @return boolean
* true if client accepts gzip encoded response
* false if client does not accept gzip encoded response
*/
static function clientAcceptsGzip() {
$m = array();
if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ){
if( preg_match(
'/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
$_SERVER['HTTP_ACCEPT_ENCODING'],
$m ) ) {
if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) )
return false;
//no gzip support found
return true;
}
}
return false;
}
/**
* Post process request uses globals and mediaWiki configuration to
* validate classes and generate request key
*/
function postProcRequestVars(){
global $wgContLanguageCode, $wgResourceLoaderNamedPaths,
$wgStyleVersion;
// Set debug flag
if ( ( isset( $_GET['debug'] ) && $_GET['debug'] == 'true' )
|| ( isset( $wgEnableScriptDebug ) && $wgEnableScriptDebug == true ) ) {
$this->debug = true;
}
// Set the urid. Be sure to escape it as it goes into our JS output.
if ( isset( $_GET['urid'] ) && $_GET['urid'] != '' ) {
$this->urid = htmlspecialchars( $_GET['urid'] );
} else {
// Just give it the current style sheet ID:
// NOTE: read the svn version number
$this->urid = $wgStyleVersion;
}
// Get the language code (if not provided use the "default" language
if ( isset( $_GET['uselang'] ) && $_GET['uselang'] != '' ) {
// Strip any non alphaNumeric or dash characters from the language code:
$this->langCode = preg_replace( "/[^A-Za-z\-_]/", '', $_GET['uselang']);
}else{
//set English as default
$this->langCode = 'en';
}
$this->langCode = self::checkForCommonsLanguageFormHack( $this->langCode );
$reqClassList = false;
if ( isset( $_GET['class'] ) && $_GET['class'] != '' ) {
$reqClassList = explode( ',', $_GET['class'] );
self::$rawClassList = $_GET['class'];
}
// Check for the requested classes
if ( $reqClassList ) {
// sanitize the Resource list and populate namedFileList
foreach ( $reqClassList as $reqClass ) {
if ( trim( $reqClass ) != '' ) {
if ( substr( $reqClass, 0, 3 ) == 'WT:' ) {
$doAddWT = false;
// Check for special case '-' resource for user-generated JS
if( substr( $reqClass, 3, 1) == '-'){
$doAddWT = true;
}else{
if( strtolower( substr( $reqClass, -3) ) == '.js'){
//make sure its a valid wikipage before doing processing
$t = Title::newFromDBkey( substr( $reqClass, 3) );
if( $t->exists()
&& ( $t->getNamespace() == NS_MEDIAWIKI
|| $t->getNamespace() == NS_USER ) ){
$doAddWT = true;
}
}
}
if( $doAddWT ){
$this->namedFileList[$reqClass] = true;
$this->requestKey .= $reqClass;
$this->jsvarurl = true;
}
continue;
}
$reqClass = preg_replace( "/[^A-Za-z0-9_\-\.]/", '', $reqClass );
$filePath = self::getPathFromClass( $reqClass );
if( !$filePath ){
$this->errorMsg .= 'Requested class: ' . xml::escapeJsString( $reqClass ) . ' not found' . "\n";
}else{
$this->namedFileList[ $reqClass ] = $filePath;
$this->requestKey .= $reqClass;
}
}
}
}
// Add the language code to the requestKey:
$this->requestKey .= '_' . $wgContLanguageCode;
// Add the unique rid
$this->requestKey .= $this->urid;
}
/**
* Pre-process request variables ~without configuration~ or any utility functions.
*
* This is to quickly get a requestKey that we can check against the cache,
* request key validation is done in postProcRequestVars
*/
function preProcRequestVars() {
$requestKey = '';
// Update the outupt format is "css", "messages" or "js"
if( isset( $_GET['format'] ) &&
( $_GET['format'] == 'css' || $_GET['format'] == 'messages')
){
$this->outputFormat = $_GET['format'];
} else {
$this->outputFormat = 'js';
}
// Check for debug ( won't use the cache)
if ( ( isset( $_GET['debug'] ) && $_GET['debug'] == 'true' ) ) {
// We are going to have to run postProcRequest
return false;
}
// Check for the urid. Be sure to escape it as it goes into our JS output.
if ( isset( $_GET['urid'] ) && $_GET['urid'] != '' ) {
$urid = htmlspecialchars( $_GET['urid'] );
}else{
// If no urid is set use special "cache" version.
// (this requires that the cache files be removed for updates to take effect.)
$urid = 'cache';
}
// Get the language code (if not provided use the "default" language
if ( isset( $_GET['uselang'] ) && $_GET['uselang'] != '' ) {
// Make sure its just a simple [A-Za-z] value
$langCode = preg_replace( "/[^A-Za-z_]/", '', $_GET['uselang']);
}else{
// Set English as default
$langCode = 'en';
}
$langCode = self::checkForCommonsLanguageFormHack( $langCode );
$reqClassList = false;
if ( isset( $_GET['class'] ) && $_GET['class'] != '' ) {
$reqClassList = explode( ',', $_GET['class'] );
}
// Check for the requested classes
if ( $reqClassList && count( $reqClassList ) > 0 ) {
// Clean the resource list and populate namedFileList
foreach ( $reqClassList as $reqClass ) {
//do some simple checks:
if ( trim( $reqClass ) != '' ){
if( substr( $reqClass, 0, 3 ) == 'WT:' && strtolower( substr( $reqClass, -3) ) == '.js' ){
// Wiki page requests (must end with .js):
$requestKey .= $reqClass;
}else if( substr( $reqClass, 0, 3 ) != 'WT:' ){
// Normal resource requests:
$reqClass = preg_replace( "/[^A-Za-z0-9_\-\.]/", '', $reqClass );
$requestKey .= $reqClass;
}else{
// Not a valid class
}
}
}
}
// Add the language code to the requestKey:
$requestKey .= '_' . $langCode;
// Add the format to the requestKey:
$requestKey .= '_' . $this->outputFormat;
// Add the unique rid
$requestKey .= '_' . $urid;
return $requestKey;
}
/**
* Check for the commons language hack.
* ( someone had the bright idea to use language keys as message
* name-spaces for separate upload forms )
*
* @param {String} $langKey The lang key for the form
*/
public static function checkForCommonsLanguageFormHack( $langKey){
$formNames = array( 'ownwork', 'fromflickr', 'fromwikimedia', 'fromgov');
foreach( $formNames as $formName ){
// Directly reference a form Name then its "english"
if( $formName == $langKey ){
return 'en';
}
// If the langKey includes a form name (ie esownwork or es-ownwork)
// then strip the form name use that as the language key
if( strpos($langKey, $formName) !==false ){
$langKey = str_replace($formName, '', $langKey);
//English wikipedia puts "-" after language keys remove that:
if( $langKey[ strlen( $langKey ) - 1 ] == '-'){
$langKey = substr( $langKey, 0, strlen( $langKey ) - 1 );
}
return $langKey;
}
}
// Else just return the key unchanged:
return $langKey;
}
/**
* Get a file path for a given class
*
* @param {String} $reqClass Resource key to get the path for
* @return path of the resource or "false"
*/
public static function getPathFromClass( $reqClass ){
global $wgResourceLoaderNamedPaths;
// Make sure the resource is loaded:
try {
NamedResourceLoader::loadResourcePaths();
} catch( Exception $e ) {
$this->errorMsg .= "getPathFromClass: " . $e->getMessage() ;
}
if ( isset( $wgResourceLoaderNamedPaths[ $reqClass ] ) ) {
return $wgResourceLoaderNamedPaths[ $reqClass ];
} else {
return false;
}
}
// Check that the filename ends with .js or .css
function validFileExtension( $ext ){
return !( $ext == 'js' || $ext == 'css');
}
/**
* Retrieve the js or css file into a string, updates errorMsg if not retrievable.
*
* @param {String} $filePath File to get
* @return {String} of the file contents
*/
function getFileContents( $filePath ) {
global $IP;
$ext = substr($filePath, strrpos($filePath, '.') + 1);
if ( self::validFileExtension( $ext) ) {
$this->errorMsg .= "\nError file name must end with .js or .css " . htmlspecialchars( $filePath ) . " \n ";
return false;
}
// Check the file does not include ../ traversing
if ( strpos( $filePath, '../' ) !== false ) {
$this->errorMsg .= "\nError file name must not traverse paths: " . htmlspecialchars( $filePath ) . " \n ";
return false;
}
// Load the file
wfSuppressWarnings();
$fileContents = file_get_contents( realpath( $filePath ) );
wfRestoreWarnings();
if ( $fileContents === false ) {
$fname = explode( '/',$filePath);
$fname = end( $fname );
// NOTE: check PHP error level. Don't want to expose paths if errors are hidden.
$this->errorMsg .= 'Requested File: ' . htmlspecialchars( $filePath ) . ' could not be read' . "\n";
return false;
}
return $fileContents;
}
/**
* Get a localized script javascript
*
* Strips debug statements: mw.log( 'msg' );
* Localizes the javascript calling the languageMsgReplace function
*
* @param {String} $resourceName Name of resource to be processed.
* @return processed javascript string
*/
function getLocalizedScriptText( $resourceName ){
global $wgEnableScriptLocalization;
// Get the script text:
$scriptText = $this->getResourceText( $resourceName );
if( !$scriptText ) {
// Specific error already reported in getResourceText()
return '';
}
$moduleName = NamedResourceLoader::getModuleNameForResource( $resourceName );
$scriptText = $this->transformScriptText( $scriptText, $moduleName );
// Return the js string unmodified if we did not transform with the localisation.
return $scriptText;
}
/*
* Transform script text with language key substitution
* and clear out debug lines if present.
* @param {String} $scriptText Text string to be transformed
*/
function transformScriptText( $scriptText , $moduleName){
global $wgEnableScriptLocalization;
// Strip out mw.log debug lines (if not in debug mode)
if( !$this->debug ){
$scriptText = $this->removeLogStatements( $scriptText );
}
// Do language swap by index:
if ( $wgEnableScriptLocalization ){
// NOTE getResourceMessageJS could identify which mode we are in and we would not need to
// try each of these search patterns in the same order as before.
// Get the mw.addMessage javascript
self::$addMessageJs = $this->getAddMessagesFromScriptText( $scriptText , $moduleName);
// Check for mw.includeAllModuleMsgs() call to be replaced with all the msgs
// Use preg_replace_callback to avoid back-refrence substitution
$scriptText = preg_replace_callback(
self::$includeAllMsgsRegEx,
'ResourceLoader::preg_addMessageJs',
$scriptText,
1,
$count
);
if( $count != 0 ){
return $scriptText;
}
// Replace mw.addMessages with localized msgs in javascript string
$inx = self::getAddMessagesIndex( $scriptText );
if( $inx ){
// Return the final string (without double {})
return substr($scriptText, 0, $inx['sfull']) . self::$addMessageJs . substr($scriptText, $inx['efull']);
}
// Replace mw.addMessageKeys with localized msgs in javascript string
$inx = self::getAddMessageKeyIndex( $scriptText );
if( $inx ) {
// Return the final string (without double {})
return substr( $scriptText, 0, $inx['sfull'] ). self::$addMessageJs . substr($scriptText, $inx['efull']);
}
}
// Return the javascript str unmodified if we did not transform with the localisation
return $scriptText;
}
/**
* Remove all occurances of mw.log( 'some js string or expresion' );
* @param {string} $jsString
*/
static function removeLogStatements( $jsString ){
$outputJs = '';
for ( $i = 0; $i < strlen( $jsString ); $i++ ) {
// find next occurrence of
preg_match( '/([\n;]\s*mw\.log\s*)\(/', $jsString, $matches, PREG_OFFSET_CAPTURE, $i );
// check if any matches are left:
if( count( $matches ) == 0){
$outputJs .= substr( $jsString, $i );
break;
}
if( count( $matches ) > 0 ){
$startOfLogIndex = strlen( $matches[1][0] ) + $matches[1][1];
// append everything up to this point:
$outputJs .= substr( $jsString, $i, ( $startOfLogIndex - strlen( $matches[1][0] ) )-$i );
// Increment i to position of closing ) not inside quotes
$parenthesesDepth = 0;
$ignorenext = false;
$inquote = false;
$inSingleQuote = false;
for ( $i = $startOfLogIndex; $i < strlen( $jsString ); $i++ ) {
$char = $jsString[$i];
if ( $ignorenext ) {
$ignorenext = false;
} else {
// Search for a close ) that is not in quotes
switch( $char ) {
case '"':
if( !$inSingleQuote ){
$inquote = !$inquote;
}
break;
case '\'':
if( !$inquote ){
$inSingleQuote = !$inSingleQuote;
}
break;
case '(':
if( !$inquote && !$inSingleQuote ){
$parenthesesDepth++;
}
break;
case ')':
if( ! $inquote && !$inSingleQuote ){
$parenthesesDepth--;
}
break;
case '\\':
if ( $inquote ) $ignorenext = true;
break;
}
// Done with close parentheses search for next mw.log in outer loop:
if( $parenthesesDepth === 0 ){
break;
}
}
}
}
}
return $outputJs;
}
/* simple function to return addMessageJs without preg_replace back reference substitution */
private static function preg_addMessageJs(){
return self::$addMessageJs;
}
/**
* Get the "addMesseges" function index ( for replacing msg text with localized json )
*
* @param {String} $str Javascript string to grab msg text from
* @return {Array} Array with start and end points character indexes
*/
static public function getAddMessagesIndex( $str ){
$returnIndex = array();
preg_match( '/mw.addMessages\s*\(\s*\{/', $str, $matches, PREG_OFFSET_CAPTURE );
if( count($matches) == 0){
return false;
}
if( count( $matches ) > 0 ){
//offset + match str length gives startIndex:
$returnIndex['s'] = strlen( $matches[0][0] ) + $matches[0][1];
// Also store the full replacement index
$returnIndex['sfull'] = $matches[0][1];
}
$ignorenext = false;
$inquote = false;
// Look for closing } not inside quotes::
for ( $i = $returnIndex['s']; $i < strlen( $str ); $i++ ) {
$char = $str[$i];
if ( $ignorenext ) {
$ignorenext = false;
} else {
// Search for a close } that is not in quotes or escaped
switch( $char ) {
case '"':
$inquote = !$inquote;
break;
case '}':
if( ! $inquote){
$returnIndex['e'] = $i;
}
break;
case '\\':
if ( $inquote ) $ignorenext = true;
break;
}
}
// If return index is set break out
if( isset( $returnIndex['e'] ) ) {
break;
}
}
// Check for ); at the end
preg_match( '/\s*\)\s*\;?/', $str, $matches, PREG_OFFSET_CAPTURE, $returnIndex['e'] );
if( $matches[0][1] ){
$returnIndex[ 'efull' ] = $matches[0][1] + strlen( $matches[0][0] );
}
return $returnIndex;
}
/**
* Get the "addMessageKey" function index ( for replacing msg keys with localized json addMessage call)
*
* @param {String} $str Javascript string to grab msg text from
* @return {Array} Array with start and end points character indexes
*/
static public function getAddMessageKeyIndex( $str ){