Fixed some doxygen warnings
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 /**
24 * ResourceLoader module based on local JavaScript/CSS files.
25 */
26 class ResourceLoaderFileModule extends ResourceLoaderModule {
27
28 /* Protected Members */
29
30 /** String: Local base path, see __construct() */
31 protected $localBasePath = '';
32 /** String: Remote base path, see __construct() */
33 protected $remoteBasePath = '';
34 /**
35 * Array: List of paths to JavaScript files to always include
36 * @example array( [file-path], [file-path], ... )
37 */
38 protected $scripts = array();
39 /**
40 * Array: List of JavaScript files to include when using a specific language
41 * @example array( [language-code] => array( [file-path], [file-path], ... ), ... )
42 */
43 protected $languageScripts = array();
44 /**
45 * Array: List of JavaScript files to include when using a specific skin
46 * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
47 */
48 protected $skinScripts = array();
49 /**
50 * Array: List of paths to JavaScript files to include in debug mode
51 * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
52 */
53 protected $debugScripts = array();
54 /**
55 * Array: List of paths to JavaScript files to include in the startup module
56 * @example array( [file-path], [file-path], ... )
57 */
58 protected $loaderScripts = array();
59 /**
60 * Array: List of paths to CSS files to always include
61 * @example array( [file-path], [file-path], ... )
62 */
63 protected $styles = array();
64 /**
65 * Array: List of paths to CSS files to include when using specific skins
66 * @example array( [file-path], [file-path], ... )
67 */
68 protected $skinStyles = array();
69 /**
70 * Array: List of modules this module depends on
71 * @example array( [file-path], [file-path], ... )
72 */
73 protected $dependencies = array();
74 /**
75 * Array: List of message keys used by this module
76 * @example array( [message-key], [message-key], ... )
77 */
78 protected $messages = array();
79 /** String: Name of group to load this module in */
80 protected $group;
81 /** Boolean: Link to raw files in debug mode */
82 protected $debugRaw = true;
83 /**
84 * Array: Cache for mtime
85 * @example array( [hash] => [mtime], [hash] => [mtime], ... )
86 */
87 protected $modifiedTime = array();
88 /**
89 * Array: Place where readStyleFile() tracks file dependencies
90 * @example array( [file-path], [file-path], ... )
91 */
92 protected $localFileRefs = array();
93
94 /* Methods */
95
96 /**
97 * Constructs a new module from an options array.
98 *
99 * @param $options Array: List of options; if not given or empty, an empty module will be
100 * constructed
101 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
102 * to $IP
103 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
104 * to $wgScriptPath
105 *
106 * @example $options
107 * array(
108 * // Scripts to always include
109 * 'scripts' => [file path string or array of file path strings],
110 * // Scripts to include in specific language contexts
111 * 'languageScripts' => array(
112 * [language code] => [file path string or array of file path strings],
113 * ),
114 * // Scripts to include in specific skin contexts
115 * 'skinScripts' => array(
116 * [skin name] => [file path string or array of file path strings],
117 * ),
118 * // Scripts to include in debug contexts
119 * 'debugScripts' => [file path string or array of file path strings],
120 * // Scripts to include in the startup module
121 * 'loaderScripts' => [file path string or array of file path strings],
122 * // Modules which must be loaded before this module
123 * 'dependencies' => [modile name string or array of module name strings],
124 * // Styles to always load
125 * 'styles' => [file path string or array of file path strings],
126 * // Styles to include in specific skin contexts
127 * 'skinStyles' => array(
128 * [skin name] => [file path string or array of file path strings],
129 * ),
130 * // Messages to always load
131 * 'messages' => [array of message key strings],
132 * // Group which this module should be loaded together with
133 * 'group' => [group name string],
134 * )
135 */
136 public function __construct( $options = array(), $localBasePath = null,
137 $remoteBasePath = null )
138 {
139 global $IP, $wgScriptPath;
140 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
141 $this->remoteBasePath = $remoteBasePath === null ? $wgScriptPath : $remoteBasePath;
142 foreach ( $options as $member => $option ) {
143 switch ( $member ) {
144 // Lists of file paths
145 case 'scripts':
146 case 'debugScripts':
147 case 'loaderScripts':
148 case 'styles':
149 $this->{$member} = (array) $option;
150 break;
151 // Collated lists of file paths
152 case 'languageScripts':
153 case 'skinScripts':
154 case 'skinStyles':
155 if ( !is_array( $option ) ) {
156 throw new MWException(
157 "Invalid collated file path list error. " .
158 "'$option' given, array expected."
159 );
160 }
161 foreach ( $option as $key => $value ) {
162 if ( !is_string( $key ) ) {
163 throw new MWException(
164 "Invalid collated file path list key error. " .
165 "'$key' given, string expected."
166 );
167 }
168 $this->{$member}[$key] = (array) $value;
169 }
170 break;
171 // Lists of strings
172 case 'dependencies':
173 case 'messages':
174 $this->{$member} = (array) $option;
175 break;
176 // Single strings
177 case 'group':
178 $this->{$member} = (string) $option;
179 break;
180 // Single booleans
181 case 'debugRaw':
182 $this->{$member} = (bool) $option;
183 break;
184 }
185 }
186 }
187
188 /**
189 * Gets all scripts for a given context concatenated together.
190 *
191 * @param $context ResourceLoaderContext: Context in which to generate script
192 * @return String: JavaScript code for $context
193 */
194 public function getScript( ResourceLoaderContext $context ) {
195 global $wgServer;
196
197 $files = array_merge(
198 $this->scripts,
199 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
200 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
201 );
202 if ( $context->getDebug() ) {
203 $files = array_merge( $files, $this->debugScripts );
204 if ( $this->debugRaw ) {
205 $script = '';
206 foreach ( $files as $file ) {
207 $path = $wgServer . $this->getRemotePath( $file );
208 $script .= "\n\t" . Xml::encodeJsCall( 'mediaWiki.loader.load', array( $path ) );
209 }
210 return $script;
211 }
212 }
213 return $this->readScriptFiles( $files );
214 }
215
216 /**
217 * Gets loader script.
218 *
219 * @return String: JavaScript code to be added to startup module
220 */
221 public function getLoaderScript() {
222 if ( count( $this->loaderScripts ) == 0 ) {
223 return false;
224 }
225 return $this->readScriptFiles( $this->loaderScripts );
226 }
227
228 /**
229 * Gets all styles for a given context concatenated together.
230 *
231 * @param $context ResourceLoaderContext: Context in which to generate styles
232 * @return String: CSS code for $context
233 */
234 public function getStyles( ResourceLoaderContext $context ) {
235 // Merge general styles and skin specific styles, retaining media type collation
236 $styles = $this->readStyleFiles( $this->styles );
237 $skinStyles = $this->readStyleFiles(
238 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ) );
239
240 foreach ( $skinStyles as $media => $style ) {
241 if ( isset( $styles[$media] ) ) {
242 $styles[$media] .= $style;
243 } else {
244 $styles[$media] = $style;
245 }
246 }
247 // Collect referenced files
248 $this->localFileRefs = array_unique( $this->localFileRefs );
249 // If the list has been modified since last time we cached it, update the cache
250 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
251 $dbw = wfGetDB( DB_MASTER );
252 $dbw->replace( 'module_deps',
253 array( array( 'md_module', 'md_skin' ) ), array(
254 'md_module' => $this->getName(),
255 'md_skin' => $context->getSkin(),
256 'md_deps' => FormatJson::encode( $this->localFileRefs ),
257 )
258 );
259 }
260 return $styles;
261 }
262
263 /**
264 * Gets list of message keys used by this module.
265 *
266 * @return Array: List of message keys
267 */
268 public function getMessages() {
269 return $this->messages;
270 }
271
272 /**
273 * Gets the name of the group this module should be loaded in.
274 *
275 * @return String: Group name
276 */
277 public function getGroup() {
278 return $this->group;
279 }
280
281 /**
282 * Gets list of names of modules this module depends on.
283 *
284 * @return Array: List of module names
285 */
286 public function getDependencies() {
287 return $this->dependencies;
288 }
289
290 /**
291 * Get the last modified timestamp of this module.
292 *
293 * Last modified timestamps are calculated from the highest last modified
294 * timestamp of this module's constituent files as well as the files it
295 * depends on. This function is context-sensitive, only performing
296 * calculations on files relevant to the given language, skin and debug
297 * mode.
298 *
299 * @param $context ResourceLoaderContext: Context in which to calculate
300 * the modified time
301 * @return Integer: UNIX timestamp
302 * @see ResourceLoaderModule::getFileDependencies
303 */
304 public function getModifiedTime( ResourceLoaderContext $context ) {
305 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
306 return $this->modifiedTime[$context->getHash()];
307 }
308 wfProfileIn( __METHOD__ );
309
310 $files = array();
311
312 // Flatten style files into $files
313 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
314 foreach ( $styles as $styleFiles ) {
315 $files = array_merge( $files, $styleFiles );
316 }
317 $skinFiles = self::tryForKey(
318 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
319 $context->getSkin(),
320 'default'
321 );
322 foreach ( $skinFiles as $styleFiles ) {
323 $files = array_merge( $files, $styleFiles );
324 }
325
326 // Final merge, this should result in a master list of dependent files
327 $files = array_merge(
328 $files,
329 $this->scripts,
330 $context->getDebug() ? $this->debugScripts : array(),
331 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
332 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
333 $this->loaderScripts
334 );
335 $files = array_map( array( $this, 'getLocalPath' ), $files );
336 // File deps need to be treated separately because they're already prefixed
337 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
338
339 // If a module is nothing but a list of dependencies, we need to avoid
340 // giving max() an empty array
341 if ( count( $files ) === 0 ) {
342 return $this->modifiedTime[$context->getHash()] = 1;
343 }
344
345 wfProfileIn( __METHOD__.'-filemtime' );
346 $filesMtime = max( array_map( 'filemtime', $files ) );
347 wfProfileOut( __METHOD__.'-filemtime' );
348 $this->modifiedTime[$context->getHash()] = max(
349 $filesMtime,
350 $this->getMsgBlobMtime( $context->getLanguage() ) );
351 wfProfileOut( __METHOD__ );
352 return $this->modifiedTime[$context->getHash()];
353 }
354
355 /* Protected Members */
356
357 protected function getLocalPath( $path ) {
358 return "{$this->localBasePath}/$path";
359 }
360
361 protected function getRemotePath( $path ) {
362 return "{$this->remoteBasePath}/$path";
363 }
364
365 /**
366 * Collates file paths by option (where provided).
367 *
368 * @param $list Array: List of file paths in any combination of index/path
369 * or path/options pairs
370 * @param $option String: option name
371 * @param $default Mixed: default value if the option isn't set
372 * @return Array: List of file paths, collated by $option
373 */
374 protected static function collateFilePathListByOption( array $list, $option, $default ) {
375 $collatedFiles = array();
376 foreach ( (array) $list as $key => $value ) {
377 if ( is_int( $key ) ) {
378 // File name as the value
379 if ( !isset( $collatedFiles[$default] ) ) {
380 $collatedFiles[$default] = array();
381 }
382 $collatedFiles[$default][] = $value;
383 } else if ( is_array( $value ) ) {
384 // File name as the key, options array as the value
385 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
386 if ( !isset( $collatedFiles[$optionValue] ) ) {
387 $collatedFiles[$optionValue] = array();
388 }
389 $collatedFiles[$optionValue][] = $key;
390 }
391 }
392 return $collatedFiles;
393 }
394
395 /**
396 * Gets a list of element that match a key, optionally using a fallback key.
397 *
398 * @param $list Array: List of lists to select from
399 * @param $key String: Key to look for in $map
400 * @param $fallback String: Key to look for in $list if $key doesn't exist
401 * @return Array: List of elements from $map which matched $key or $fallback,
402 * or an empty list in case of no match
403 */
404 protected static function tryForKey( array $list, $key, $fallback = null ) {
405 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
406 return $list[$key];
407 } else if ( is_string( $fallback )
408 && isset( $list[$fallback] )
409 && is_array( $list[$fallback] ) )
410 {
411 return $list[$fallback];
412 }
413 return array();
414 }
415
416 /**
417 * Gets the contents of a list of JavaScript files.
418 *
419 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
420 * @return String: Concatenated and remapped JavaScript data from $scripts
421 */
422 protected function readScriptFiles( array $scripts ) {
423 if ( empty( $scripts ) ) {
424 return '';
425 }
426 $js = '';
427 foreach ( array_unique( $scripts ) as $fileName ) {
428 $localPath = $this->getLocalPath( $fileName );
429 $contents = file_get_contents( $localPath );
430 if ( $contents === false ) {
431 throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
432 }
433 $js .= $contents . "\n";
434 }
435 return $js;
436 }
437
438 /**
439 * Gets the contents of a list of CSS files.
440 *
441 * @param $styles Array: List of file paths to styles to read, remap and concetenate
442 * @return Array: List of concatenated and remapped CSS data from $styles,
443 * keyed by media type
444 */
445 protected function readStyleFiles( array $styles ) {
446 if ( empty( $styles ) ) {
447 return array();
448 }
449 $styles = self::collateFilePathListByOption( $styles, 'media', 'all' );
450 foreach ( $styles as $media => $files ) {
451 $styles[$media] = implode(
452 "\n", array_map( array( $this, 'readStyleFile' ), array_unique( $files ) )
453 );
454 }
455 return $styles;
456 }
457
458 /**
459 * Reads a style file.
460 *
461 * This method can be used as a callback for array_map()
462 *
463 * @param $path String: File path of script file to read
464 * @return String: CSS data in script file
465 */
466 protected function readStyleFile( $path ) {
467 $localPath = $this->getLocalPath( $path );
468 $style = file_get_contents( $localPath );
469 if ( $style === false ) {
470 throw new MWException( __METHOD__.": style file not found: \"$localPath\"" );
471 }
472 $dir = $this->getLocalPath( dirname( $path ) );
473 $remoteDir = $this->getRemotePath( dirname( $path ) );
474 // Get and register local file references
475 $this->localFileRefs = array_merge(
476 $this->localFileRefs,
477 CSSMin::getLocalFileReferences( $style, $dir ) );
478 return CSSMin::remap(
479 $style, $dir, $remoteDir, true
480 );
481 }
482 }