Merge "MessagesEs.php: add non-camelcase names to some special page names"
[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 * @return null|string
161 */
162 protected function getContent( $titleText ) {
163 $title = Title::newFromText( $titleText );
164 if ( !$title ) {
165 return null; // Bad title
166 }
167
168 // If the page is a redirect, follow the redirect.
169 if ( $title->isRedirect() ) {
170 $content = $this->getContentObj( $title );
171 $title = $content ? $content->getUltimateRedirectTarget() : null;
172 if ( !$title ) {
173 return null; // Dead redirect
174 }
175 }
176
177 $handler = ContentHandler::getForTitle( $title );
178 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
179 $format = CONTENT_FORMAT_CSS;
180 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
181 $format = CONTENT_FORMAT_JAVASCRIPT;
182 } else {
183 return null; // Bad content model
184 }
185
186 $content = $this->getContentObj( $title );
187 if ( !$content ) {
188 return null; // No content found
189 }
190
191 return $content->serialize( $format );
192 }
193
194 /**
195 * @param Title $title
196 * @return Content|null
197 */
198 protected function getContentObj( Title $title ) {
199 $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title );
200 if ( !$revision ) {
201 return null;
202 }
203 $content = $revision->getContent( Revision::RAW );
204 if ( !$content ) {
205 wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
206 return null;
207 }
208 return $content;
209 }
210
211 /**
212 * @param ResourceLoaderContext $context
213 * @return string JavaScript code
214 */
215 public function getScript( ResourceLoaderContext $context ) {
216 $scripts = '';
217 foreach ( $this->getPages( $context ) as $titleText => $options ) {
218 if ( $options['type'] !== 'script' ) {
219 continue;
220 }
221 $script = $this->getContent( $titleText );
222 if ( strval( $script ) !== '' ) {
223 $script = $this->validateScriptFile( $titleText, $script );
224 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
225 }
226 }
227 return $scripts;
228 }
229
230 /**
231 * @param ResourceLoaderContext $context
232 * @return array
233 */
234 public function getStyles( ResourceLoaderContext $context ) {
235 $styles = [];
236 foreach ( $this->getPages( $context ) as $titleText => $options ) {
237 if ( $options['type'] !== 'style' ) {
238 continue;
239 }
240 $media = isset( $options['media'] ) ? $options['media'] : 'all';
241 $style = $this->getContent( $titleText );
242 if ( strval( $style ) === '' ) {
243 continue;
244 }
245 if ( $this->getFlip( $context ) ) {
246 $style = CSSJanus::transform( $style, true, false );
247 }
248 $style = MemoizedCallable::call( 'CSSMin::remap',
249 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
250 if ( !isset( $styles[$media] ) ) {
251 $styles[$media] = [];
252 }
253 $style = ResourceLoader::makeComment( $titleText ) . $style;
254 $styles[$media][] = $style;
255 }
256 return $styles;
257 }
258
259 /**
260 * Disable module content versioning.
261 *
262 * This class does not support generating content outside of a module
263 * request due to foreign database support.
264 *
265 * See getDefinitionSummary() for meta-data versioning.
266 *
267 * @return bool
268 */
269 public function enableModuleContentVersion() {
270 return false;
271 }
272
273 /**
274 * @param ResourceLoaderContext $context
275 * @return array
276 */
277 public function getDefinitionSummary( ResourceLoaderContext $context ) {
278 $summary = parent::getDefinitionSummary( $context );
279 $summary[] = [
280 'pages' => $this->getPages( $context ),
281 // Includes meta data of current revisions
282 'titleInfo' => $this->getTitleInfo( $context ),
283 ];
284 return $summary;
285 }
286
287 /**
288 * @param ResourceLoaderContext $context
289 * @return bool
290 */
291 public function isKnownEmpty( ResourceLoaderContext $context ) {
292 $revisions = $this->getTitleInfo( $context );
293
294 // For user modules, don't needlessly load if there are no non-empty pages
295 if ( $this->getGroup() === 'user' ) {
296 foreach ( $revisions as $revision ) {
297 if ( $revision['page_len'] > 0 ) {
298 // At least one non-empty page, module should be loaded
299 return false;
300 }
301 }
302 return true;
303 }
304
305 // T70488: For other modules (i.e. ones that are called in cached html output) only check
306 // page existance. This ensures that, if some pages in a module are temporarily blanked,
307 // we don't end omit the module's script or link tag on some pages.
308 return count( $revisions ) === 0;
309 }
310
311 private function setTitleInfo( $batchKey, array $titleInfo ) {
312 $this->titleInfo[$batchKey] = $titleInfo;
313 }
314
315 private static function makeTitleKey( LinkTarget $title ) {
316 // Used for keys in titleInfo.
317 return "{$title->getNamespace()}:{$title->getDBkey()}";
318 }
319
320 /**
321 * Get the information about the wiki pages for a given context.
322 * @param ResourceLoaderContext $context
323 * @return array Keyed by page name
324 */
325 protected function getTitleInfo( ResourceLoaderContext $context ) {
326 $dbr = $this->getDB();
327 if ( !$dbr ) {
328 // We're dealing with a subclass that doesn't have a DB
329 return [];
330 }
331
332 $pageNames = array_keys( $this->getPages( $context ) );
333 sort( $pageNames );
334 $batchKey = implode( '|', $pageNames );
335 if ( !isset( $this->titleInfo[$batchKey] ) ) {
336 $this->titleInfo[$batchKey] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
337 }
338 return $this->titleInfo[$batchKey];
339 }
340
341 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
342 $titleInfo = [];
343 $batch = new LinkBatch;
344 foreach ( $pages as $titleText ) {
345 $title = Title::newFromText( $titleText );
346 if ( $title ) {
347 // Page name may be invalid if user-provided (e.g. gadgets)
348 $batch->addObj( $title );
349 }
350 }
351 if ( !$batch->isEmpty() ) {
352 $res = $db->select( 'page',
353 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
354 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
355 $batch->constructSet( 'page', $db ),
356 $fname
357 );
358 foreach ( $res as $row ) {
359 // Avoid including ids or timestamps of revision/page tables so
360 // that versions are not wasted
361 $title = new TitleValue( (int)$row->page_namespace, $row->page_title );
362 $titleInfo[ self::makeTitleKey( $title ) ] = [
363 'page_len' => $row->page_len,
364 'page_latest' => $row->page_latest,
365 'page_touched' => $row->page_touched,
366 ];
367 }
368 }
369 return $titleInfo;
370 }
371
372 /**
373 * @since 1.28
374 * @param ResourceLoaderContext $context
375 * @param IDatabase $db
376 * @param string[] $moduleNames
377 */
378 public static function preloadTitleInfo(
379 ResourceLoaderContext $context, IDatabase $db, array $moduleNames
380 ) {
381 $rl = $context->getResourceLoader();
382 // getDB() can be overridden to point to a foreign database.
383 // For now, only preload local. In the future, we could preload by wikiID.
384 $allPages = [];
385 /** @var ResourceLoaderWikiModule[] $wikiModules */
386 $wikiModules = [];
387 foreach ( $moduleNames as $name ) {
388 $module = $rl->getModule( $name );
389 if ( $module instanceof self ) {
390 $mDB = $module->getDB();
391 // Subclasses may disable getDB and implement getTitleInfo differently
392 if ( $mDB && $mDB->getDomainID() === $db->getDomainID() ) {
393 $wikiModules[] = $module;
394 $allPages += $module->getPages( $context );
395 }
396 }
397 }
398
399 if ( !$wikiModules ) {
400 // Nothing to preload
401 return;
402 }
403
404 $pageNames = array_keys( $allPages );
405 sort( $pageNames );
406 $hash = sha1( implode( '|', $pageNames ) );
407
408 // Avoid Zend bug where "static::" does not apply LSB in the closure
409 $func = [ static::class, 'fetchTitleInfo' ];
410 $fname = __METHOD__;
411
412 $cache = ObjectCache::getMainWANInstance();
413 $allInfo = $cache->getWithSetCallback(
414 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID(), $hash ),
415 $cache::TTL_HOUR,
416 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
417 $setOpts += Database::getCacheSetOptions( $db );
418
419 return call_user_func( $func, $db, $pageNames, $fname );
420 },
421 [
422 'checkKeys' => [
423 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getDomainID() ) ]
424 ]
425 );
426
427 foreach ( $wikiModules as $wikiModule ) {
428 $pages = $wikiModule->getPages( $context );
429 // Before we intersect, map the names to canonical form (T145673).
430 $intersect = [];
431 foreach ( $pages as $pageName => $unused ) {
432 $title = Title::newFromText( $pageName );
433 if ( $title ) {
434 $intersect[ self::makeTitleKey( $title ) ] = 1;
435 } else {
436 // Page name may be invalid if user-provided (e.g. gadgets)
437 $rl->getLogger()->info(
438 'Invalid wiki page title "{title}" in ' . __METHOD__,
439 [ 'title' => $pageName ]
440 );
441 }
442 }
443 $info = array_intersect_key( $allInfo, $intersect );
444 $pageNames = array_keys( $pages );
445 sort( $pageNames );
446 $batchKey = implode( '|', $pageNames );
447 $wikiModule->setTitleInfo( $batchKey, $info );
448 }
449 }
450
451 /**
452 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
453 * page change if it was a JS or CSS page
454 *
455 * @param Title $title
456 * @param Revision|null $old Prior page revision
457 * @param Revision|null $new New page revision
458 * @param string $wikiId
459 * @since 1.28
460 */
461 public static function invalidateModuleCache(
462 Title $title, Revision $old = null, Revision $new = null, $wikiId
463 ) {
464 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
465
466 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
467 $purge = true;
468 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
469 $purge = true;
470 } else {
471 $purge = ( $title->isSiteConfigPage() || $title->isUserConfigPage() );
472 }
473
474 if ( $purge ) {
475 $cache = ObjectCache::getMainWANInstance();
476 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
477 $cache->touchCheckKey( $key );
478 }
479 }
480
481 /**
482 * @since 1.28
483 * @return string
484 */
485 public function getType() {
486 // Check both because subclasses don't always pass pages via the constructor,
487 // they may also override getPages() instead, in which case we should keep
488 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
489 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
490 }
491 }