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