Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / resourceloader / ResourceLoaderWikiModule.php
blob14d6e056e0642ae69dd65b8c9f086f0d09fe63aa
1 <?php
2 /**
3 * Abstraction for ResourceLoader modules that pull from wiki pages.
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.
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.
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 /**
26 * Abstraction for ResourceLoader modules which pull from wiki pages
28 * This can only be used for wiki pages in the MediaWiki and User namespaces,
29 * because of its dependence on the functionality of Title::isCssJsSubpage
30 * and Title::isCssOrJsPage().
32 * This module supports being used as a placeholder for a module on a remote wiki.
33 * To do so, getDB() must be overloaded to return a foreign database object that
34 * allows local wikis to query page metadata.
36 * Safe for calls on local wikis are:
37 * - Option getters:
38 * - getGroup()
39 * - getPages()
40 * - Basic methods that strictly involve the foreign database
41 * - getDB()
42 * - isKnownEmpty()
43 * - getTitleInfo()
45 class ResourceLoaderWikiModule extends ResourceLoaderModule {
47 // Origin defaults to users with sitewide authority
48 protected $origin = self::ORIGIN_USER_SITEWIDE;
50 // In-process cache for title info
51 protected $titleInfo = [];
53 // List of page names that contain CSS
54 protected $styles = [];
56 // List of page names that contain JavaScript
57 protected $scripts = [];
59 // Group of module
60 protected $group;
62 /**
63 * @param array $options For back-compat, this can be omitted in favour of overwriting getPages.
65 public function __construct( array $options = null ) {
66 if ( is_null( $options ) ) {
67 return;
70 foreach ( $options as $member => $option ) {
71 switch ( $member ) {
72 case 'styles':
73 case 'scripts':
74 case 'group':
75 case 'targets':
76 $this->{$member} = $option;
77 break;
82 /**
83 * Subclasses should return an associative array of resources in the module.
84 * Keys should be the title of a page in the MediaWiki or User namespace.
86 * Values should be a nested array of options. The supported keys are 'type' and
87 * (CSS only) 'media'.
89 * For scripts, 'type' should be 'script'.
91 * For stylesheets, 'type' should be 'style'.
92 * There is an optional media key, the value of which can be the
93 * medium ('screen', 'print', etc.) of the stylesheet.
95 * @param ResourceLoaderContext $context
96 * @return array
98 protected function getPages( ResourceLoaderContext $context ) {
99 $config = $this->getConfig();
100 $pages = [];
102 // Filter out pages from origins not allowed by the current wiki configuration.
103 if ( $config->get( 'UseSiteJs' ) ) {
104 foreach ( $this->scripts as $script ) {
105 $pages[$script] = [ 'type' => 'script' ];
109 if ( $config->get( 'UseSiteCss' ) ) {
110 foreach ( $this->styles as $style ) {
111 $pages[$style] = [ 'type' => 'style' ];
115 return $pages;
119 * Get group name
121 * @return string
123 public function getGroup() {
124 return $this->group;
128 * Get the Database object used in getTitleInfo().
130 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
131 * database object, or null if getTitleInfo() shouldn't access the database.
133 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
134 * In particular, it doesn't work for getContent() or getScript() etc.
136 * @return IDatabase|null
138 protected function getDB() {
139 return wfGetDB( DB_REPLICA );
143 * @param string $titleText
144 * @return null|string
146 protected function getContent( $titleText ) {
147 $title = Title::newFromText( $titleText );
148 if ( !$title ) {
149 return null;
152 $handler = ContentHandler::getForTitle( $title );
153 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
154 $format = CONTENT_FORMAT_CSS;
155 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
156 $format = CONTENT_FORMAT_JAVASCRIPT;
157 } else {
158 return null;
161 $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title->getArticleID(),
162 $title->getLatestRevID() );
163 if ( !$revision ) {
164 return null;
166 $revision->setTitle( $title );
167 $content = $revision->getContent( Revision::RAW );
169 if ( !$content ) {
170 wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
171 return null;
174 return $content->serialize( $format );
178 * @param ResourceLoaderContext $context
179 * @return string
181 public function getScript( ResourceLoaderContext $context ) {
182 $scripts = '';
183 foreach ( $this->getPages( $context ) as $titleText => $options ) {
184 if ( $options['type'] !== 'script' ) {
185 continue;
187 $script = $this->getContent( $titleText );
188 if ( strval( $script ) !== '' ) {
189 $script = $this->validateScriptFile( $titleText, $script );
190 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
193 return $scripts;
197 * @param ResourceLoaderContext $context
198 * @return array
200 public function getStyles( ResourceLoaderContext $context ) {
201 $styles = [];
202 foreach ( $this->getPages( $context ) as $titleText => $options ) {
203 if ( $options['type'] !== 'style' ) {
204 continue;
206 $media = isset( $options['media'] ) ? $options['media'] : 'all';
207 $style = $this->getContent( $titleText );
208 if ( strval( $style ) === '' ) {
209 continue;
211 if ( $this->getFlip( $context ) ) {
212 $style = CSSJanus::transform( $style, true, false );
214 $style = MemoizedCallable::call( 'CSSMin::remap',
215 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
216 if ( !isset( $styles[$media] ) ) {
217 $styles[$media] = [];
219 $style = ResourceLoader::makeComment( $titleText ) . $style;
220 $styles[$media][] = $style;
222 return $styles;
226 * Disable module content versioning.
228 * This class does not support generating content outside of a module
229 * request due to foreign database support.
231 * See getDefinitionSummary() for meta-data versioning.
233 * @return bool
235 public function enableModuleContentVersion() {
236 return false;
240 * @param ResourceLoaderContext $context
241 * @return array
243 public function getDefinitionSummary( ResourceLoaderContext $context ) {
244 $summary = parent::getDefinitionSummary( $context );
245 $summary[] = [
246 'pages' => $this->getPages( $context ),
247 // Includes meta data of current revisions
248 'titleInfo' => $this->getTitleInfo( $context ),
250 return $summary;
254 * @param ResourceLoaderContext $context
255 * @return bool
257 public function isKnownEmpty( ResourceLoaderContext $context ) {
258 $revisions = $this->getTitleInfo( $context );
260 // For user modules, don't needlessly load if there are no non-empty pages
261 if ( $this->getGroup() === 'user' ) {
262 foreach ( $revisions as $revision ) {
263 if ( $revision['page_len'] > 0 ) {
264 // At least one non-empty page, module should be loaded
265 return false;
268 return true;
271 // Bug 68488: For other modules (i.e. ones that are called in cached html output) only check
272 // page existance. This ensures that, if some pages in a module are temporarily blanked,
273 // we don't end omit the module's script or link tag on some pages.
274 return count( $revisions ) === 0;
277 private function setTitleInfo( $key, array $titleInfo ) {
278 $this->titleInfo[$key] = $titleInfo;
282 * Get the information about the wiki pages for a given context.
283 * @param ResourceLoaderContext $context
284 * @return array Keyed by page name
286 protected function getTitleInfo( ResourceLoaderContext $context ) {
287 $dbr = $this->getDB();
288 if ( !$dbr ) {
289 // We're dealing with a subclass that doesn't have a DB
290 return [];
293 $pageNames = array_keys( $this->getPages( $context ) );
294 sort( $pageNames );
295 $key = implode( '|', $pageNames );
296 if ( !isset( $this->titleInfo[$key] ) ) {
297 $this->titleInfo[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
299 return $this->titleInfo[$key];
302 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
303 $titleInfo = [];
304 $batch = new LinkBatch;
305 foreach ( $pages as $titleText ) {
306 $title = Title::newFromText( $titleText );
307 if ( $title ) {
308 // Page name may be invalid if user-provided (e.g. gadgets)
309 $batch->addObj( $title );
312 if ( !$batch->isEmpty() ) {
313 $res = $db->select( 'page',
314 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
315 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
316 $batch->constructSet( 'page', $db ),
317 $fname
319 foreach ( $res as $row ) {
320 // Avoid including ids or timestamps of revision/page tables so
321 // that versions are not wasted
322 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
323 $titleInfo[$title->getPrefixedText()] = [
324 'page_len' => $row->page_len,
325 'page_latest' => $row->page_latest,
326 'page_touched' => $row->page_touched,
330 return $titleInfo;
334 * @since 1.28
335 * @param ResourceLoaderContext $context
336 * @param IDatabase $db
337 * @param string[] $moduleNames
339 public static function preloadTitleInfo(
340 ResourceLoaderContext $context, IDatabase $db, array $moduleNames
342 $rl = $context->getResourceLoader();
343 // getDB() can be overridden to point to a foreign database.
344 // For now, only preload local. In the future, we could preload by wikiID.
345 $allPages = [];
346 /** @var ResourceLoaderWikiModule[] $wikiModules */
347 $wikiModules = [];
348 foreach ( $moduleNames as $name ) {
349 $module = $rl->getModule( $name );
350 if ( $module instanceof self ) {
351 $mDB = $module->getDB();
352 // Subclasses may disable getDB and implement getTitleInfo differently
353 if ( $mDB && $mDB->getWikiID() === $db->getWikiID() ) {
354 $wikiModules[] = $module;
355 $allPages += $module->getPages( $context );
360 $pageNames = array_keys( $allPages );
361 sort( $pageNames );
362 $hash = sha1( implode( '|', $pageNames ) );
364 // Avoid Zend bug where "static::" does not apply LSB in the closure
365 $func = [ static::class, 'fetchTitleInfo' ];
366 $fname = __METHOD__;
368 $cache = ObjectCache::getMainWANInstance();
369 $allInfo = $cache->getWithSetCallback(
370 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID(), $hash ),
371 $cache::TTL_HOUR,
372 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
373 $setOpts += Database::getCacheSetOptions( $db );
375 return call_user_func( $func, $db, $pageNames, $fname );
377 [ 'checkKeys' => [ $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID() ) ] ]
380 foreach ( $wikiModules as $wikiModule ) {
381 $pages = $wikiModule->getPages( $context );
382 // Before we intersect, map the names to canonical form (T145673).
383 $intersect = [];
384 foreach ( $pages as $page => $unused ) {
385 $title = Title::newFromText( $page );
386 if ( $title ) {
387 $intersect[ $title->getPrefixedText() ] = 1;
388 } else {
389 // Page name may be invalid if user-provided (e.g. gadgets)
390 $rl->getLogger()->info(
391 'Invalid wiki page title "{title}" in ' . __METHOD__,
392 [ 'title' => $page ]
396 $info = array_intersect_key( $allInfo, $intersect );
397 $pageNames = array_keys( $pages );
398 sort( $pageNames );
399 $key = implode( '|', $pageNames );
400 $wikiModule->setTitleInfo( $key, $info );
405 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
406 * page change if it was a JS or CSS page
408 * @param Title $title
409 * @param Revision|null $old Prior page revision
410 * @param Revision|null $new New page revision
411 * @param string $wikiId
412 * @since 1.28
414 public static function invalidateModuleCache(
415 Title $title, Revision $old = null, Revision $new = null, $wikiId
417 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
419 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
420 $purge = true;
421 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
422 $purge = true;
423 } else {
424 $purge = ( $title->isCssOrJsPage() || $title->isCssJsSubpage() );
427 if ( $purge ) {
428 $cache = ObjectCache::getMainWANInstance();
429 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
430 $cache->touchCheckKey( $key );
435 * @since 1.28
436 * @return string
438 public function getType() {
439 // Check both because subclasses don't always pass pages via the constructor,
440 // they may also override getPages() instead, in which case we should keep
441 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
442 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;