Merge "Changed quoting function for oracleDB."
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
1 <?php
2 /**
3 * Base class for resource loading system.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Roan Kattouw
22 * @author Trevor Parscal
23 */
24
25 /**
26 * Dynamic JavaScript and CSS resource loading system.
27 *
28 * Most of the documention is on the MediaWiki documentation wiki starting at:
29 * http://www.mediawiki.org/wiki/ResourceLoader
30 */
31 class ResourceLoader {
32
33 /* Protected Static Members */
34 protected static $filterCacheVersion = 7;
35 protected static $requiredSourceProperties = array( 'loadScript' );
36
37 /** Array: List of module name/ResourceLoaderModule object pairs */
38 protected $modules = array();
39
40 /** Associative array mapping module name to info associative array */
41 protected $moduleInfos = array();
42
43 /** Associative array mapping framework ids to a list of names of test suite modules */
44 /** like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. ) */
45 protected $testModuleNames = array();
46
47 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
48 protected $sources = array();
49
50 /** @var bool */
51 protected $hasErrors = false;
52
53 /* Protected Methods */
54
55 /**
56 * Loads information stored in the database about modules.
57 *
58 * This method grabs modules dependencies from the database and updates modules
59 * objects.
60 *
61 * This is not inside the module code because it is much faster to
62 * request all of the information at once than it is to have each module
63 * requests its own information. This sacrifice of modularity yields a substantial
64 * performance improvement.
65 *
66 * @param array $modules List of module names to preload information for
67 * @param $context ResourceLoaderContext: Context to load the information within
68 */
69 public function preloadModuleInfo( array $modules, ResourceLoaderContext $context ) {
70 if ( !count( $modules ) ) {
71 return; // or else Database*::select() will explode, plus it's cheaper!
72 }
73 $dbr = wfGetDB( DB_SLAVE );
74 $skin = $context->getSkin();
75 $lang = $context->getLanguage();
76
77 // Get file dependency information
78 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
79 'md_module' => $modules,
80 'md_skin' => $skin
81 ), __METHOD__
82 );
83
84 // Set modules' dependencies
85 $modulesWithDeps = array();
86 foreach ( $res as $row ) {
87 $this->getModule( $row->md_module )->setFileDependencies( $skin,
88 FormatJson::decode( $row->md_deps, true )
89 );
90 $modulesWithDeps[] = $row->md_module;
91 }
92
93 // Register the absence of a dependency row too
94 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
95 $this->getModule( $name )->setFileDependencies( $skin, array() );
96 }
97
98 // Get message blob mtimes. Only do this for modules with messages
99 $modulesWithMessages = array();
100 foreach ( $modules as $name ) {
101 if ( count( $this->getModule( $name )->getMessages() ) ) {
102 $modulesWithMessages[] = $name;
103 }
104 }
105 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
106 if ( count( $modulesWithMessages ) ) {
107 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
108 'mr_resource' => $modulesWithMessages,
109 'mr_lang' => $lang
110 ), __METHOD__
111 );
112 foreach ( $res as $row ) {
113 $this->getModule( $row->mr_resource )->setMsgBlobMtime( $lang,
114 wfTimestamp( TS_UNIX, $row->mr_timestamp ) );
115 unset( $modulesWithoutMessages[$row->mr_resource] );
116 }
117 }
118 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
119 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
120 }
121 }
122
123 /**
124 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
125 *
126 * Available filters are:
127 * - minify-js \see JavaScriptMinifier::minify
128 * - minify-css \see CSSMin::minify
129 *
130 * If $data is empty, only contains whitespace or the filter was unknown,
131 * $data is returned unmodified.
132 *
133 * @param string $filter Name of filter to run
134 * @param string $data Text to filter, such as JavaScript or CSS text
135 * @return String: Filtered data, or a comment containing an error message
136 */
137 protected function filter( $filter, $data ) {
138 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
139 wfProfileIn( __METHOD__ );
140
141 // For empty/whitespace-only data or for unknown filters, don't perform
142 // any caching or processing
143 if ( trim( $data ) === ''
144 || !in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
145 {
146 wfProfileOut( __METHOD__ );
147 return $data;
148 }
149
150 // Try for cache hit
151 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
152 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self::$filterCacheVersion, md5( $data ) );
153 $cache = wfGetCache( CACHE_ANYTHING );
154 $cacheEntry = $cache->get( $key );
155 if ( is_string( $cacheEntry ) ) {
156 wfProfileOut( __METHOD__ );
157 return $cacheEntry;
158 }
159
160 $result = '';
161 // Run the filter - we've already verified one of these will work
162 try {
163 switch ( $filter ) {
164 case 'minify-js':
165 $result = JavaScriptMinifier::minify( $data,
166 $wgResourceLoaderMinifierStatementsOnOwnLine,
167 $wgResourceLoaderMinifierMaxLineLength
168 );
169 $result .= "\n/* cache key: $key */";
170 break;
171 case 'minify-css':
172 $result = CSSMin::minify( $data );
173 $result .= "\n/* cache key: $key */";
174 break;
175 }
176
177 // Save filtered text to Memcached
178 $cache->set( $key, $result );
179 } catch ( Exception $exception ) {
180 $exception->logException();
181 wfDebugLog( 'resourceloader', __METHOD__ . ": minification failed: $exception" );
182 $this->hasErrors = true;
183 // Return exception as a comment
184 $result = self::formatException( $exception );
185 }
186
187 wfProfileOut( __METHOD__ );
188
189 return $result;
190 }
191
192 /* Methods */
193
194 /**
195 * Registers core modules and runs registration hooks.
196 */
197 public function __construct() {
198 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript, $wgEnableJavaScriptTest;
199
200 wfProfileIn( __METHOD__ );
201
202 // Add 'local' source first
203 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
204
205 // Add other sources
206 $this->addSource( $wgResourceLoaderSources );
207
208 // Register core modules
209 $this->register( include "$IP/resources/Resources.php" );
210 // Register extension modules
211 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
212 $this->register( $wgResourceModules );
213
214 if ( $wgEnableJavaScriptTest === true ) {
215 $this->registerTestModules();
216 }
217
218 wfProfileOut( __METHOD__ );
219 }
220
221 /**
222 * Registers a module with the ResourceLoader system.
223 *
224 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
225 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
226 * this may also be a ResourceLoaderModule object. Optional when using
227 * multiple-registration calling style.
228 * @throws MWException: If a duplicate module registration is attempted
229 * @throws MWException: If a module name contains illegal characters (pipes or commas)
230 * @throws MWException: If something other than a ResourceLoaderModule is being registered
231 * @return Boolean: False if there were any errors, in which case one or more modules were not
232 * registered
233 */
234 public function register( $name, $info = null ) {
235 wfProfileIn( __METHOD__ );
236
237 // Allow multiple modules to be registered in one call
238 $registrations = is_array( $name ) ? $name : array( $name => $info );
239 foreach ( $registrations as $name => $info ) {
240 // Disallow duplicate registrations
241 if ( isset( $this->moduleInfos[$name] ) ) {
242 wfProfileOut( __METHOD__ );
243 // A module has already been registered by this name
244 throw new MWException(
245 'ResourceLoader duplicate registration error. ' .
246 'Another module has already been registered as ' . $name
247 );
248 }
249
250 // Check $name for validity
251 if ( !self::isValidModuleName( $name ) ) {
252 wfProfileOut( __METHOD__ );
253 throw new MWException( "ResourceLoader module name '$name' is invalid, see ResourceLoader::isValidModuleName()" );
254 }
255
256 // Attach module
257 if ( is_object( $info ) ) {
258 // Old calling convention
259 // Validate the input
260 if ( !( $info instanceof ResourceLoaderModule ) ) {
261 wfProfileOut( __METHOD__ );
262 throw new MWException( 'ResourceLoader invalid module error. ' .
263 'Instances of ResourceLoaderModule expected.' );
264 }
265
266 $this->moduleInfos[$name] = array( 'object' => $info );
267 $info->setName( $name );
268 $this->modules[$name] = $info;
269 } else {
270 // New calling convention
271 $this->moduleInfos[$name] = $info;
272 }
273 }
274
275 wfProfileOut( __METHOD__ );
276 }
277
278 /**
279 */
280 public function registerTestModules() {
281 global $IP, $wgEnableJavaScriptTest;
282
283 if ( $wgEnableJavaScriptTest !== true ) {
284 throw new MWException( 'Attempt to register JavaScript test modules but <code>$wgEnableJavaScriptTest</code> is false. Edit your <code>LocalSettings.php</code> to enable it.' );
285 }
286
287 wfProfileIn( __METHOD__ );
288
289 // Get core test suites
290 $testModules = array();
291 $testModules['qunit'] = include "$IP/tests/qunit/QUnitTestResources.php";
292 // Get other test suites (e.g. from extensions)
293 wfRunHooks( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
294
295 // Add the testrunner (which configures QUnit) to the dependencies.
296 // Since it must be ready before any of the test suites are executed.
297 foreach ( $testModules['qunit'] as &$module ) {
298 // Make sure all test modules are top-loading so that when QUnit starts
299 // on document-ready, it will run once and finish. If some tests arrive
300 // later (possibly after QUnit has already finished) they will be ignored.
301 $module['position'] = 'top';
302 $module['dependencies'][] = 'mediawiki.tests.qunit.testrunner';
303 }
304
305 foreach ( $testModules as $id => $names ) {
306 // Register test modules
307 $this->register( $testModules[$id] );
308
309 // Keep track of their names so that they can be loaded together
310 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
311 }
312
313 wfProfileOut( __METHOD__ );
314 }
315
316 /**
317 * Add a foreign source of modules.
318 *
319 * Source properties:
320 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
321 *
322 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
323 * @param array $properties source properties
324 * @throws MWException
325 */
326 public function addSource( $id, $properties = null ) {
327 // Allow multiple sources to be registered in one call
328 if ( is_array( $id ) ) {
329 foreach ( $id as $key => $value ) {
330 $this->addSource( $key, $value );
331 }
332 return;
333 }
334
335 // Disallow duplicates
336 if ( isset( $this->sources[$id] ) ) {
337 throw new MWException(
338 'ResourceLoader duplicate source addition error. ' .
339 'Another source has already been registered as ' . $id
340 );
341 }
342
343 // Validate properties
344 foreach ( self::$requiredSourceProperties as $prop ) {
345 if ( !isset( $properties[$prop] ) ) {
346 throw new MWException( "Required property $prop missing from source ID $id" );
347 }
348 }
349
350 $this->sources[$id] = $properties;
351 }
352
353 /**
354 * Get a list of module names
355 *
356 * @return Array: List of module names
357 */
358 public function getModuleNames() {
359 return array_keys( $this->moduleInfos );
360 }
361
362 /**
363 * Get a list of test module names for one (or all) frameworks.
364 * If the given framework id is unknkown, or if the in-object variable is not an array,
365 * then it will return an empty array.
366 *
367 * @param string $framework Optional. Get only the test module names for one
368 * particular framework.
369 * @return Array
370 */
371 public function getTestModuleNames( $framework = 'all' ) {
372 /// @todo api siteinfo prop testmodulenames modulenames
373 if ( $framework == 'all' ) {
374 return $this->testModuleNames;
375 } elseif ( isset( $this->testModuleNames[$framework] ) && is_array( $this->testModuleNames[$framework] ) ) {
376 return $this->testModuleNames[$framework];
377 } else {
378 return array();
379 }
380 }
381
382 /**
383 * Get the ResourceLoaderModule object for a given module name.
384 *
385 * @param string $name Module name
386 * @return ResourceLoaderModule if module has been registered, null otherwise
387 */
388 public function getModule( $name ) {
389 if ( !isset( $this->modules[$name] ) ) {
390 if ( !isset( $this->moduleInfos[$name] ) ) {
391 // No such module
392 return null;
393 }
394 // Construct the requested object
395 $info = $this->moduleInfos[$name];
396 /** @var ResourceLoaderModule $object */
397 if ( isset( $info['object'] ) ) {
398 // Object given in info array
399 $object = $info['object'];
400 } else {
401 if ( !isset( $info['class'] ) ) {
402 $class = 'ResourceLoaderFileModule';
403 } else {
404 $class = $info['class'];
405 }
406 $object = new $class( $info );
407 }
408 $object->setName( $name );
409 $this->modules[$name] = $object;
410 }
411
412 return $this->modules[$name];
413 }
414
415 /**
416 * Get the list of sources
417 *
418 * @return Array: array( id => array of properties, .. )
419 */
420 public function getSources() {
421 return $this->sources;
422 }
423
424 /**
425 * Outputs a response to a resource load-request, including a content-type header.
426 *
427 * @param $context ResourceLoaderContext: Context in which a response should be formed
428 */
429 public function respond( ResourceLoaderContext $context ) {
430 global $wgCacheEpoch, $wgUseFileCache;
431
432 // Use file cache if enabled and available...
433 if ( $wgUseFileCache ) {
434 $fileCache = ResourceFileCache::newFromContext( $context );
435 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
436 return; // output handled
437 }
438 }
439
440 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
441 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
442 // is used: ob_clean() will clear the GZIP header in that case and it won't come
443 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
444 // the whole thing in our own output buffer to be sure the active buffer
445 // doesn't use ob_gzhandler.
446 // See http://bugs.php.net/bug.php?id=36514
447 ob_start();
448
449 wfProfileIn( __METHOD__ );
450 $errors = '';
451
452 // Split requested modules into two groups, modules and missing
453 $modules = array();
454 $missing = array();
455 foreach ( $context->getModules() as $name ) {
456 if ( isset( $this->moduleInfos[$name] ) ) {
457 $module = $this->getModule( $name );
458 // Do not allow private modules to be loaded from the web.
459 // This is a security issue, see bug 34907.
460 if ( $module->getGroup() === 'private' ) {
461 wfDebugLog( 'resourceloader', __METHOD__ . ": request for private module '$name' denied" );
462 $this->hasErrors = true;
463 // Add exception to the output as a comment
464 $errors .= self::makeComment( "Cannot show private module \"$name\"" );
465
466 continue;
467 }
468 $modules[$name] = $module;
469 } else {
470 $missing[] = $name;
471 }
472 }
473
474 // Preload information needed to the mtime calculation below
475 try {
476 $this->preloadModuleInfo( array_keys( $modules ), $context );
477 } catch ( Exception $e ) {
478 $e->logException();
479 wfDebugLog( 'resourceloader', __METHOD__ . ": preloading module info failed: $e" );
480 $this->hasErrors = true;
481 // Add exception to the output as a comment
482 $errors .= self::formatException( $e );
483 }
484
485 wfProfileIn( __METHOD__ . '-getModifiedTime' );
486
487 // To send Last-Modified and support If-Modified-Since, we need to detect
488 // the last modified time
489 $mtime = wfTimestamp( TS_UNIX, $wgCacheEpoch );
490 foreach ( $modules as $module ) {
491 /**
492 * @var $module ResourceLoaderModule
493 */
494 try {
495 // Calculate maximum modified time
496 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
497 } catch ( Exception $e ) {
498 $e->logException();
499 wfDebugLog( 'resourceloader', __METHOD__ . ": calculating maximum modified time failed: $e" );
500 $this->hasErrors = true;
501 // Add exception to the output as a comment
502 $errors .= self::formatException( $e );
503 }
504 }
505
506 wfProfileOut( __METHOD__ . '-getModifiedTime' );
507
508 // If there's an If-Modified-Since header, respond with a 304 appropriately
509 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
510 wfProfileOut( __METHOD__ );
511 return; // output handled (buffers cleared)
512 }
513
514 // Generate a response
515 $response = $this->makeModuleResponse( $context, $modules, $missing );
516
517 // Prepend comments indicating exceptions
518 $response = $errors . $response;
519
520 // Capture any PHP warnings from the output buffer and append them to the
521 // response in a comment if we're in debug mode.
522 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
523 $response = self::makeComment( $warnings ) . $response;
524 $this->hasErrors = true;
525 }
526
527 // Save response to file cache unless there are errors
528 if ( isset( $fileCache ) && !$errors && !$missing ) {
529 // Cache single modules...and other requests if there are enough hits
530 if ( ResourceFileCache::useFileCache( $context ) ) {
531 if ( $fileCache->isCacheWorthy() ) {
532 $fileCache->saveText( $response );
533 } else {
534 $fileCache->incrMissesRecent( $context->getRequest() );
535 }
536 }
537 }
538
539 // Send content type and cache related headers
540 $this->sendResponseHeaders( $context, $mtime, $this->hasErrors );
541
542 // Remove the output buffer and output the response
543 ob_end_clean();
544 echo $response;
545
546 wfProfileOut( __METHOD__ );
547 }
548
549 /**
550 * Send content type and last modified headers to the client.
551 * @param $context ResourceLoaderContext
552 * @param string $mtime TS_MW timestamp to use for last-modified
553 * @param bool $errors Whether there are commented-out errors in the response
554 * @return void
555 */
556 protected function sendResponseHeaders( ResourceLoaderContext $context, $mtime, $errors ) {
557 global $wgResourceLoaderMaxage;
558 // If a version wasn't specified we need a shorter expiry time for updates
559 // to propagate to clients quickly
560 // If there were errors, we also need a shorter expiry time so we can recover quickly
561 if ( is_null( $context->getVersion() ) || $errors ) {
562 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
563 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
564 // If a version was specified we can use a longer expiry time since changing
565 // version numbers causes cache misses
566 } else {
567 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
568 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
569 }
570 if ( $context->getOnly() === 'styles' ) {
571 header( 'Content-Type: text/css; charset=utf-8' );
572 header( 'Access-Control-Allow-Origin: *' );
573 } else {
574 header( 'Content-Type: text/javascript; charset=utf-8' );
575 }
576 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $mtime ) );
577 if ( $context->getDebug() ) {
578 // Do not cache debug responses
579 header( 'Cache-Control: private, no-cache, must-revalidate' );
580 header( 'Pragma: no-cache' );
581 } else {
582 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
583 $exp = min( $maxage, $smaxage );
584 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
585 }
586 }
587
588 /**
589 * If there's an If-Modified-Since header, respond with a 304 appropriately
590 * and clear out the output buffer. If the client cache is too old then do nothing.
591 * @param $context ResourceLoaderContext
592 * @param string $mtime The TS_MW timestamp to check the header against
593 * @return bool True iff 304 header sent and output handled
594 */
595 protected function tryRespondLastModified( ResourceLoaderContext $context, $mtime ) {
596 // If there's an If-Modified-Since header, respond with a 304 appropriately
597 // Some clients send "timestamp;length=123". Strip the part after the first ';'
598 // so we get a valid timestamp.
599 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
600 // Never send 304s in debug mode
601 if ( $ims !== false && !$context->getDebug() ) {
602 $imsTS = strtok( $ims, ';' );
603 if ( $mtime <= wfTimestamp( TS_UNIX, $imsTS ) ) {
604 // There's another bug in ob_gzhandler (see also the comment at
605 // the top of this function) that causes it to gzip even empty
606 // responses, meaning it's impossible to produce a truly empty
607 // response (because the gzip header is always there). This is
608 // a problem because 304 responses have to be completely empty
609 // per the HTTP spec, and Firefox behaves buggily when they're not.
610 // See also http://bugs.php.net/bug.php?id=51579
611 // To work around this, we tear down all output buffering before
612 // sending the 304.
613 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
614
615 header( 'HTTP/1.0 304 Not Modified' );
616 header( 'Status: 304 Not Modified' );
617 return true;
618 }
619 }
620 return false;
621 }
622
623 /**
624 * Send out code for a response from file cache if possible
625 *
626 * @param $fileCache ResourceFileCache: Cache object for this request URL
627 * @param $context ResourceLoaderContext: Context in which to generate a response
628 * @return bool If this found a cache file and handled the response
629 */
630 protected function tryRespondFromFileCache(
631 ResourceFileCache $fileCache, ResourceLoaderContext $context
632 ) {
633 global $wgResourceLoaderMaxage;
634 // Buffer output to catch warnings.
635 ob_start();
636 // Get the maximum age the cache can be
637 $maxage = is_null( $context->getVersion() )
638 ? $wgResourceLoaderMaxage['unversioned']['server']
639 : $wgResourceLoaderMaxage['versioned']['server'];
640 // Minimum timestamp the cache file must have
641 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
642 if ( !$good ) {
643 try { // RL always hits the DB on file cache miss...
644 wfGetDB( DB_SLAVE );
645 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
646 $good = $fileCache->isCacheGood(); // cache existence check
647 }
648 }
649 if ( $good ) {
650 $ts = $fileCache->cacheTimestamp();
651 // Send content type and cache headers
652 $this->sendResponseHeaders( $context, $ts, false );
653 // If there's an If-Modified-Since header, respond with a 304 appropriately
654 if ( $this->tryRespondLastModified( $context, $ts ) ) {
655 return false; // output handled (buffers cleared)
656 }
657 $response = $fileCache->fetchText();
658 // Capture any PHP warnings from the output buffer and append them to the
659 // response in a comment if we're in debug mode.
660 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
661 $response = "/*\n$warnings\n*/\n" . $response;
662 }
663 // Remove the output buffer and output the response
664 ob_end_clean();
665 echo $response . "\n/* Cached {$ts} */";
666 return true; // cache hit
667 }
668 // Clear buffer
669 ob_end_clean();
670
671 return false; // cache miss
672 }
673
674 /**
675 * Generate a CSS or JS comment block. Only use this for public data,
676 * not error message details.
677 *
678 * @param $text string
679 * @return string
680 */
681 public static function makeComment( $text ) {
682 $encText = str_replace( '*/', '* /', $text );
683 return "/*\n$encText\n*/\n";
684 }
685
686 /**
687 * Handle exception display
688 *
689 * @param Exception $e to be shown to the user
690 * @return string sanitized text that can be returned to the user
691 */
692 public static function formatException( $e ) {
693 global $wgShowExceptionDetails;
694
695 if ( $wgShowExceptionDetails ) {
696 return self::makeComment( $e->__toString() );
697 } else {
698 return self::makeComment( wfMessage( 'internalerror' )->text() );
699 }
700 }
701
702 /**
703 * Generates code for a response
704 *
705 * @param $context ResourceLoaderContext: Context in which to generate a response
706 * @param array $modules List of module objects keyed by module name
707 * @param array $missing List of unavailable modules (optional)
708 * @return String: Response data
709 */
710 public function makeModuleResponse( ResourceLoaderContext $context,
711 array $modules, $missing = array()
712 ) {
713 $out = '';
714 $exceptions = '';
715 if ( $modules === array() && $missing === array() ) {
716 return '/* No modules requested. Max made me put this here */';
717 }
718
719 wfProfileIn( __METHOD__ );
720 // Pre-fetch blobs
721 if ( $context->shouldIncludeMessages() ) {
722 try {
723 $blobs = MessageBlobStore::get( $this, $modules, $context->getLanguage() );
724 } catch ( Exception $e ) {
725 $e->logException();
726 wfDebugLog( 'resourceloader', __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e" );
727 $this->hasErrors = true;
728 // Add exception to the output as a comment
729 $exceptions .= self::formatException( $e );
730 }
731 } else {
732 $blobs = array();
733 }
734
735 // Generate output
736 $isRaw = false;
737 foreach ( $modules as $name => $module ) {
738 /**
739 * @var $module ResourceLoaderModule
740 */
741
742 wfProfileIn( __METHOD__ . '-' . $name );
743 try {
744 $scripts = '';
745 if ( $context->shouldIncludeScripts() ) {
746 // If we are in debug mode, we'll want to return an array of URLs if possible
747 // However, we can't do this if the module doesn't support it
748 // We also can't do this if there is an only= parameter, because we have to give
749 // the module a way to return a load.php URL without causing an infinite loop
750 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
751 $scripts = $module->getScriptURLsForDebug( $context );
752 } else {
753 $scripts = $module->getScript( $context );
754 if ( is_string( $scripts ) && strlen( $scripts ) && substr( $scripts, -1 ) !== ';' ) {
755 // bug 27054: Append semicolon to prevent weird bugs
756 // caused by files not terminating their statements right
757 $scripts .= ";\n";
758 }
759 }
760 }
761 // Styles
762 $styles = array();
763 if ( $context->shouldIncludeStyles() ) {
764 // Don't create empty stylesheets like array( '' => '' ) for modules
765 // that don't *have* any stylesheets (bug 38024).
766 $stylePairs = $module->getStyles( $context );
767 if ( count ( $stylePairs ) ) {
768 // If we are in debug mode without &only= set, we'll want to return an array of URLs
769 // See comment near shouldIncludeScripts() for more details
770 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
771 $styles = array(
772 'url' => $module->getStyleURLsForDebug( $context )
773 );
774 } else {
775 // Minify CSS before embedding in mw.loader.implement call
776 // (unless in debug mode)
777 if ( !$context->getDebug() ) {
778 foreach ( $stylePairs as $media => $style ) {
779 // Can be either a string or an array of strings.
780 if ( is_array( $style ) ) {
781 $stylePairs[$media] = array();
782 foreach ( $style as $cssText ) {
783 if ( is_string( $cssText ) ) {
784 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
785 }
786 }
787 } elseif ( is_string( $style ) ) {
788 $stylePairs[$media] = $this->filter( 'minify-css', $style );
789 }
790 }
791 }
792 // Wrap styles into @media groups as needed and flatten into a numerical array
793 $styles = array(
794 'css' => self::makeCombinedStyles( $stylePairs )
795 );
796 }
797 }
798 }
799
800 // Messages
801 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
802
803 // Append output
804 switch ( $context->getOnly() ) {
805 case 'scripts':
806 if ( is_string( $scripts ) ) {
807 // Load scripts raw...
808 $out .= $scripts;
809 } elseif ( is_array( $scripts ) ) {
810 // ...except when $scripts is an array of URLs
811 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
812 }
813 break;
814 case 'styles':
815 // We no longer seperate into media, they are all combined now with
816 // custom media type groups into @media .. {} sections as part of the css string.
817 // Module returns either an empty array or a numerical array with css strings.
818 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
819 break;
820 case 'messages':
821 $out .= self::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
822 break;
823 default:
824 $out .= self::makeLoaderImplementScript(
825 $name,
826 $scripts,
827 $styles,
828 new XmlJsCode( $messagesBlob )
829 );
830 break;
831 }
832 } catch ( Exception $e ) {
833 $e->logException();
834 wfDebugLog( 'resourceloader', __METHOD__ . ": generating module package failed: $e" );
835 $this->hasErrors = true;
836 // Add exception to the output as a comment
837 $exceptions .= self::formatException( $e );
838
839 // Register module as missing
840 $missing[] = $name;
841 unset( $modules[$name] );
842 }
843 $isRaw |= $module->isRaw();
844 wfProfileOut( __METHOD__ . '-' . $name );
845 }
846
847 // Update module states
848 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
849 // Set the state of modules loaded as only scripts to ready
850 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
851 $out .= self::makeLoaderStateScript(
852 array_fill_keys( array_keys( $modules ), 'ready' ) );
853 }
854 // Set the state of modules which were requested but unavailable as missing
855 if ( is_array( $missing ) && count( $missing ) ) {
856 $out .= self::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
857 }
858 }
859
860 if ( !$context->getDebug() ) {
861 if ( $context->getOnly() === 'styles' ) {
862 $out = $this->filter( 'minify-css', $out );
863 } else {
864 $out = $this->filter( 'minify-js', $out );
865 }
866 }
867
868 wfProfileOut( __METHOD__ );
869 return $exceptions . $out;
870 }
871
872 /* Static Methods */
873
874 /**
875 * Returns JS code to call to mw.loader.implement for a module with
876 * given properties.
877 *
878 * @param string $name Module name
879 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
880 * @param $styles Mixed: Array of CSS strings keyed by media type, or an array of lists of URLs to
881 * CSS files keyed by media type
882 * @param $messages Mixed: List of messages associated with this module. May either be an
883 * associative array mapping message key to value, or a JSON-encoded message blob containing
884 * the same data, wrapped in an XmlJsCode object.
885 *
886 * @throws MWException
887 * @return string
888 */
889 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
890 if ( is_string( $scripts ) ) {
891 $scripts = new XmlJsCode( "function () {\n{$scripts}\n}" );
892 } elseif ( !is_array( $scripts ) ) {
893 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
894 }
895 return Xml::encodeJsCall(
896 'mw.loader.implement',
897 array(
898 $name,
899 $scripts,
900 // Force objects. mw.loader.implement requires them to be javascript objects.
901 // Although these variables are associative arrays, which become javascript
902 // objects through json_encode. In many cases they will be empty arrays, and
903 // PHP/json_encode() consider empty arrays to be numerical arrays and
904 // output javascript "[]" instead of "{}". This fixes that.
905 (object)$styles,
906 (object)$messages
907 ),
908 ResourceLoader::inDebugMode()
909 );
910 }
911
912 /**
913 * Returns JS code which, when called, will register a given list of messages.
914 *
915 * @param $messages Mixed: Either an associative array mapping message key to value, or a
916 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
917 *
918 * @return string
919 */
920 public static function makeMessageSetScript( $messages ) {
921 return Xml::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
922 }
923
924 /**
925 * Combines an associative array mapping media type to CSS into a
926 * single stylesheet with "@media" blocks.
927 *
928 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings.
929 *
930 * @return Array
931 */
932 private static function makeCombinedStyles( array $stylePairs ) {
933 $out = array();
934 foreach ( $stylePairs as $media => $styles ) {
935 // ResourceLoaderFileModule::getStyle can return the styles
936 // as a string or an array of strings. This is to allow separation in
937 // the front-end.
938 $styles = (array)$styles;
939 foreach ( $styles as $style ) {
940 $style = trim( $style );
941 // Don't output an empty "@media print { }" block (bug 40498)
942 if ( $style !== '' ) {
943 // Transform the media type based on request params and config
944 // The way that this relies on $wgRequest to propagate request params is slightly evil
945 $media = OutputPage::transformCssMedia( $media );
946
947 if ( $media === '' || $media == 'all' ) {
948 $out[] = $style;
949 } elseif ( is_string( $media ) ) {
950 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
951 }
952 // else: skip
953 }
954 }
955 }
956 return $out;
957 }
958
959 /**
960 * Returns a JS call to mw.loader.state, which sets the state of a
961 * module or modules to a given value. Has two calling conventions:
962 *
963 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
964 * Set the state of a single module called $name to $state
965 *
966 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
967 * Set the state of modules with the given names to the given states
968 *
969 * @param $name string
970 * @param $state
971 *
972 * @return string
973 */
974 public static function makeLoaderStateScript( $name, $state = null ) {
975 if ( is_array( $name ) ) {
976 return Xml::encodeJsCall( 'mw.loader.state', array( $name ) );
977 } else {
978 return Xml::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
979 }
980 }
981
982 /**
983 * Returns JS code which calls the script given by $script. The script will
984 * be called with local variables name, version, dependencies and group,
985 * which will have values corresponding to $name, $version, $dependencies
986 * and $group as supplied.
987 *
988 * @param string $name Module name
989 * @param $version Integer: Module version number as a timestamp
990 * @param array $dependencies List of module names on which this module depends
991 * @param string $group Group which the module is in.
992 * @param string $source Source of the module, or 'local' if not foreign.
993 * @param string $script JavaScript code
994 *
995 * @return string
996 */
997 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
998 $script = str_replace( "\n", "\n\t", trim( $script ) );
999 return Xml::encodeJsCall(
1000 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1001 array( $name, $version, $dependencies, $group, $source ) );
1002 }
1003
1004 /**
1005 * Returns JS code which calls mw.loader.register with the given
1006 * parameters. Has three calling conventions:
1007 *
1008 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
1009 * Register a single module.
1010 *
1011 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1012 * Register modules with the given names.
1013 *
1014 * - ResourceLoader::makeLoaderRegisterScript( array(
1015 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
1016 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
1017 * ...
1018 * ) ):
1019 * Registers modules with the given names and parameters.
1020 *
1021 * @param string $name Module name
1022 * @param $version Integer: Module version number as a timestamp
1023 * @param array $dependencies List of module names on which this module depends
1024 * @param string $group group which the module is in.
1025 * @param string $source source of the module, or 'local' if not foreign
1026 *
1027 * @return string
1028 */
1029 public static function makeLoaderRegisterScript( $name, $version = null,
1030 $dependencies = null, $group = null, $source = null
1031 ) {
1032 if ( is_array( $name ) ) {
1033 return Xml::encodeJsCall( 'mw.loader.register', array( $name ) );
1034 } else {
1035 $version = (int)$version > 1 ? (int)$version : 1;
1036 return Xml::encodeJsCall( 'mw.loader.register',
1037 array( $name, $version, $dependencies, $group, $source ) );
1038 }
1039 }
1040
1041 /**
1042 * Returns JS code which calls mw.loader.addSource() with the given
1043 * parameters. Has two calling conventions:
1044 *
1045 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1046 * Register a single source
1047 *
1048 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
1049 * Register sources with the given IDs and properties.
1050 *
1051 * @param string $id source ID
1052 * @param array $properties source properties (see addSource())
1053 *
1054 * @return string
1055 */
1056 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1057 if ( is_array( $id ) ) {
1058 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id ) );
1059 } else {
1060 return Xml::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
1061 }
1062 }
1063
1064 /**
1065 * Returns JS code which runs given JS code if the client-side framework is
1066 * present.
1067 *
1068 * @param string $script JavaScript code
1069 *
1070 * @return string
1071 */
1072 public static function makeLoaderConditionalScript( $script ) {
1073 return "if(window.mw){\n" . trim( $script ) . "\n}";
1074 }
1075
1076 /**
1077 * Returns JS code which will set the MediaWiki configuration array to
1078 * the given value.
1079 *
1080 * @param array $configuration List of configuration values keyed by variable name
1081 *
1082 * @return string
1083 */
1084 public static function makeConfigSetScript( array $configuration ) {
1085 return Xml::encodeJsCall( 'mw.config.set', array( $configuration ), ResourceLoader::inDebugMode() );
1086 }
1087
1088 /**
1089 * Convert an array of module names to a packed query string.
1090 *
1091 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1092 * becomes 'foo.bar,baz|bar.baz,quux'
1093 * @param array $modules of module names (strings)
1094 * @return string Packed query string
1095 */
1096 public static function makePackedModulesString( $modules ) {
1097 $groups = array(); // array( prefix => array( suffixes ) )
1098 foreach ( $modules as $module ) {
1099 $pos = strrpos( $module, '.' );
1100 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1101 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1102 $groups[$prefix][] = $suffix;
1103 }
1104
1105 $arr = array();
1106 foreach ( $groups as $prefix => $suffixes ) {
1107 $p = $prefix === '' ? '' : $prefix . '.';
1108 $arr[] = $p . implode( ',', $suffixes );
1109 }
1110 $str = implode( '|', $arr );
1111 return $str;
1112 }
1113
1114 /**
1115 * Determine whether debug mode was requested
1116 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1117 * @return bool
1118 */
1119 public static function inDebugMode() {
1120 global $wgRequest, $wgResourceLoaderDebug;
1121 static $retval = null;
1122 if ( !is_null( $retval ) ) {
1123 return $retval;
1124 }
1125 return $retval = $wgRequest->getFuzzyBool( 'debug',
1126 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
1127 }
1128
1129 /**
1130 * Build a load.php URL
1131 * @param array $modules of module names (strings)
1132 * @param string $lang Language code
1133 * @param string $skin Skin name
1134 * @param string|null $user User name. If null, the &user= parameter is omitted
1135 * @param string|null $version Versioning timestamp
1136 * @param bool $debug Whether the request should be in debug mode
1137 * @param string|null $only &only= parameter
1138 * @param bool $printable Printable mode
1139 * @param bool $handheld Handheld mode
1140 * @param array $extraQuery Extra query parameters to add
1141 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1142 */
1143 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1144 $printable = false, $handheld = false, $extraQuery = array() ) {
1145 global $wgLoadScript;
1146 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1147 $only, $printable, $handheld, $extraQuery
1148 );
1149
1150 // Prevent the IE6 extension check from being triggered (bug 28840)
1151 // by appending a character that's invalid in Windows extensions ('*')
1152 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1153 }
1154
1155 /**
1156 * Build a query array (array representation of query string) for load.php. Helper
1157 * function for makeLoaderURL().
1158 *
1159 * @param array $modules
1160 * @param string $lang
1161 * @param string $skin
1162 * @param string $user
1163 * @param string $version
1164 * @param bool $debug
1165 * @param string $only
1166 * @param bool $printable
1167 * @param bool $handheld
1168 * @param array $extraQuery
1169 *
1170 * @return array
1171 */
1172 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1173 $printable = false, $handheld = false, $extraQuery = array() ) {
1174 $query = array(
1175 'modules' => self::makePackedModulesString( $modules ),
1176 'lang' => $lang,
1177 'skin' => $skin,
1178 'debug' => $debug ? 'true' : 'false',
1179 );
1180 if ( $user !== null ) {
1181 $query['user'] = $user;
1182 }
1183 if ( $version !== null ) {
1184 $query['version'] = $version;
1185 }
1186 if ( $only !== null ) {
1187 $query['only'] = $only;
1188 }
1189 if ( $printable ) {
1190 $query['printable'] = 1;
1191 }
1192 if ( $handheld ) {
1193 $query['handheld'] = 1;
1194 }
1195 $query += $extraQuery;
1196
1197 // Make queries uniform in order
1198 ksort( $query );
1199 return $query;
1200 }
1201
1202 /**
1203 * Check a module name for validity.
1204 *
1205 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1206 * at most 255 bytes.
1207 *
1208 * @param string $moduleName Module name to check
1209 * @return bool Whether $moduleName is a valid module name
1210 */
1211 public static function isValidModuleName( $moduleName ) {
1212 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1213 }
1214 }