Merge "Flag internal page retrieve/save cycles with EDIT_INTERNAL"
[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 *
31 * This module supports being used as a placeholder for a module on a remote wiki.
32 * To do so, getDB() must be overloaded to return a foreign database object that
33 * allows local wikis to query page metadata.
34 *
35 * Safe for calls on local wikis are:
36 * - Option getters:
37 * - getGroup()
38 * - getPosition()
39 * - getPages()
40 * - Basic methods that strictly involve the foreign database
41 * - getDB()
42 * - isKnownEmpty()
43 * - getTitleInfo()
44 */
45 class ResourceLoaderWikiModule extends ResourceLoaderModule {
46 /** @var string Position on the page to load this module at */
47 protected $position = 'bottom';
48
49 // Origin defaults to users with sitewide authority
50 protected $origin = self::ORIGIN_USER_SITEWIDE;
51
52 // In-process cache for title info
53 protected $titleInfo = [];
54
55 // List of page names that contain CSS
56 protected $styles = [];
57
58 // List of page names that contain JavaScript
59 protected $scripts = [];
60
61 // Group of module
62 protected $group;
63
64 // Whether to enable variable expansion (e.g. "{skin}")
65 protected $allowVariables = false;
66
67 /**
68 * @param array $options For back-compat, this can be omitted in favour of overwriting getPages.
69 */
70 public function __construct( array $options = null ) {
71 if ( is_null( $options ) ) {
72 return;
73 }
74
75 foreach ( $options as $member => $option ) {
76 switch ( $member ) {
77 case 'position':
78 case 'styles':
79 case 'scripts':
80 case 'group':
81 case 'targets':
82 case 'allowVariables':
83 $this->{$member} = $option;
84 break;
85 }
86 }
87 }
88
89 /**
90 * Subclasses should return an associative array of resources in the module.
91 * Keys should be the title of a page in the MediaWiki or User namespace.
92 *
93 * Values should be a nested array of options. The supported keys are 'type' and
94 * (CSS only) 'media'.
95 *
96 * For scripts, 'type' should be 'script'.
97 *
98 * For stylesheets, 'type' should be 'style'.
99 * There is an optional media key, the value of which can be the
100 * medium ('screen', 'print', etc.) of the stylesheet.
101 *
102 * @param ResourceLoaderContext $context
103 * @return array
104 */
105 protected function getPages( ResourceLoaderContext $context ) {
106 $config = $this->getConfig();
107 $pages = [];
108
109 // Filter out pages from origins not allowed by the current wiki configuration.
110 if ( $config->get( 'UseSiteJs' ) ) {
111 foreach ( $this->scripts as $script ) {
112 $page = $this->expandVariables( $context, $script );
113 $pages[$page] = [ 'type' => 'script' ];
114 }
115 }
116
117 if ( $config->get( 'UseSiteCss' ) ) {
118 foreach ( $this->styles as $style ) {
119 $page = $this->expandVariables( $context, $style );
120 $pages[$page] = [ 'type' => 'style' ];
121 }
122 }
123
124 return $pages;
125 }
126
127 private function expandVariables( ResourceLoaderContext $context, $pageName ) {
128 if ( !$this->allowVariables ) {
129 return $pageName;
130 }
131 return strtr( $pageName, [
132 '{skin}' => $context->getSkin()
133 ] );
134 }
135
136 /**
137 * Get group name
138 *
139 * @return string
140 */
141 public function getGroup() {
142 return $this->group;
143 }
144
145 /**
146 * Get the Database object used in getTitleInfo().
147 *
148 * Defaults to the local slave DB. Subclasses may want to override this to return a foreign
149 * database object, or null if getTitleInfo() shouldn't access the database.
150 *
151 * NOTE: This ONLY works for getTitleInfo() and isKnownEmpty(), NOT FOR ANYTHING ELSE.
152 * In particular, it doesn't work for getContent() or getScript() etc.
153 *
154 * @return IDatabase|null
155 */
156 protected function getDB() {
157 return wfGetDB( DB_SLAVE );
158 }
159
160 /**
161 * @param string $title
162 * @return null|string
163 */
164 protected function getContent( $titleText ) {
165 $title = Title::newFromText( $titleText );
166 if ( !$title ) {
167 return null;
168 }
169
170 $handler = ContentHandler::getForTitle( $title );
171 if ( $handler->isSupportedFormat( CONTENT_FORMAT_CSS ) ) {
172 $format = CONTENT_FORMAT_CSS;
173 } elseif ( $handler->isSupportedFormat( CONTENT_FORMAT_JAVASCRIPT ) ) {
174 $format = CONTENT_FORMAT_JAVASCRIPT;
175 } else {
176 return null;
177 }
178
179 $revision = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
180 if ( !$revision ) {
181 return null;
182 }
183
184 $content = $revision->getContent( Revision::RAW );
185
186 if ( !$content ) {
187 wfDebugLog( 'resourceloader', __METHOD__ . ': failed to load content of JS/CSS page!' );
188 return null;
189 }
190
191 return $content->serialize( $format );
192 }
193
194 /**
195 * @param ResourceLoaderContext $context
196 * @return string
197 */
198 public function getScript( ResourceLoaderContext $context ) {
199 $scripts = '';
200 foreach ( $this->getPages( $context ) as $titleText => $options ) {
201 if ( $options['type'] !== 'script' ) {
202 continue;
203 }
204 $script = $this->getContent( $titleText );
205 if ( strval( $script ) !== '' ) {
206 $script = $this->validateScriptFile( $titleText, $script );
207 $scripts .= ResourceLoader::makeComment( $titleText ) . $script . "\n";
208 }
209 }
210 return $scripts;
211 }
212
213 /**
214 * @param ResourceLoaderContext $context
215 * @return array
216 */
217 public function getStyles( ResourceLoaderContext $context ) {
218 $styles = [];
219 foreach ( $this->getPages( $context ) as $titleText => $options ) {
220 if ( $options['type'] !== 'style' ) {
221 continue;
222 }
223 $media = isset( $options['media'] ) ? $options['media'] : 'all';
224 $style = $this->getContent( $titleText );
225 if ( strval( $style ) === '' ) {
226 continue;
227 }
228 if ( $this->getFlip( $context ) ) {
229 $style = CSSJanus::transform( $style, true, false );
230 }
231 $style = MemoizedCallable::call( 'CSSMin::remap',
232 [ $style, false, $this->getConfig()->get( 'ScriptPath' ), true ] );
233 if ( !isset( $styles[$media] ) ) {
234 $styles[$media] = [];
235 }
236 $style = ResourceLoader::makeComment( $titleText ) . $style;
237 $styles[$media][] = $style;
238 }
239 return $styles;
240 }
241
242 /**
243 * Disable module content versioning.
244 *
245 * This class does not support generating content outside of a module
246 * request due to foreign database support.
247 *
248 * See getDefinitionSummary() for meta-data versioning.
249 *
250 * @return bool
251 */
252 public function enableModuleContentVersion() {
253 return false;
254 }
255
256 /**
257 * @param ResourceLoaderContext $context
258 * @return array
259 */
260 public function getDefinitionSummary( ResourceLoaderContext $context ) {
261 $summary = parent::getDefinitionSummary( $context );
262 $summary[] = [
263 'pages' => $this->getPages( $context ),
264 // Includes SHA1 of content
265 'titleInfo' => $this->getTitleInfo( $context ),
266 ];
267 return $summary;
268 }
269
270 /**
271 * @param ResourceLoaderContext $context
272 * @return bool
273 */
274 public function isKnownEmpty( ResourceLoaderContext $context ) {
275 $revisions = $this->getTitleInfo( $context );
276
277 // For user modules, don't needlessly load if there are no non-empty pages
278 if ( $this->getGroup() === 'user' ) {
279 foreach ( $revisions as $revision ) {
280 if ( $revision['rev_len'] > 0 ) {
281 // At least one non-empty page, module should be loaded
282 return false;
283 }
284 }
285 return true;
286 }
287
288 // Bug 68488: For other modules (i.e. ones that are called in cached html output) only check
289 // page existance. This ensures that, if some pages in a module are temporarily blanked,
290 // we don't end omit the module's script or link tag on some pages.
291 return count( $revisions ) === 0;
292 }
293
294 /**
295 * Get the information about the wiki pages for a given context.
296 * @param ResourceLoaderContext $context
297 * @return array Keyed by page name. Contains arrays with 'rev_len' and 'rev_sha1' keys
298 */
299 protected function getTitleInfo( ResourceLoaderContext $context ) {
300 $dbr = $this->getDB();
301 if ( !$dbr ) {
302 // We're dealing with a subclass that doesn't have a DB
303 return [];
304 }
305
306 $pages = $this->getPages( $context );
307 $key = implode( '|', array_keys( $pages ) );
308 if ( !isset( $this->titleInfo[$key] ) ) {
309 $this->titleInfo[$key] = [];
310 $batch = new LinkBatch;
311 foreach ( $pages as $titleText => $options ) {
312 $batch->addObj( Title::newFromText( $titleText ) );
313 }
314
315 if ( !$batch->isEmpty() ) {
316 $res = $dbr->select( [ 'page', 'revision' ],
317 // Include page_touched to allow purging if cache is poisoned (T117587, T113916)
318 [ 'page_namespace', 'page_title', 'page_touched', 'rev_len', 'rev_sha1' ],
319 $batch->constructSet( 'page', $dbr ),
320 __METHOD__,
321 [],
322 [ 'revision' => [ 'INNER JOIN', [ 'page_latest=rev_id' ] ] ]
323 );
324 foreach ( $res as $row ) {
325 // Avoid including ids or timestamps of revision/page tables so
326 // that versions are not wasted
327 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
328 $this->titleInfo[$key][$title->getPrefixedText()] = [
329 'rev_len' => $row->rev_len,
330 'rev_sha1' => $row->rev_sha1,
331 'page_touched' => $row->page_touched,
332 ];
333 }
334 }
335 }
336 return $this->titleInfo[$key];
337 }
338
339 public function getPosition() {
340 return $this->position;
341 }
342 }