resourceloader: Remove support for $context === null in getContentObj
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderWikiModule.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 use MediaWiki\Linker\LinkTarget;
24 use MediaWiki\Revision\RevisionRecord;
25 use Wikimedia\Assert\Assert;
26 use Wikimedia\Rdbms\Database;
27 use Wikimedia\Rdbms\IDatabase;
28 use MediaWiki\MediaWikiServices;
29
30 /**
31 * Abstraction for ResourceLoader modules which pull from wiki pages
32 *
33 * This can only be used for wiki pages in the MediaWiki and User namespaces,
34 * because of its dependence on the functionality of Title::isUserConfigPage()
35 * and Title::isSiteConfigPage().
36 *
37 * This module supports being used as a placeholder for a module on a remote wiki.
38 * To do so, getDB() must be overloaded to return a foreign database object that
39 * allows local wikis to query page metadata.
40 *
41 * Safe for calls on local wikis are:
42 * - Option getters:
43 * - getGroup()
44 * - getPages()
45 * - Basic methods that strictly involve the foreign database
46 * - getDB()
47 * - isKnownEmpty()
48 * - getTitleInfo()
49 *
50 * @ingroup ResourceLoader
51 * @since 1.17
52 */
53 class ResourceLoaderWikiModule extends ResourceLoaderModule {
54
55 // Origin defaults to users with sitewide authority
56 protected $origin = self::ORIGIN_USER_SITEWIDE;
57
58 // In-process cache for title info, structured as an array
59 // [
60 // <batchKey> // Pipe-separated list of sorted keys from getPages
61 // => [
62 // <titleKey> => [ // Normalised title key
63 // 'page_len' => ..,
64 // 'page_latest' => ..,
65 // 'page_touched' => ..,
66 // ]
67 // ]
68 // ]
69 // @see self::fetchTitleInfo()
70 // @see self::makeTitleKey()
71 protected $titleInfo = [];
72
73 // List of page names that contain CSS
74 protected $styles = [];
75
76 // List of page names that contain JavaScript
77 protected $scripts = [];
78
79 // Group of module
80 protected $group;
81
82 /**
83 * @param array|null $options For back-compat, this can be omitted in favour of overwriting
84 * getPages.
85 */
86 public function __construct( array $options = null ) {
87 if ( $options === null ) {
88 return;
89 }
90
91 foreach ( $options as $member => $option ) {
92 switch ( $member ) {
93 case 'styles':
94 case 'scripts':
95 case 'group':
96 case 'targets':
97 $this->{$member} = $option;
98 break;
99 }
100 }
101 }
102
103 /**
104 * Subclasses should return an associative array of resources in the module.
105 * Keys should be the title of a page in the MediaWiki or User namespace.
106 *
107 * Values should be a nested array of options. The supported keys are 'type' and
108 * (CSS only) 'media'.
109 *
110 * For scripts, 'type' should be 'script'.
111 *
112 * For stylesheets, 'type' should be 'style'.
113 * There is an optional media key, the value of which can be the
114 * medium ('screen', 'print', etc.) of the stylesheet.
115 *
116 * @param ResourceLoaderContext $context
117 * @return array
118 */
119 protected function getPages( ResourceLoaderContext $context ) {
120 $config = $this->getConfig();
121 $pages = [];
122
123 // Filter out pages from origins not allowed by the current wiki configuration.
124 if ( $config->get( 'UseSiteJs' ) ) {
125 foreach ( $this->scripts as $script ) {
126 $pages[$script] = [ 'type' => 'script' ];
127 }
128 }
129
130 if ( $config->get( 'UseSiteCss' ) ) {
131 foreach ( $this->styles as $style ) {
132 $pages[$style] = [ 'type' => 'style' ];
133 }
134 }
135
136 return $pages;
137 }
138
139 /**
140 * Get group name
141 *
142 * @return string
143 */
144 public function getGroup() {
145 return $this->group;
146 }
147
148 /**
149 * Get the Database handle used for computing the module version.
150 *
151 * Subclasses may override this to return a foreign database, which would
152 * allow them to register a module on wiki A that fetches wiki pages from
153 * wiki B.
154 *
155 * The way this works is that the local module is a placeholder that can
156 * only computer a module version hash. The 'source' of the module must
157 * be set to the foreign wiki directly. Methods getScript() and getContent()
158 * will not use this handle and are not valid on the local wiki.
159 *
160 * @return IDatabase
161 */
162 protected function getDB() {
163 return wfGetDB( DB_REPLICA );
164 }
165
166 /**
167 * @param string $titleText
168 * @param ResourceLoaderContext $context
169 * @return null|string
170 * @since 1.32 added the $context parameter
171 */
172 protected function getContent( $titleText, ResourceLoaderContext $context ) {
173 $title = Title::newFromText( $titleText );
174 if ( !$title ) {
175 return null; // Bad title
176 }
177
178 $content = $this->getContentObj( $title, $context );
179 if ( !$content ) {
180 return null; // No content found
181 }
182
183 $handler = $content->getContentHandler();
184 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
185 $format = CONTENT_FORMAT_CSS;
186 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
187 $format = CONTENT_FORMAT_JAVASCRIPT;
188 } else {
189 return null; // Bad content model
190 }
191
192 return $content->serialize( $format );
193 }
194
195 /**
196 * @param Title $title
197 * @param ResourceLoaderContext $context
198 * @param int|null $maxRedirects Maximum number of redirects to follow. If
199 * null, uses $wgMaxRedirects
200 * @return Content|null
201 * @since 1.32 added the $context and $maxRedirects parameters
202 */
203 protected function getContentObj(
204 Title $title, ResourceLoaderContext $context, $maxRedirects = null
205 ) {
206 $overrideCallback = $context->getContentOverrideCallback();
207 $content = $overrideCallback ? call_user_func( $overrideCallback, $title ) : null;
208 if ( $content ) {
209 if ( !$content instanceof Content ) {
210 $this->getLogger()->error(
211 'Bad content override for "{title}" in ' . __METHOD__,
212 [ 'title' => $title->getPrefixedText() ]
213 );
214 return null;
215 }
216 } else {
217 $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
218 if ( !$revision ) {
219 return null;
220 }
221 $content = $revision->getContent( RevisionRecord::RAW );
222
223 if ( !$content ) {
224 $this->getLogger()->error(
225 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__,
226 [ 'title' => $title->getPrefixedText() ]
227 );
228 return null;
229 }
230 }
231
232 if ( $content && $content->isRedirect() ) {
233 if ( $maxRedirects === null ) {
234 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?: 0;
235 }
236 if ( $maxRedirects > 0 ) {
237 $newTitle = $content->getRedirectTarget();
238 return $newTitle ? $this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
239 }
240 }
241
242 return $content;
243 }
244
245 /**
246 * @param ResourceLoaderContext $context
247 * @return bool
248 */
249 public function shouldEmbedModule( ResourceLoaderContext $context ) {
250 $overrideCallback = $context->getContentOverrideCallback();
251 if ( $overrideCallback && $this->getSource() === 'local' ) {
252 foreach ( $this->getPages( $context ) as $page => $info ) {
253 $title = Title::newFromText( $page );
254 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
255 return true;
256 }
257 }
258 }
259
260 return parent::shouldEmbedModule( $context );
261 }
262
263 /**
264 * @param ResourceLoaderContext $context
265 * @return string JavaScript code
266 */
267 public function getScript( ResourceLoaderContext $context ) {
268 $scripts = '';
269 foreach ( $this->getPages( $context ) as $titleText => $options ) {
270 if ( $options['type'] !== 'script' ) {
271 continue;
272 }
273 $script = $this->getContent( $titleText, $context );
274 if ( strval( $script ) !== '' ) {
275 $script = $this->validateScriptFile( $titleText, $script );
276 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
277 }
278 }
279 return $scripts;
280 }
281
282 /**
283 * @param ResourceLoaderContext $context
284 * @return array
285 */
286 public function getStyles( ResourceLoaderContext $context ) {
287 $styles = [];
288 foreach ( $this->getPages( $context ) as $titleText => $options ) {
289 if ( $options['type'] !== 'style' ) {
290 continue;
291 }
292 $media = $options['media'] ?? 'all';
293 $style = $this->getContent( $titleText, $context );
294 if ( strval( $style ) === '' ) {
295 continue;
296 }
297 if ( $this->getFlip( $context ) ) {
298 $style = CSSJanus::transform( $style, true, false );
299 }
300 $style = MemoizedCallable::call( 'CSSMin::remap',
301 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
302 if ( !isset( $styles[$media] ) ) {
303 $styles[$media] = [];
304 }
305 $style = ResourceLoader::makeComment( $titleText ) . $style;
306 $styles[$media][] = $style;
307 }
308 return $styles;
309 }
310
311 /**
312 * Disable module content versioning.
313 *
314 * This class does not support generating content outside of a module
315 * request due to foreign database support.
316 *
317 * See getDefinitionSummary() for meta-data versioning.
318 *
319 * @return bool
320 */
321 public function enableModuleContentVersion() {
322 return false;
323 }
324
325 /**
326 * @param ResourceLoaderContext $context
327 * @return array
328 */
329 public function getDefinitionSummary( ResourceLoaderContext $context ) {
330 $summary = parent::getDefinitionSummary( $context );
331 $summary[] = [
332 'pages' => $this->getPages( $context ),
333 // Includes meta data of current revisions
334 'titleInfo' => $this->getTitleInfo( $context ),
335 ];
336 return $summary;
337 }
338
339 /**
340 * @param ResourceLoaderContext $context
341 * @return bool
342 */
343 public function isKnownEmpty( ResourceLoaderContext $context ) {
344 $revisions = $this->getTitleInfo( $context );
345
346 // If a module has dependencies it cannot be empty. An empty array will be cast to false
347 if ( $this->getDependencies() ) {
348 return false;
349 }
350 // For user modules, don't needlessly load if there are no non-empty pages
351 if ( $this->getGroup() === 'user' ) {
352 foreach ( $revisions as $revision ) {
353 if ( $revision['page_len'] > 0 ) {
354 // At least one non-empty page, module should be loaded
355 return false;
356 }
357 }
358 return true;
359 }
360
361 // T70488: For other modules (i.e. ones that are called in cached html output) only check
362 // page existance. This ensures that, if some pages in a module are temporarily blanked,
363 // we don't end omit the module's script or link tag on some pages.
364 return count( $revisions ) === 0;
365 }
366
367 private function setTitleInfo( $batchKey, array $titleInfo ) {
368 $this->titleInfo[$batchKey] = $titleInfo;
369 }
370
371 private static function makeTitleKey( LinkTarget $title ) {
372 // Used for keys in titleInfo.
373 return "{$title->getNamespace()}:{$title->getDBkey()}";
374 }
375
376 /**
377 * Get the information about the wiki pages for a given context.
378 * @param ResourceLoaderContext $context
379 * @return array Keyed by page name
380 */
381 protected function getTitleInfo( ResourceLoaderContext $context ) {
382 $dbr = $this->getDB();
383
384 $pageNames = array_keys( $this->getPages( $context ) );
385 sort( $pageNames );
386 $batchKey = implode( '|', $pageNames );
387 if ( !isset( $this->titleInfo[$batchKey] ) ) {
388 $this->titleInfo[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
389 }
390
391 $titleInfo = $this->titleInfo[$batchKey];
392
393 // Override the title info from the overrides, if any
394 $overrideCallback = $context->getContentOverrideCallback();
395 if ( $overrideCallback ) {
396 foreach ( $pageNames as $page ) {
397 $title = Title::newFromText( $page );
398 $content = $title ? call_user_func( $overrideCallback, $title ) : null;
399 if ( $content !== null ) {
400 $titleInfo[$title->getPrefixedText()] = [
401 'page_len' => $content->getSize(),
402 'page_latest' => 'TBD', // None available
403 'page_touched' => wfTimestamp( TS_MW ),
404 ];
405 }
406 }
407 }
408
409 return $titleInfo;
410 }
411
412 /** @return array */
413 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
414 $titleInfo = [];
415 $batch = new LinkBatch;
416 foreach ( $pages as $titleText ) {
417 $title = Title::newFromText( $titleText );
418 if ( $title ) {
419 // Page name may be invalid if user-provided (e.g. gadgets)
420 $batch->addObj( $title );
421 }
422 }
423 if ( !$batch->isEmpty() ) {
424 $res = $db->select( 'page',
425 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
426 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
427 $batch->constructSet( 'page', $db ),
428 $fname
429 );
430 foreach ( $res as $row ) {
431 // Avoid including ids or timestamps of revision/page tables so
432 // that versions are not wasted
433 $title = new TitleValue( (int)$row->page_namespace, $row->page_title );
434 $titleInfo[self::makeTitleKey( $title )] = [
435 'page_len' => $row->page_len,
436 'page_latest' => $row->page_latest,
437 'page_touched' => $row->page_touched,
438 ];
439 }
440 }
441 return $titleInfo;
442 }
443
444 /**
445 * @since 1.28
446 * @param ResourceLoaderContext $context
447 * @param IDatabase $db
448 * @param string[] $moduleNames
449 */
450 public static function preloadTitleInfo(
451 ResourceLoaderContext $context, IDatabase $db, array $moduleNames
452 ) {
453 $rl = $context->getResourceLoader();
454 // getDB() can be overridden to point to a foreign database.
455 // For now, only preload local. In the future, we could preload by wikiID.
456 $allPages = [];
457 /** @var ResourceLoaderWikiModule[] $wikiModules */
458 $wikiModules = [];
459 foreach ( $moduleNames as $name ) {
460 $module = $rl->getModule( $name );
461 if ( $module instanceof self ) {
462 $mDB = $module->getDB();
463 // Subclasses may implement getDB differently
464 if ( $mDB->getDomainID() === $db->getDomainID() ) {
465 $wikiModules[] = $module;
466 $allPages += $module->getPages( $context );
467 }
468 }
469 }
470
471 if ( !$wikiModules ) {
472 // Nothing to preload
473 return;
474 }
475
476 $pageNames = array_keys( $allPages );
477 sort( $pageNames );
478 $hash = sha1( implode( '|', $pageNames ) );
479
480 // Avoid Zend bug where "static::" does not apply LSB in the closure
481 $func = [ static::class, 'fetchTitleInfo' ];
482 $fname = __METHOD__;
483
484 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
485 $allInfo = $cache->getWithSetCallback(
486 $cache->makeGlobalKey( 'resourceloader-titleinfo', $db->getDomainID(), $hash ),
487 $cache::TTL_HOUR,
488 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
489 $setOpts += Database::getCacheSetOptions( $db );
490
491 return call_user_func( $func, $db, $pageNames, $fname );
492 },
493 [
494 'checkKeys' => [
495 $cache->makeGlobalKey( 'resourceloader-titleinfo', $db->getDomainID() ) ]
496 ]
497 );
498
499 foreach ( $wikiModules as $wikiModule ) {
500 $pages = $wikiModule->getPages( $context );
501 // Before we intersect, map the names to canonical form (T145673).
502 $intersect = [];
503 foreach ( $pages as $pageName => $unused ) {
504 $title = Title::newFromText( $pageName );
505 if ( $title ) {
506 $intersect[ self::makeTitleKey( $title ) ] = 1;
507 } else {
508 // Page name may be invalid if user-provided (e.g. gadgets)
509 $rl->getLogger()->info(
510 'Invalid wiki page title "{title}" in ' . __METHOD__,
511 [ 'title' => $pageName ]
512 );
513 }
514 }
515 $info = array_intersect_key( $allInfo, $intersect );
516 $pageNames = array_keys( $pages );
517 sort( $pageNames );
518 $batchKey = implode( '|', $pageNames );
519 $wikiModule->setTitleInfo( $batchKey, $info );
520 }
521 }
522
523 /**
524 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
525 * page change if it was a JS or CSS page
526 *
527 * @param Title $title
528 * @param Revision|null $old Prior page revision
529 * @param Revision|null $new New page revision
530 * @param string $domain Database domain ID
531 * @since 1.28
532 */
533 public static function invalidateModuleCache(
534 Title $title, Revision $old = null, Revision $new = null, $domain
535 ) {
536 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
537
538 Assert::parameterType( 'string', $domain, '$domain' );
539
540 // TODO: MCR: differentiate between page functionality and content model!
541 // Not all pages containing CSS or JS have to be modules! [PageType]
542 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
543 $purge = true;
544 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
545 $purge = true;
546 } else {
547 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
548 }
549
550 if ( $purge ) {
551 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
552 $key = $cache->makeGlobalKey( 'resourceloader-titleinfo', $domain );
553 $cache->touchCheckKey( $key );
554 }
555 }
556
557 /**
558 * @since 1.28
559 * @return string
560 */
561 public function getType() {
562 // Check both because subclasses don't always pass pages via the constructor,
563 // they may also override getPages() instead, in which case we should keep
564 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
565 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
566 }
567 }