Merge "Convert file delete to use OOUI"
[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 Wikimedia\Rdbms\Database;
27 use Wikimedia\Rdbms\IDatabase;
28
29 /**
30 * Abstraction for ResourceLoader modules which pull from wiki pages
31 *
32 * This can only be used for wiki pages in the MediaWiki and User namespaces,
33 * because of its dependence on the functionality of Title::isUserConfigPage()
34 * and Title::isSiteConfigPage().
35 *
36 * This module supports being used as a placeholder for a module on a remote wiki.
37 * To do so, getDB() must be overloaded to return a foreign database object that
38 * allows local wikis to query page metadata.
39 *
40 * Safe for calls on local wikis are:
41 * - Option getters:
42 * - getGroup()
43 * - getPages()
44 * - Basic methods that strictly involve the foreign database
45 * - getDB()
46 * - isKnownEmpty()
47 * - getTitleInfo()
48 */
49 class ResourceLoaderWikiModule extends ResourceLoaderModule {
50
51 // Origin defaults to users with sitewide authority
52 protected $origin = self::ORIGIN_USER_SITEWIDE;
53
54 // In-process cache for title info, structured as an array
55 // [
56 // <batchKey> // Pipe-separated list of sorted keys from getPages
57 // => [
58 // <titleKey> => [ // Normalised title key
59 // 'page_len' => ..,
60 // 'page_latest' => ..,
61 // 'page_touched' => ..,
62 // ]
63 // ]
64 // ]
65 // @see self::fetchTitleInfo()
66 // @see self::makeTitleKey()
67 protected $titleInfo = [];
68
69 // List of page names that contain CSS
70 protected $styles = [];
71
72 // List of page names that contain JavaScript
73 protected $scripts = [];
74
75 // Group of module
76 protected $group;
77
78 /**
79 * @param array|null $options For back-compat, this can be omitted in favour of overwriting
80 * getPages.
81 */
82 public function __construct( array $options = null ) {
83 if ( is_null( $options ) ) {
84 return;
85 }
86
87 foreach ( $options as $member => $option ) {
88 switch ( $member ) {
89 case 'styles':
90 case 'scripts':
91 case 'group':
92 case 'targets':
93 $this->{$member} = $option;
94 break;
95 }
96 }
97 }
98
99 /**
100 * Subclasses should return an associative array of resources in the module.
101 * Keys should be the title of a page in the MediaWiki or User namespace.
102 *
103 * Values should be a nested array of options. The supported keys are 'type' and
104 * (CSS only) 'media'.
105 *
106 * For scripts, 'type' should be 'script'.
107 *
108 * For stylesheets, 'type' should be 'style'.
109 * There is an optional media key, the value of which can be the
110 * medium ('screen', 'print', etc.) of the stylesheet.
111 *
112 * @param ResourceLoaderContext $context
113 * @return array
114 */
115 protected function getPages( ResourceLoaderContext $context ) {
116 $config = $this->getConfig();
117 $pages = [];
118
119 // Filter out pages from origins not allowed by the current wiki configuration.
120 if ( $config->get( 'UseSiteJs' ) ) {
121 foreach ( $this->scripts as $script ) {
122 $pages[$script] = [ 'type' => 'script' ];
123 }
124 }
125
126 if ( $config->get( 'UseSiteCss' ) ) {
127 foreach ( $this->styles as $style ) {
128 $pages[$style] = [ 'type' => 'style' ];
129 }
130 }
131
132 return $pages;
133 }
134
135 /**
136 * Get group name
137 *
138 * @return string
139 */
140 public function getGroup() {
141 return $this->group;
142 }
143
144 /**
145 * Get the Database object used in getTitleInfo().
146 *
147 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
148 * database object, or null if getTitleInfo() shouldn't access the database.
149 *
150 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
151 * In particular, it doesn't work for getContent() or getScript() etc.
152 *
153 * @return IDatabase|null
154 */
155 protected function getDB() {
156 return wfGetDB( DB_REPLICA );
157 }
158
159 /**
160 * @param string $titleText
161 * @param ResourceLoaderContext|null $context (but passing null is deprecated)
162 * @return null|string
163 * @since 1.32 added the $context parameter
164 */
165 protected function getContent( $titleText, ResourceLoaderContext $context = null ) {
166 $title = Title::newFromText( $titleText );
167 if ( !$title ) {
168 return null; // Bad title
169 }
170
171 $content = $this->getContentObj( $title, $context );
172 if ( !$content ) {
173 return null; // No content found
174 }
175
176 $handler = $content->getContentHandler();
177 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
178 $format = CONTENT_FORMAT_CSS;
179 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
180 $format = CONTENT_FORMAT_JAVASCRIPT;
181 } else {
182 return null; // Bad content model
183 }
184
185 return $content->serialize( $format );
186 }
187
188 /**
189 * @param Title $title
190 * @param ResourceLoaderContext|null $context (but passing null is deprecated)
191 * @param int|null $maxRedirects Maximum number of redirects to follow. If
192 * null, uses $wgMaxRedirects
193 * @return Content|null
194 * @since 1.32 added the $context and $maxRedirects parameters
195 */
196 protected function getContentObj(
197 Title $title, ResourceLoaderContext $context = null, $maxRedirects = null
198 ) {
199 if ( $context === null ) {
200 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.32' );
201 }
202
203 $overrideCallback = $context ? $context->getContentOverrideCallback() : null;
204 $content = $overrideCallback ? call_user_func( $overrideCallback, $title ) : null;
205 if ( $content ) {
206 if ( !$content instanceof Content ) {
207 $this->getLogger()->error(
208 'Bad content override for "{title}" in ' . __METHOD__,
209 [ 'title' => $title->getPrefixedText() ]
210 );
211 return null;
212 }
213 } else {
214 $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
215 if ( !$revision ) {
216 return null;
217 }
218 $content = $revision->getContent( Revision::RAW );
219
220 if ( !$content ) {
221 $this->getLogger()->error(
222 'Failed to load content of JS/CSS page "{title}" in ' . __METHOD__,
223 [ 'title' => $title->getPrefixedText() ]
224 );
225 return null;
226 }
227 }
228
229 if ( $content && $content->isRedirect() ) {
230 if ( $maxRedirects === null ) {
231 $maxRedirects = $this->getConfig()->get( 'MaxRedirects' ) ?: 0;
232 }
233 if ( $maxRedirects > 0 ) {
234 $newTitle = $content->getRedirectTarget();
235 return $newTitle ? $this->getContentObj( $newTitle, $context, $maxRedirects - 1 ) : null;
236 }
237 }
238
239 return $content;
240 }
241
242 /**
243 * @param ResourceLoaderContext $context
244 * @return bool
245 */
246 public function shouldEmbedModule( ResourceLoaderContext $context ) {
247 $overrideCallback = $context->getContentOverrideCallback();
248 if ( $overrideCallback && $this->getSource() === 'local' ) {
249 foreach ( $this->getPages( $context ) as $page => $info ) {
250 $title = Title::newFromText( $page );
251 if ( $title && call_user_func( $overrideCallback, $title ) !== null ) {
252 return true;
253 }
254 }
255 }
256
257 return parent::shouldEmbedModule( $context );
258 }
259
260 /**
261 * @param ResourceLoaderContext $context
262 * @return string JavaScript code
263 */
264 public function getScript( ResourceLoaderContext $context ) {
265 $scripts = '';
266 foreach ( $this->getPages( $context ) as $titleText => $options ) {
267 if ( $options['type'] !== 'script' ) {
268 continue;
269 }
270 $script = $this->getContent( $titleText, $context );
271 if ( strval( $script ) !== '' ) {
272 $script = $this->validateScriptFile( $titleText, $script );
273 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
274 }
275 }
276 return $scripts;
277 }
278
279 /**
280 * @param ResourceLoaderContext $context
281 * @return array
282 */
283 public function getStyles( ResourceLoaderContext $context ) {
284 $styles = [];
285 foreach ( $this->getPages( $context ) as $titleText => $options ) {
286 if ( $options['type'] !== 'style' ) {
287 continue;
288 }
289 $media = $options['media'] ?? 'all';
290 $style = $this->getContent( $titleText, $context );
291 if ( strval( $style ) === '' ) {
292 continue;
293 }
294 if ( $this->getFlip( $context ) ) {
295 $style = CSSJanus::transform( $style, true, false );
296 }
297 $style = MemoizedCallable::call( 'CSSMin::remap',
298 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
299 if ( !isset( $styles[$media] ) ) {
300 $styles[$media] = [];
301 }
302 $style = ResourceLoader::makeComment( $titleText ) . $style;
303 $styles[$media][] = $style;
304 }
305 return $styles;
306 }
307
308 /**
309 * Disable module content versioning.
310 *
311 * This class does not support generating content outside of a module
312 * request due to foreign database support.
313 *
314 * See getDefinitionSummary() for meta-data versioning.
315 *
316 * @return bool
317 */
318 public function enableModuleContentVersion() {
319 return false;
320 }
321
322 /**
323 * @param ResourceLoaderContext $context
324 * @return array
325 */
326 public function getDefinitionSummary( ResourceLoaderContext $context ) {
327 $summary = parent::getDefinitionSummary( $context );
328 $summary[] = [
329 'pages' => $this->getPages( $context ),
330 // Includes meta data of current revisions
331 'titleInfo' => $this->getTitleInfo( $context ),
332 ];
333 return $summary;
334 }
335
336 /**
337 * @param ResourceLoaderContext $context
338 * @return bool
339 */
340 public function isKnownEmpty( ResourceLoaderContext $context ) {
341 $revisions = $this->getTitleInfo( $context );
342
343 // If a module has dependencies it cannot be empty. An empty array will be cast to false
344 if ( $this->getDependencies() ) {
345 return false;
346 }
347 // For user modules, don't needlessly load if there are no non-empty pages
348 if ( $this->getGroup() === 'user' ) {
349 foreach ( $revisions as $revision ) {
350 if ( $revision['page_len'] > 0 ) {
351 // At least one non-empty page, module should be loaded
352 return false;
353 }
354 }
355 return true;
356 }
357
358 // T70488: For other modules (i.e. ones that are called in cached html output) only check
359 // page existance. This ensures that, if some pages in a module are temporarily blanked,
360 // we don't end omit the module's script or link tag on some pages.
361 return count( $revisions ) === 0;
362 }
363
364 private function setTitleInfo( $batchKey, array $titleInfo ) {
365 $this->titleInfo[$batchKey] = $titleInfo;
366 }
367
368 private static function makeTitleKey( LinkTarget $title ) {
369 // Used for keys in titleInfo.
370 return "{$title->getNamespace()}:{$title->getDBkey()}";
371 }
372
373 /**
374 * Get the information about the wiki pages for a given context.
375 * @param ResourceLoaderContext $context
376 * @return array Keyed by page name
377 */
378 protected function getTitleInfo( ResourceLoaderContext $context ) {
379 $dbr = $this->getDB();
380 if ( !$dbr ) {
381 // We're dealing with a subclass that doesn't have a DB
382 return [];
383 }
384
385 $pageNames = array_keys( $this->getPages( $context ) );
386 sort( $pageNames );
387 $batchKey = implode( '|', $pageNames );
388 if ( !isset( $this->titleInfo[$batchKey] ) ) {
389 $this->titleInfo[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
390 }
391
392 $titleInfo = $this->titleInfo[$batchKey];
393
394 // Override the title info from the overrides, if any
395 $overrideCallback = $context->getContentOverrideCallback();
396 if ( $overrideCallback ) {
397 foreach ( $pageNames as $page ) {
398 $title = Title::newFromText( $page );
399 $content = $title ? call_user_func( $overrideCallback, $title ) : null;
400 if ( $content !== null ) {
401 $titleInfo[$title->getPrefixedText()] = [
402 'page_len' => $content->getSize(),
403 'page_latest' => 'TBD', // None available
404 'page_touched' => wfTimestamp( TS_MW ),
405 ];
406 }
407 }
408 }
409
410 return $titleInfo;
411 }
412
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 disable getDB and implement getTitleInfo differently
464 if ( $mDB && $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 = ObjectCache::getMainWANInstance();
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 $wikiId
531 * @since 1.28
532 */
533 public static function invalidateModuleCache(
534 Title $title, Revision $old = null, Revision $new = null, $wikiId
535 ) {
536 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
537
538 // TODO: MCR: differentiate between page functionality and content model!
539 // Not all pages containing CSS or JS have to be modules! [PageType]
540 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
541 $purge = true;
542 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
543 $purge = true;
544 } else {
545 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
546 }
547
548 if ( $purge ) {
549 $cache = ObjectCache::getMainWANInstance();
550 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
551 $cache->touchCheckKey( $key );
552 }
553 }
554
555 /**
556 * @since 1.28
557 * @return string
558 */
559 public function getType() {
560 // Check both because subclasses don't always pass pages via the constructor,
561 // they may also override getPages() instead, in which case we should keep
562 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
563 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
564 }
565 }