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