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