MediaWiki  REL1_22
ResourceLoaderFileModule.php
Go to the documentation of this file.
00001 <?php
00028 class ResourceLoaderFileModule extends ResourceLoaderModule {
00029 
00030     /* Protected Members */
00031 
00033     protected $localBasePath = '';
00035     protected $remoteBasePath = '';
00043     protected $scripts = array();
00051     protected $languageScripts = array();
00059     protected $skinScripts = array();
00067     protected $debugScripts = array();
00075     protected $loaderScripts = array();
00083     protected $styles = array();
00091     protected $skinStyles = array();
00099     protected $dependencies = array();
00107     protected $messages = array();
00109     protected $group;
00111     protected $position = 'bottom';
00113     protected $debugRaw = true;
00115     protected $raw = false;
00116     protected $targets = array( 'desktop' );
00117 
00122     protected $hasGeneratedStyles = false;
00123 
00131     protected $modifiedTime = array();
00139     protected $localFileRefs = array();
00140 
00141     /* Methods */
00142 
00195     public function __construct( $options = array(), $localBasePath = null,
00196         $remoteBasePath = null
00197     ) {
00198         global $IP, $wgScriptPath, $wgResourceBasePath;
00199         $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
00200         if ( $remoteBasePath !== null ) {
00201             $this->remoteBasePath = $remoteBasePath;
00202         } else {
00203             $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
00204         }
00205 
00206         if ( isset( $options['remoteExtPath'] ) ) {
00207             global $wgExtensionAssetsPath;
00208             $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
00209         }
00210 
00211         foreach ( $options as $member => $option ) {
00212             switch ( $member ) {
00213                 // Lists of file paths
00214                 case 'scripts':
00215                 case 'debugScripts':
00216                 case 'loaderScripts':
00217                 case 'styles':
00218                     $this->{$member} = (array)$option;
00219                     break;
00220                 // Collated lists of file paths
00221                 case 'languageScripts':
00222                 case 'skinScripts':
00223                 case 'skinStyles':
00224                     if ( !is_array( $option ) ) {
00225                         throw new MWException(
00226                             "Invalid collated file path list error. " .
00227                             "'$option' given, array expected."
00228                         );
00229                     }
00230                     foreach ( $option as $key => $value ) {
00231                         if ( !is_string( $key ) ) {
00232                             throw new MWException(
00233                                 "Invalid collated file path list key error. " .
00234                                 "'$key' given, string expected."
00235                             );
00236                         }
00237                         $this->{$member}[$key] = (array)$value;
00238                     }
00239                     break;
00240                 // Lists of strings
00241                 case 'dependencies':
00242                 case 'messages':
00243                 case 'targets':
00244                     $this->{$member} = (array)$option;
00245                     break;
00246                 // Single strings
00247                 case 'group':
00248                 case 'position':
00249                 case 'localBasePath':
00250                 case 'remoteBasePath':
00251                     $this->{$member} = (string)$option;
00252                     break;
00253                 // Single booleans
00254                 case 'debugRaw':
00255                 case 'raw':
00256                     $this->{$member} = (bool)$option;
00257                     break;
00258             }
00259         }
00260         // Make sure the remote base path is a complete valid URL,
00261         // but possibly protocol-relative to avoid cache pollution
00262         $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
00263     }
00264 
00271     public function getScript( ResourceLoaderContext $context ) {
00272         $files = $this->getScriptFiles( $context );
00273         return $this->readScriptFiles( $files );
00274     }
00275 
00280     public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
00281         $urls = array();
00282         foreach ( $this->getScriptFiles( $context ) as $file ) {
00283             $urls[] = $this->getRemotePath( $file );
00284         }
00285         return $urls;
00286     }
00287 
00291     public function supportsURLLoading() {
00292         return $this->debugRaw;
00293     }
00294 
00300     public function getLoaderScript() {
00301         if ( count( $this->loaderScripts ) == 0 ) {
00302             return false;
00303         }
00304         return $this->readScriptFiles( $this->loaderScripts );
00305     }
00306 
00313     public function getStyles( ResourceLoaderContext $context ) {
00314         $styles = $this->readStyleFiles(
00315             $this->getStyleFiles( $context ),
00316             $this->getFlip( $context )
00317         );
00318         // Collect referenced files
00319         $this->localFileRefs = array_unique( $this->localFileRefs );
00320         // If the list has been modified since last time we cached it, update the cache
00321         try {
00322             if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
00323                 $dbw = wfGetDB( DB_MASTER );
00324                 $dbw->replace( 'module_deps',
00325                     array( array( 'md_module', 'md_skin' ) ), array(
00326                         'md_module' => $this->getName(),
00327                         'md_skin' => $context->getSkin(),
00328                         'md_deps' => FormatJson::encode( $this->localFileRefs ),
00329                     )
00330                 );
00331             }
00332         } catch ( Exception $e ) {
00333             wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
00334         }
00335         return $styles;
00336     }
00337 
00342     public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
00343         if ( $this->hasGeneratedStyles ) {
00344             // Do the default behaviour of returning a url back to load.php
00345             // but with only=styles.
00346             return parent::getStyleURLsForDebug( $context );
00347         }
00348         // Our module consists entirely of real css files,
00349         // in debug mode we can load those directly.
00350         $urls = array();
00351         foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
00352             $urls[$mediaType] = array();
00353             foreach ( $list as $file ) {
00354                 $urls[$mediaType][] = $this->getRemotePath( $file );
00355             }
00356         }
00357         return $urls;
00358     }
00359 
00365     public function getMessages() {
00366         return $this->messages;
00367     }
00368 
00374     public function getGroup() {
00375         return $this->group;
00376     }
00377 
00381     public function getPosition() {
00382         return $this->position;
00383     }
00384 
00390     public function getDependencies() {
00391         return $this->dependencies;
00392     }
00393 
00397     public function isRaw() {
00398         return $this->raw;
00399     }
00400 
00415     public function getModifiedTime( ResourceLoaderContext $context ) {
00416         if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
00417             return $this->modifiedTime[$context->getHash()];
00418         }
00419         wfProfileIn( __METHOD__ );
00420 
00421         $files = array();
00422 
00423         // Flatten style files into $files
00424         $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
00425         foreach ( $styles as $styleFiles ) {
00426             $files = array_merge( $files, $styleFiles );
00427         }
00428         $skinFiles = self::tryForKey(
00429             self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
00430             $context->getSkin(),
00431             'default'
00432         );
00433         foreach ( $skinFiles as $styleFiles ) {
00434             $files = array_merge( $files, $styleFiles );
00435         }
00436 
00437         // Final merge, this should result in a master list of dependent files
00438         $files = array_merge(
00439             $files,
00440             $this->scripts,
00441             $context->getDebug() ? $this->debugScripts : array(),
00442             self::tryForKey( $this->languageScripts, $context->getLanguage() ),
00443             self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
00444             $this->loaderScripts
00445         );
00446         $files = array_map( array( $this, 'getLocalPath' ), $files );
00447         // File deps need to be treated separately because they're already prefixed
00448         $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
00449 
00450         // If a module is nothing but a list of dependencies, we need to avoid
00451         // giving max() an empty array
00452         if ( count( $files ) === 0 ) {
00453             wfProfileOut( __METHOD__ );
00454             return $this->modifiedTime[$context->getHash()] = 1;
00455         }
00456 
00457         wfProfileIn( __METHOD__ . '-filemtime' );
00458         $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
00459         wfProfileOut( __METHOD__ . '-filemtime' );
00460         $this->modifiedTime[$context->getHash()] = max(
00461             $filesMtime,
00462             $this->getMsgBlobMtime( $context->getLanguage() ) );
00463 
00464         wfProfileOut( __METHOD__ );
00465         return $this->modifiedTime[$context->getHash()];
00466     }
00467 
00468     /* Protected Methods */
00469 
00474     protected function getLocalPath( $path ) {
00475         return "{$this->localBasePath}/$path";
00476     }
00477 
00482     protected function getRemotePath( $path ) {
00483         return "{$this->remoteBasePath}/$path";
00484     }
00485 
00493     public function getStyleSheetLang( $path ) {
00494         return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
00495     }
00496 
00506     protected static function collateFilePathListByOption( array $list, $option, $default ) {
00507         $collatedFiles = array();
00508         foreach ( (array)$list as $key => $value ) {
00509             if ( is_int( $key ) ) {
00510                 // File name as the value
00511                 if ( !isset( $collatedFiles[$default] ) ) {
00512                     $collatedFiles[$default] = array();
00513                 }
00514                 $collatedFiles[$default][] = $value;
00515             } elseif ( is_array( $value ) ) {
00516                 // File name as the key, options array as the value
00517                 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
00518                 if ( !isset( $collatedFiles[$optionValue] ) ) {
00519                     $collatedFiles[$optionValue] = array();
00520                 }
00521                 $collatedFiles[$optionValue][] = $key;
00522             }
00523         }
00524         return $collatedFiles;
00525     }
00526 
00536     protected static function tryForKey( array $list, $key, $fallback = null ) {
00537         if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
00538             return $list[$key];
00539         } elseif ( is_string( $fallback )
00540             && isset( $list[$fallback] )
00541             && is_array( $list[$fallback] ) )
00542         {
00543             return $list[$fallback];
00544         }
00545         return array();
00546     }
00547 
00554     protected function getScriptFiles( ResourceLoaderContext $context ) {
00555         $files = array_merge(
00556             $this->scripts,
00557             self::tryForKey( $this->languageScripts, $context->getLanguage() ),
00558             self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
00559         );
00560         if ( $context->getDebug() ) {
00561             $files = array_merge( $files, $this->debugScripts );
00562         }
00563 
00564         return array_unique( $files );
00565     }
00566 
00573     protected function getStyleFiles( ResourceLoaderContext $context ) {
00574         return array_merge_recursive(
00575             self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
00576             self::collateFilePathListByOption(
00577                 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
00578             )
00579         );
00580     }
00581 
00586     public function getAllStyleFiles() {
00587         $files = array();
00588         foreach( (array)$this->styles as $key => $value ) {
00589             if ( is_array( $value ) ) {
00590                 $path = $key;
00591             } else {
00592                 $path = $value;
00593             }
00594             $files[] = $this->getLocalPath( $path );
00595         }
00596         return $files;
00597     }
00598 
00606     protected function readScriptFiles( array $scripts ) {
00607         global $wgResourceLoaderValidateStaticJS;
00608         if ( empty( $scripts ) ) {
00609             return '';
00610         }
00611         $js = '';
00612         foreach ( array_unique( $scripts ) as $fileName ) {
00613             $localPath = $this->getLocalPath( $fileName );
00614             if ( !file_exists( $localPath ) ) {
00615                 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
00616             }
00617             $contents = file_get_contents( $localPath );
00618             if ( $wgResourceLoaderValidateStaticJS ) {
00619                 // Static files don't really need to be checked as often; unlike
00620                 // on-wiki module they shouldn't change unexpectedly without
00621                 // admin interference.
00622                 $contents = $this->validateScriptFile( $fileName, $contents );
00623             }
00624             $js .= $contents . "\n";
00625         }
00626         return $js;
00627     }
00628 
00640     protected function readStyleFiles( array $styles, $flip ) {
00641         if ( empty( $styles ) ) {
00642             return array();
00643         }
00644         foreach ( $styles as $media => $files ) {
00645             $uniqueFiles = array_unique( $files );
00646             $styles[$media] = implode(
00647                 "\n",
00648                 array_map(
00649                     array( $this, 'readStyleFile' ),
00650                     $uniqueFiles,
00651                     array_fill( 0, count( $uniqueFiles ), $flip )
00652                 )
00653             );
00654         }
00655         return $styles;
00656     }
00657 
00669     protected function readStyleFile( $path, $flip ) {
00670         $localPath = $this->getLocalPath( $path );
00671         if ( !file_exists( $localPath ) ) {
00672             $msg = __METHOD__ . ": style file not found: \"$localPath\"";
00673             wfDebugLog( 'resourceloader', $msg );
00674             throw new MWException( $msg );
00675         }
00676 
00677         if ( $this->getStyleSheetLang( $path ) === 'less' ) {
00678             $style = $this->compileLESSFile( $localPath );
00679             $this->hasGeneratedStyles = true;
00680         } else {
00681             $style = file_get_contents( $localPath );
00682         }
00683 
00684         if ( $flip ) {
00685             $style = CSSJanus::transform( $style, true, false );
00686         }
00687         $dirname = dirname( $path );
00688         if ( $dirname == '.' ) {
00689             // If $path doesn't have a directory component, don't prepend a dot
00690             $dirname = '';
00691         }
00692         $dir = $this->getLocalPath( $dirname );
00693         $remoteDir = $this->getRemotePath( $dirname );
00694         // Get and register local file references
00695         $this->localFileRefs = array_merge(
00696             $this->localFileRefs,
00697             CSSMin::getLocalFileReferences( $style, $dir )
00698         );
00699         return CSSMin::remap(
00700             $style, $dir, $remoteDir, true
00701         );
00702     }
00703 
00709     public function getFlip( $context ) {
00710         return $context->getDirection() === 'rtl';
00711     }
00712 
00718     public function getTargets() {
00719         return $this->targets;
00720     }
00721 
00732     protected static function getLESSCacheKey( $fileName ) {
00733         $vars = json_encode( ResourceLoader::getLESSVars() );
00734         $hash = md5( $fileName . $vars );
00735         return wfMemcKey( 'resourceloader', 'less', $hash );
00736     }
00737 
00751     protected function compileLESSFile( $fileName ) {
00752         $key = self::getLESSCacheKey( $fileName );
00753         $cache = wfGetCache( CACHE_ANYTHING );
00754 
00755         // The input to lessc. Either an associative array representing the
00756         // cached results of a previous compilation, or the string file name if
00757         // no cache result exists.
00758         $source = $cache->get( $key );
00759         if ( !is_array( $source ) || !isset( $source['root'] ) ) {
00760             $source = $fileName;
00761         }
00762 
00763         $compiler = ResourceLoader::getLessCompiler();
00764         $result = null;
00765 
00766         $result = $compiler->cachedCompile( $source );
00767 
00768         if ( !is_array( $result ) ) {
00769             throw new MWException( 'LESS compiler result has type ' . gettype( $result ) . '; array expected.' );
00770         }
00771 
00772         $this->localFileRefs += array_keys( $result['files'] );
00773         $cache->set( $key, $result );
00774         return $result['compiled'];
00775     }
00776 }