Debian Codegraph @

includes/ResourceLoader/WikiModule.php

raw symbols SCIP
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 namespace MediaWiki\ResourceLoader;
24
25 use CSSJanus;
26 use MediaWiki\Content\Content;
27 use MediaWiki\Json\FormatJson;
28 use MediaWiki\Linker\LinkTarget;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Page\PageIdentity;
32 use MediaWiki\Revision\RevisionRecord;
33 use MediaWiki\Revision\SlotRecord;
34 use MediaWiki\Title\Title;
35 use MediaWiki\Title\TitleValue;
36 use MemoizedCallable;
37 use Wikimedia\Minify\CSSMin;
38 use Wikimedia\Rdbms\Database;
39 use Wikimedia\Rdbms\IReadableDatabase;
40 use Wikimedia\Timestamp\ConvertibleTimestamp;
41
42 /**
43 * Abstraction for ResourceLoader modules which pull from wiki pages
44 *
45 * This can only be used for wiki pages in the MediaWiki and User namespaces,
46 * because of its dependence on the functionality of Title::isUserConfigPage()
47 * and Title::isSiteConfigPage().
48 *
49 * This module supports being used as a placeholder for a module on a remote wiki.
50 * To do so, getDB() must be overloaded to return a foreign database object that
51 * allows local wikis to query page metadata.
52 *
53 * Safe for calls on local wikis are:
54 * - Option getters:
55 * - getGroup()
56 * - getPages()
57 * - Basic methods that strictly involve the foreign database
58 * - getDB()
59 * - isKnownEmpty()
60 * - getTitleInfo()
61 *
62 * @ingroup ResourceLoader
63 * @since 1.17
64 */
65 class WikiModule extends Module {
66 /** @var string Origin defaults to users with sitewide authority */
67 protected $origin = self::ORIGIN_USER_SITEWIDE;
68
69 /**
70 * In-process cache for title info, structured as an array
71 * [
72 * <batchKey> // Pipe-separated list of sorted keys from getPages
73 * => [
74 * <titleKey> => [ // Normalised title key
75 * 'page_len' => ..,
76 * 'page_latest' => ..,
77 * 'page_touched' => ..,
78 * ]
79 * ]
80 * ]
81 * @see self::fetchTitleInfo()
82 * @see self::makeTitleKey()
83 * @var array
84 */
85 protected $titleInfo = [];
86
87 /** @var array List of page names that contain CSS */
88 protected $styles = [];
89
90 /** @var array List of page names that contain JavaScript */
91 protected $scripts = [];
92
93 /** @var array List of page names that contain JSON */
94 protected $datas = [];
95
96 /** @var string|null Group of module */
97 protected $group;
98
99 /**
100 * @param array|null $options For back-compat, this can be omitted in favour of overwriting
101 * getPages.
102 */
103 public function __construct( ?array $options = null ) {
104 if ( $options === null ) {
105 return;
106 }
107
108 foreach ( $options as $member => $option ) {
109 switch ( $member ) {
110 case 'styles':
111 case 'scripts':
112 case 'datas':
113 case 'group':
114 $this->{$member} = $option;
115 break;
116 }
117 }
118 }
119
120 /**
121 * Subclasses should return an associative array of resources in the module.
122 * Keys should be the title of a page in the MediaWiki or User namespace.
123 *
124 * Values should be a nested array of options.
125 * The supported keys are 'type' and (CSS only) 'media'.
126 *
127 * For scripts, 'type' should be 'script'.
128 * For JSON files, 'type' should be 'data'.
129 * For stylesheets, 'type' should be 'style'.
130 *
131 * There is an optional 'media' key, the value of which can be the
132 * medium ('screen', 'print', etc.) of the stylesheet.
133 *
134 * @param Context $context
135 * @return array[]
136 * @phan-return array<string,array{type:string,media?:string}>
137 */
138 protected function getPages( Context $context ) {
139 $config = $this->getConfig();
140 $pages = [];
141
142 // Filter out pages from origins not allowed by the current wiki configuration.
143 if ( $config->get( MainConfigNames::UseSiteJs ) ) {
144 foreach ( $this->scripts as $script ) {
145 $pages[$script] = [ 'type' => 'script' ];
146 }
147 foreach ( $this->datas as $data ) {
148 $pages[$data] = [ 'type' => 'data' ];
149 }
150 }
151
152 if ( $config->get( MainConfigNames::UseSiteCss ) ) {
153 foreach ( $this->styles as $style ) {
154 $pages[$style] = [ 'type' => 'style' ];
155 }
156 }
157
158 return $pages;
159 }
160
161 /**
162 * Get group name
163 *
164 * @return string|null
165 */
166 public function getGroup() {
167 return $this->group;
168 }
169
170 /**
171 * Get the Database handle used for computing the module version.
172 *
173 * Subclasses may override this to return a foreign database, which would
174 * allow them to register a module on wiki A that fetches wiki pages from
175 * wiki B.
176 *
177 * The way this works is that the local module is a placeholder that can
178 * only computer a module version hash. The 'source' of the module must
179 * be set to the foreign wiki directly. Methods getScript() and getContent()
180 * will not use this handle and are not valid on the local wiki.
181 *
182 * @return IReadableDatabase
183 */
184 protected function getDB() {
185 return MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
186 }
187
188 /**
189 * @param string $titleText
190 * @param Context $context
191 * @return null|string
192 * @since 1.32 added the $context parameter
193 */
194 protected function getContent( $titleText, Context $context ) {
195 $pageStore = MediaWikiServices::getInstance()->getPageStore();
196 $title = $pageStore->getPageByText( $titleText );
197 if ( !$title ) {
198 return null; // Bad title
199 }
200
201 $content = $this->getContentObj( $title, $context );
202 if ( !$content ) {
203 return null; // No content found
204 }
205
206 $handler = $content->getContentHandler();
207 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
208 $format = CONTENT_FORMAT_CSS;
209 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
210 $format = CONTENT_FORMAT_JAVASCRIPT;
211 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JSON ) ) {
212 $format = CONTENT_FORMAT_JSON;
213 } else {
214 return null; // Bad content model
215 }
216
217 return $content->serialize( $format );
218 }
219
220 /**
221 * @param PageIdentity $page
222 * @param Context $context
223 * @param int $maxRedirects Maximum number of redirects to follow.
224 * Either 0 or 1.
225 * @return Content|null
226 * @since 1.32 added the $context and $maxRedirects parameters
227 * @internal for testing
228 */
229 protected function getContentObj(
230 PageIdentity $page, Context $context, $maxRedirects = 1
231 ) {
232 $overrideCallback = $context->getContentOverrideCallback();
233 $content = $overrideCallback ? call_user_func( $overrideCallback, $page ) : null;
234 if ( $content ) {
235 if ( !$content instanceof Content ) {
236 $this->getLogger()->error(
237 'Bad content override for "{title}" in ' . __METHOD__,
238 [ 'title' => (string)$page ]
239 );
240 return null;
241 }
242 } else {
243 $revision = MediaWikiServices::getInstance()
244 ->getRevisionLookup()
245 ->getKnownCurrentRevision( $page );
246 if ( !$revision ) {
247 return null;
248 }
249 $content = $revision->getContent( SlotRecord::MAIN, RevisionRecord::RAW );
250
251 if ( !$content ) {
252 $this->getLogger()->error(
253 'Failed to load content of CSS/JS/JSON page "{title}" in ' . __METHOD__,
254 [ 'title' => (string)$page ]
255 );
256 return null;
257 }
258 }
259
260 if ( $maxRedirects > 0 ) {
261 $newTitle = $content->getRedirectTarget();
262 if ( $newTitle ) {
263 return $this->getContentObj( $newTitle, $context, 0 );
264 }
265 }
266
267 return $content;
268 }
269
270 /**
271 * @param Context $context
272 * @return bool
273 */
274 public function shouldEmbedModule( Context $context ) {
275 $overrideCallback = $context->getContentOverrideCallback();
276 if ( $overrideCallback && $this->getSource() === 'local' ) {
277 foreach ( $this->getPages( $context ) as $page => $info ) {
278 $title = Title::newFromText( $page );
279 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
280 return true;
281 }
282 }
283 }
284
285 return parent::shouldEmbedModule( $context );
286 }
287
288 /**
289 * @param Context $context
290 * @return string|array JavaScript code, or a package files array
291 */
292 public function getScript( Context $context ) {
293 if ( $this->isPackaged() ) {
294 return $this->getPackageFiles( $context );
295 } else {
296 $scripts = '';
297 foreach ( $this->getPages( $context ) as $titleText => $options ) {
298 if ( $options['type'] !== 'script' ) {
299 continue;
300 }
301 $script = $this->getContent( $titleText, $context );
302 if ( strval( $script ) !== '' ) {
303 $script = $this->validateScriptFile( $titleText, $script );
304 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
305 }
306 }
307 return $scripts;
308 }
309 }
310
311 /**
312 * Get whether this module is a packaged module.
313 *
314 * If false (the default), JavaScript pages are concatenated and executed as a single
315 * script. JSON pages are not supported.
316 *
317 * If true, the pages are bundled such that each page gets a virtual file name, where only
318 * the "main" script will be executed at first, and other JS or JSON pages may be be imported
319 * in client-side code through the `require()` function.
320 *
321 * @stable to override
322 * @since 1.38
323 * @return bool
324 */
325 protected function isPackaged(): bool {
326 // Packaged mode is disabled by default for backwards compatibility.
327 // Subclasses may opt-in to this feature.
328 return false;
329 }
330
331 /**
332 * @return bool
333 */
334 public function supportsURLLoading() {
335 // If package files are involved, don't support URL loading
336 return !$this->isPackaged();
337 }
338
339 /**
340 * Convert a namespace-formatted page title to a virtual package file name.
341 *
342 * This determines how the page may be imported in client-side code via `require()`.
343 *
344 * @stable to override
345 * @since 1.38
346 * @param string $titleText
347 * @return string
348 */
349 protected function getRequireKey( string $titleText ): string {
350 return $titleText;
351 }
352
353 /**
354 * @param Context $context
355 * @return array{main:?string,files:array<string,array>}
356 */
357 private function getPackageFiles( Context $context ): array {
358 $main = null;
359
360 $files = [];
361 foreach ( $this->getPages( $context ) as $titleText => $options ) {
362 if ( $options['type'] !== 'script' && $options['type'] !== 'data' ) {
363 continue;
364 }
365 $content = $this->getContent( $titleText, $context );
366 if ( strval( $content ) !== '' ) {
367 $fileKey = $this->getRequireKey( $titleText );
368 if ( $options['type'] === 'script' ) {
369 $script = $this->validateScriptFile( $titleText, $content );
370 $files[$fileKey] = [
371 'type' => 'script',
372 'content' => $script,
373 ];
374 // First script becomes the "main" script
375 $main ??= $fileKey;
376 } elseif ( $options['type'] === 'data' ) {
377 $data = FormatJson::decode( $content );
378 if ( $data == null ) {
379 // This is unlikely to happen since we only load JSON from
380 // wiki pages with a JSON content model, which are validated
381 // during edit save.
382 $data = [ 'error' => 'Invalid JSON' ];
383 }
384 $files[$fileKey] = [
385 'type' => 'data',
386 'content' => $data,
387 ];
388 }
389 }
390 }
391
392 return [
393 'main' => $main,
394 'files' => $files,
395 ];
396 }
397
398 /**
399 * @param Context $context
400 * @return array
401 */
402 public function getStyles( Context $context ) {
403 $remoteDir = $this->getConfig()->get( MainConfigNames::ScriptPath );
404 if ( $remoteDir === '' ) {
405 // When the site is configured with the script path at the
406 // document root, MediaWiki uses an empty string but that is
407 // not a valid URI path. Expand to a slash to avoid fatals
408 // later in CSSMin::resolveUrl().
409 // See also FilePath::extractBasePaths, T282280.
410 $remoteDir = '/';
411 }
412
413 $styles = [];
414 foreach ( $this->getPages( $context ) as $titleText => $options ) {
415 if ( $options['type'] !== 'style' ) {
416 continue;
417 }
418 $style = $this->getContent( $titleText, $context );
419 if ( strval( $style ) === '' ) {
420 continue;
421 }
422 if ( $this->getFlip( $context ) ) {
423 $style = CSSJanus::transform( $style, true, false );
424 }
425
426 $style = MemoizedCallable::call(
427 [ CSSMin::class, 'remap' ],
428 [ $style, false, $remoteDir, true ]
429 );
430 $media = $options['media'] ?? 'all';
431 $style = ResourceLoader::makeComment( $titleText ) . $style;
432 $styles[$media][] = $style;
433 }
434 return $styles;
435 }
436
437 /**
438 * Disable module content versioning.
439 *
440 * This class does not support generating content outside of a module
441 * request due to foreign database support.
442 *
443 * See getDefinitionSummary() for meta-data versioning.
444 *
445 * @return bool
446 */
447 public function enableModuleContentVersion() {
448 return false;
449 }
450
451 /**
452 * @param Context $context
453 * @return array
454 */
455 public function getDefinitionSummary( Context $context ) {
456 $summary = parent::getDefinitionSummary( $context );
457 $summary[] = [
458 'pages' => $this->getPages( $context ),
459 // Includes meta data of current revisions
460 'titleInfo' => $this->getTitleInfo( $context ),
461 ];
462 return $summary;
463 }
464
465 /**
466 * @param Context $context
467 * @return bool
468 */
469 public function isKnownEmpty( Context $context ) {
470 // If a module has dependencies it cannot be empty. An empty array will be cast to false
471 if ( $this->getDependencies() ) {
472 return false;
473 }
474
475 // Optimisation: For user modules, don't needlessly load if there are no non-empty pages
476 // This is worthwhile because unlike most modules, user modules require their own
477 // separate embedded request (managed by ClientHtml).
478 $revisions = $this->getTitleInfo( $context );
479 if ( $this->getGroup() === self::GROUP_USER ) {
480 foreach ( $revisions as $revision ) {
481 if ( $revision['page_len'] > 0 ) {
482 // At least one non-empty page, module should be loaded
483 return false;
484 }
485 }
486 return true;
487 }
488
489 // T70488: For non-user modules (i.e. ones that are called in cached HTML output) only check
490 // page existence. This ensures that, if some pages in a module are temporarily blanked,
491 // we don't stop embedding the module's script or link tag on newly cached pages.
492 return count( $revisions ) === 0;
493 }
494
495 private function setTitleInfo( $batchKey, array $titleInfo ) {
496 $this->titleInfo[$batchKey] = $titleInfo;
497 }
498
499 private static function makeTitleKey( LinkTarget $title ) {
500 // Used for keys in titleInfo.
501 return "{$title->getNamespace()}:{$title->getDBkey()}";
502 }
503
504 /**
505 * Get the information about the wiki pages for a given context.
506 * @param Context $context
507 * @return array[] Keyed by page name
508 */
509 protected function getTitleInfo( Context $context ) {
510 $pageNames = array_keys( $this->getPages( $context ) );
511 sort( $pageNames );
512 $batchKey = implode( '|', $pageNames );
513 if ( !isset( $this->titleInfo[$batchKey] ) ) {
514 $this->titleInfo[$batchKey] = static::fetchTitleInfo( $this->getDB(), $pageNames, __METHOD__ );
515 }
516
517 $titleInfo = $this->titleInfo[$batchKey];
518
519 // Override the title info from the overrides, if any
520 $overrideCallback = $context->getContentOverrideCallback();
521 if ( $overrideCallback ) {
522 foreach ( $pageNames as $page ) {
523 $title = Title::newFromText( $page );
524 $content = $title ? call_user_func( $overrideCallback, $title ) : null;
525 if ( $content !== null ) {
526 $titleInfo[$title->getPrefixedText()] = [
527 'page_len' => $content->getSize(),
528 'page_latest' => 'TBD', // None available
529 'page_touched' => ConvertibleTimestamp::now( TS_MW ),
530 ];
531 }
532 }
533 }
534
535 return $titleInfo;
536 }
537
538 /**
539 * @param IReadableDatabase $db
540 * @param string[] $pages
541 * @param string $fname @phan-mandatory-param
542 * @return array
543 */
544 protected static function fetchTitleInfo( IReadableDatabase $db, array $pages, $fname = __METHOD__ ) {
545 $titleInfo = [];
546 $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
547 $batch = $linkBatchFactory->newLinkBatch();
548 foreach ( $pages as $titleText ) {
549 $title = Title::newFromText( $titleText );
550 if ( $title ) {
551 // Page name may be invalid if user-provided (e.g. gadgets)
552 $batch->addObj( $title );
553 }
554 }
555 if ( !$batch->isEmpty() ) {
556 $res = $db->newSelectQueryBuilder()
557 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
558 ->select( [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ] )
559 ->from( 'page' )
560 ->where( $batch->constructSet( 'page', $db ) )
561 ->caller( $fname )->fetchResultSet();
562 foreach ( $res as $row ) {
563 // Avoid including ids or timestamps of revision/page tables so
564 // that versions are not wasted
565 $title = new TitleValue( (int)$row->page_namespace, $row->page_title );
566 $titleInfo[self::makeTitleKey( $title )] = [
567 'page_len' => $row->page_len,
568 'page_latest' => $row->page_latest,
569 'page_touched' => ConvertibleTimestamp::convert( TS_MW, $row->page_touched ),
570 ];
571 }
572 }
573 return $titleInfo;
574 }
575
576 /**
577 * Batched version of WikiModule::getTitleInfo
578 *
579 * Title info for the passed modules is cached together. On index.php, OutputPage improves
580 * cache use by having one batch shared between all users (site-wide modules) and a batch
581 * for current-user modules.
582 *
583 * @since 1.28
584 * @internal For use by ResourceLoader and OutputPage only
585 * @param Context $context
586 * @param string[] $moduleNames
587 */
588 public static function preloadTitleInfo(
589 Context $context, array $moduleNames
590 ) {
591 $rl = $context->getResourceLoader();
592 // getDB() can be overridden to point to a foreign database.
593 // Group pages by database to ensure we fetch titles from the correct database.
594 // By preloading both local and foreign titles, this method doesn't depend
595 // on knowing the local database.
596
597 /** @var array<string,array{db:IReadableDatabase,pages:string[],modules:WikiModule[]}> $byDomain */
598 $byDomain = [];
599 foreach ( $moduleNames as $name ) {
600 $module = $rl->getModule( $name );
601 if ( $module instanceof self ) {
602 // Subclasses may implement getDB differently
603 $db = $module->getDB();
604 $domain = $db->getDomainID();
605
606 $byDomain[ $domain ] ??= [ 'db' => $db, 'pages' => [], 'modules' => [] ];
607 $byDomain[ $domain ]['pages'] = array_merge(
608 $byDomain[ $domain ]['pages'],
609 array_keys( $module->getPages( $context ) )
610 );
611 $byDomain[ $domain ]['modules'][] = $module;
612 }
613 }
614
615 if ( !$byDomain ) {
616 // Nothing to preload
617 return;
618 }
619
620 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
621 $fname = __METHOD__;
622
623 foreach ( $byDomain as $domainId => $batch ) {
624 // Fetch title info
625 sort( $batch['pages'] );
626 $pagesHash = sha1( implode( '|', $batch['pages'] ) );
627 $allInfo = $cache->getWithSetCallback(
628 $cache->makeGlobalKey( 'resourceloader-titleinfo', $domainId, $pagesHash ),
629 $cache::TTL_HOUR,
630 static function ( $curVal, &$ttl, array &$setOpts ) use ( $batch, $fname ) {
631 $setOpts += Database::getCacheSetOptions( $batch['db'] );
632 return static::fetchTitleInfo( $batch['db'], $batch['pages'], $fname );
633 },
634 [
635 'checkKeys' => [
636 $cache->makeGlobalKey( 'resourceloader-titleinfo', $domainId ) ]
637 ]
638 );
639
640 // Inject to WikiModule objects
641 foreach ( $batch['modules'] as $wikiModule ) {
642 $pages = $wikiModule->getPages( $context );
643 $info = [];
644 foreach ( $pages as $pageName => $unused ) {
645 // Map page name to canonical form (T145673).
646 $title = Title::newFromText( $pageName );
647 if ( !$title ) {
648 // Page name may be invalid if user-provided (e.g. gadgets)
649 $rl->getLogger()->info(
650 'Invalid wiki page title "{title}" in ' . __METHOD__,
651 [ 'title' => $pageName ]
652 );
653 continue;
654 }
655 $infoKey = self::makeTitleKey( $title );
656 if ( isset( $allInfo[$infoKey] ) ) {
657 $info[$infoKey] = $allInfo[$infoKey];
658 }
659 }
660 $pageNames = array_keys( $pages );
661 sort( $pageNames );
662 $batchKey = implode( '|', $pageNames );
663 $wikiModule->setTitleInfo( $batchKey, $info );
664 }
665 }
666 }
667
668 /**
669 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
670 * page change if it was a JS or CSS page
671 *
672 * @internal
673 * @param PageIdentity $page
674 * @param RevisionRecord|null $old Prior page revision
675 * @param RevisionRecord|null $new New page revision
676 * @param string $domain Database domain ID
677 */
678 public static function invalidateModuleCache(
679 PageIdentity $page,
680 ?RevisionRecord $old,
681 ?RevisionRecord $new,
682 string $domain
683 ) {
684 static $models = [ CONTENT_MODEL_CSS, CONTENT_MODEL_JAVASCRIPT ];
685
686 $purge = false;
687 // TODO: MCR: differentiate between page functionality and content model!
688 // Not all pages containing CSS or JS have to be modules! [PageType]
689 if ( $old ) {
690 $oldModel = $old->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )->getModel();
691 if ( in_array( $oldModel, $models ) ) {
692 $purge = true;
693 }
694 }
695
696 if ( !$purge && $new ) {
697 $newModel = $new->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )->getModel();
698 if ( in_array( $newModel, $models ) ) {
699 $purge = true;
700 }
701 }
702
703 if ( !$purge ) {
704 $title = Title::newFromPageIdentity( $page );
705 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
706 }
707
708 if ( $purge ) {
709 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
710 $key = $cache->makeGlobalKey( 'resourceloader-titleinfo', $domain );
711 $cache->touchCheckKey( $key );
712 }
713 }
714
715 /**
716 * @since 1.28
717 * @return string
718 */
719 public function getType() {
720 // Check both because subclasses don't always pass pages via the constructor,
721 // they may also override getPages() instead, in which case we should keep
722 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
723 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
724 }
725 }