Merge "Add missing @group Database tags in tests"
[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 /**
26 * Abstraction for ResourceLoader modules which pull from wiki pages
27 *
28 * This can only be used for wiki pages in the MediaWiki and User namespaces,
29 * because of its dependence on the functionality of Title::isCssJsSubpage
30 * and Title::isCssOrJsPage().
31 *
32 * This module supports being used as a placeholder for a module on a remote wiki.
33 * To do so, getDB() must be overloaded to return a foreign database object that
34 * allows local wikis to query page metadata.
35 *
36 * Safe for calls on local wikis are:
37 * - Option getters:
38 * - getGroup()
39 * - getPages()
40 * - Basic methods that strictly involve the foreign database
41 * - getDB()
42 * - isKnownEmpty()
43 * - getTitleInfo()
44 */
45 class ResourceLoaderWikiModule extends ResourceLoaderModule {
46
47 // Origin defaults to users with sitewide authority
48 protected $origin = self::ORIGIN_USER_SITEWIDE;
49
50 // In-process cache for title info
51 protected $titleInfo = [];
52
53 // List of page names that contain CSS
54 protected $styles = [];
55
56 // List of page names that contain JavaScript
57 protected $scripts = [];
58
59 // Group of module
60 protected $group;
61
62 /**
63 * @param array $options For back-compat, this can be omitted in favour of overwriting getPages.
64 */
65 public function __construct( array $options = null ) {
66 if ( is_null( $options ) ) {
67 return;
68 }
69
70 foreach ( $options as $member => $option ) {
71 switch ( $member ) {
72 case 'styles':
73 case 'scripts':
74 case 'group':
75 case 'targets':
76 $this->{$member} = $option;
77 break;
78 }
79 }
80 }
81
82 /**
83 * Subclasses should return an associative array of resources in the module.
84 * Keys should be the title of a page in the MediaWiki or User namespace.
85 *
86 * Values should be a nested array of options. The supported keys are 'type' and
87 * (CSS only) 'media'.
88 *
89 * For scripts, 'type' should be 'script'.
90 *
91 * For stylesheets, 'type' should be 'style'.
92 * There is an optional media key, the value of which can be the
93 * medium ('screen', 'print', etc.) of the stylesheet.
94 *
95 * @param ResourceLoaderContext $context
96 * @return array
97 */
98 protected function getPages( ResourceLoaderContext $context ) {
99 $config = $this->getConfig();
100 $pages = [];
101
102 // Filter out pages from origins not allowed by the current wiki configuration.
103 if ( $config->get( 'UseSiteJs' ) ) {
104 foreach ( $this->scripts as $script ) {
105 $pages[$script] = [ 'type' => 'script' ];
106 }
107 }
108
109 if ( $config->get( 'UseSiteCss' ) ) {
110 foreach ( $this->styles as $style ) {
111 $pages[$style] = [ 'type' => 'style' ];
112 }
113 }
114
115 return $pages;
116 }
117
118 /**
119 * Get group name
120 *
121 * @return string
122 */
123 public function getGroup() {
124 return $this->group;
125 }
126
127 /**
128 * Get the Database object used in getTitleInfo().
129 *
130 * Defaults to the local replica DB. Subclasses may want to override this to return a foreign
131 * database object, or null if getTitleInfo() shouldn't access the database.
132 *
133 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
134 * In particular, it doesn't work for getContent() or getScript() etc.
135 *
136 * @return IDatabase|null
137 */
138 protected function getDB() {
139 return wfGetDB( DB_REPLICA );
140 }
141
142 /**
143 * @param string $titleText
144 * @return null|string
145 */
146 protected function getContent( $titleText ) {
147 $title = Title::newFromText( $titleText );
148 if ( !$title ) {
149 return null;
150 }
151
152 // If the page is a redirect, follow the redirect.
153 if ( $title->isRedirect() ) {
154 $content = $this->getContentObj( $title );
155 $title = $content ? $content->getUltimateRedirectTarget() : null;
156 if ( !$title ) {
157 return null;
158 }
159 }
160
161 $handler = ContentHandler::getForTitle( $title );
162 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
163 $format = CONTENT_FORMAT_CSS;
164 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
165 $format = CONTENT_FORMAT_JAVASCRIPT;
166 } else {
167 return null;
168 }
169
170 $content = $this->getContentObj( $title );
171 if ( !$content ) {
172 return null;
173 }
174
175 return $content->serialize( $format );
176 }
177
178 /**
179 * @param Title $title
180 * @return Content|null
181 */
182 protected function getContentObj( Title $title ) {
183 $revision = Revision::newKnownCurrent( wfGetDB( DB_REPLICA ), $title->getArticleID(),
184 $title->getLatestRevID() );
185 if ( !$revision ) {
186 return null;
187 }
188 $revision->setTitle( $title );
189 $content = $revision->getContent( Revision::RAW );
190 if ( !$content ) {
191 wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
192 return null;
193 }
194 return $content;
195 }
196
197 /**
198 * @param ResourceLoaderContext $context
199 * @return string
200 */
201 public function getScript( ResourceLoaderContext $context ) {
202 $scripts = '';
203 foreach ( $this->getPages( $context ) as $titleText => $options ) {
204 if ( $options['type'] !== 'script' ) {
205 continue;
206 }
207 $script = $this->getContent( $titleText );
208 if ( strval( $script ) !== '' ) {
209 $script = $this->validateScriptFile( $titleText, $script );
210 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
211 }
212 }
213 return $scripts;
214 }
215
216 /**
217 * @param ResourceLoaderContext $context
218 * @return array
219 */
220 public function getStyles( ResourceLoaderContext $context ) {
221 $styles = [];
222 foreach ( $this->getPages( $context ) as $titleText => $options ) {
223 if ( $options['type'] !== 'style' ) {
224 continue;
225 }
226 $media = isset( $options['media'] ) ? $options['media'] : 'all';
227 $style = $this->getContent( $titleText );
228 if ( strval( $style ) === '' ) {
229 continue;
230 }
231 if ( $this->getFlip( $context ) ) {
232 $style = CSSJanus::transform( $style, true, false );
233 }
234 $style = MemoizedCallable::call( 'CSSMin::remap',
235 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
236 if ( !isset( $styles[$media] ) ) {
237 $styles[$media] = [];
238 }
239 $style = ResourceLoader::makeComment( $titleText ) . $style;
240 $styles[$media][] = $style;
241 }
242 return $styles;
243 }
244
245 /**
246 * Disable module content versioning.
247 *
248 * This class does not support generating content outside of a module
249 * request due to foreign database support.
250 *
251 * See getDefinitionSummary() for meta-data versioning.
252 *
253 * @return bool
254 */
255 public function enableModuleContentVersion() {
256 return false;
257 }
258
259 /**
260 * @param ResourceLoaderContext $context
261 * @return array
262 */
263 public function getDefinitionSummary( ResourceLoaderContext $context ) {
264 $summary = parent::getDefinitionSummary( $context );
265 $summary[] = [
266 'pages' => $this->getPages( $context ),
267 // Includes meta data of current revisions
268 'titleInfo' => $this->getTitleInfo( $context ),
269 ];
270 return $summary;
271 }
272
273 /**
274 * @param ResourceLoaderContext $context
275 * @return bool
276 */
277 public function isKnownEmpty( ResourceLoaderContext $context ) {
278 $revisions = $this->getTitleInfo( $context );
279
280 // For user modules, don't needlessly load if there are no non-empty pages
281 if ( $this->getGroup() === 'user' ) {
282 foreach ( $revisions as $revision ) {
283 if ( $revision['page_len'] > 0 ) {
284 // At least one non-empty page, module should be loaded
285 return false;
286 }
287 }
288 return true;
289 }
290
291 // T70488: For other modules (i.e. ones that are called in cached html output) only check
292 // page existance. This ensures that, if some pages in a module are temporarily blanked,
293 // we don't end omit the module's script or link tag on some pages.
294 return count( $revisions ) === 0;
295 }
296
297 private function setTitleInfo( $key, array $titleInfo ) {
298 $this->titleInfo[$key] = $titleInfo;
299 }
300
301 /**
302 * Get the information about the wiki pages for a given context.
303 * @param ResourceLoaderContext $context
304 * @return array Keyed by page name
305 */
306 protected function getTitleInfo( ResourceLoaderContext $context ) {
307 $dbr = $this->getDB();
308 if ( !$dbr ) {
309 // We're dealing with a subclass that doesn't have a DB
310 return [];
311 }
312
313 $pageNames = array_keys( $this->getPages( $context ) );
314 sort( $pageNames );
315 $key = implode( '|', $pageNames );
316 if ( !isset( $this->titleInfo[$key] ) ) {
317 $this->titleInfo[$key] = static::fetchTitleInfo( $dbr, $pageNames, __METHOD__ );
318 }
319 return $this->titleInfo[$key];
320 }
321
322 protected static function fetchTitleInfo( IDatabase $db, array $pages, $fname = __METHOD__ ) {
323 $titleInfo = [];
324 $batch = new LinkBatch;
325 foreach ( $pages as $titleText ) {
326 $title = Title::newFromText( $titleText );
327 if ( $title ) {
328 // Page name may be invalid if user-provided (e.g. gadgets)
329 $batch->addObj( $title );
330 }
331 }
332 if ( !$batch->isEmpty() ) {
333 $res = $db->select( 'page',
334 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
335 [ 'page_namespace', 'page_title', 'page_touched', 'page_len', 'page_latest' ],
336 $batch->constructSet( 'page', $db ),
337 $fname
338 );
339 foreach ( $res as $row ) {
340 // Avoid including ids or timestamps of revision/page tables so
341 // that versions are not wasted
342 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
343 $titleInfo[$title->getPrefixedText()] = [
344 'page_len' => $row->page_len,
345 'page_latest' => $row->page_latest,
346 'page_touched' => $row->page_touched,
347 ];
348 }
349 }
350 return $titleInfo;
351 }
352
353 /**
354 * @since 1.28
355 * @param ResourceLoaderContext $context
356 * @param IDatabase $db
357 * @param string[] $moduleNames
358 */
359 public static function preloadTitleInfo(
360 ResourceLoaderContext $context, IDatabase $db, array $moduleNames
361 ) {
362 $rl = $context->getResourceLoader();
363 // getDB() can be overridden to point to a foreign database.
364 // For now, only preload local. In the future, we could preload by wikiID.
365 $allPages = [];
366 /** @var ResourceLoaderWikiModule[] $wikiModules */
367 $wikiModules = [];
368 foreach ( $moduleNames as $name ) {
369 $module = $rl->getModule( $name );
370 if ( $module instanceof self ) {
371 $mDB = $module->getDB();
372 // Subclasses may disable getDB and implement getTitleInfo differently
373 if ( $mDB && $mDB->getWikiID() === $db->getWikiID() ) {
374 $wikiModules[] = $module;
375 $allPages += $module->getPages( $context );
376 }
377 }
378 }
379
380 if ( !$wikiModules ) {
381 // Nothing to preload
382 return;
383 }
384
385 $pageNames = array_keys( $allPages );
386 sort( $pageNames );
387 $hash = sha1( implode( '|', $pageNames ) );
388
389 // Avoid Zend bug where "static::" does not apply LSB in the closure
390 $func = [ static::class, 'fetchTitleInfo' ];
391 $fname = __METHOD__;
392
393 $cache = ObjectCache::getMainWANInstance();
394 $allInfo = $cache->getWithSetCallback(
395 $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID(), $hash ),
396 $cache::TTL_HOUR,
397 function ( $curVal, &$ttl, array &$setOpts ) use ( $func, $pageNames, $db, $fname ) {
398 $setOpts += Database::getCacheSetOptions( $db );
399
400 return call_user_func( $func, $db, $pageNames, $fname );
401 },
402 [ 'checkKeys' => [ $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $db->getWikiID() ) ] ]
403 );
404
405 foreach ( $wikiModules as $wikiModule ) {
406 $pages = $wikiModule->getPages( $context );
407 // Before we intersect, map the names to canonical form (T145673).
408 $intersect = [];
409 foreach ( $pages as $page => $unused ) {
410 $title = Title::newFromText( $page );
411 if ( $title ) {
412 $intersect[ $title->getPrefixedText() ] = 1;
413 } else {
414 // Page name may be invalid if user-provided (e.g. gadgets)
415 $rl->getLogger()->info(
416 'Invalid wiki page title "{title}" in ' . __METHOD__,
417 [ 'title' => $page ]
418 );
419 }
420 }
421 $info = array_intersect_key( $allInfo, $intersect );
422 $pageNames = array_keys( $pages );
423 sort( $pageNames );
424 $key = implode( '|', $pageNames );
425 $wikiModule->setTitleInfo( $key, $info );
426 }
427 }
428
429 /**
430 * Clear the preloadTitleInfo() cache for all wiki modules on this wiki on
431 * page change if it was a JS or CSS page
432 *
433 * @param Title $title
434 * @param Revision|null $old Prior page revision
435 * @param Revision|null $new New page revision
436 * @param string $wikiId
437 * @since 1.28
438 */
439 public static function invalidateModuleCache(
440 Title $title, Revision $old = null, Revision $new = null, $wikiId
441 ) {
442 static $formats = [ CONTENT_FORMAT_CSS, CONTENT_FORMAT_JAVASCRIPT ];
443
444 if ( $old && in_array( $old->getContentFormat(), $formats ) ) {
445 $purge = true;
446 } elseif ( $new && in_array( $new->getContentFormat(), $formats ) ) {
447 $purge = true;
448 } else {
449 $purge = ( $title->isCssOrJsPage() || $title->isCssJsSubpage() );
450 }
451
452 if ( $purge ) {
453 $cache = ObjectCache::getMainWANInstance();
454 $key = $cache->makeGlobalKey( 'resourceloader', 'titleinfo', $wikiId );
455 $cache->touchCheckKey( $key );
456 }
457 }
458
459 /**
460 * @since 1.28
461 * @return string
462 */
463 public function getType() {
464 // Check both because subclasses don't always pass pages via the constructor,
465 // they may also override getPages() instead, in which case we should keep
466 // defaulting to LOAD_GENERAL and allow them to override getType() separately.
467 return ( $this->styles && !$this->scripts ) ? self::LOAD_STYLES : self::LOAD_GENERAL;
468 }
469 }