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