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