Merge "(bug 43270) Add wgPostEdit to show if user just saved this page"
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 /**
3 * Preparation for the final page rendering.
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 */
22
23 /**
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
27 *
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
30 *
31 * @todo FIXME: Another class handles sending the whole page to the client.
32 *
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
34 * in November 2010.
35 *
36 * @todo document
37 */
38 class OutputPage extends ContextSource {
39 /// Should be private. Used with addMeta() which adds "<meta>"
40 var $mMetatags = array();
41
42 /// "<meta keywords='stuff'>" most of the time the first 10 links to an article
43 var $mKeywords = array();
44
45 var $mLinktags = array();
46 var $mCanonicalUrl = false;
47
48 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
49 var $mExtStyles = array();
50
51 /// Should be private - has getter and setter. Contains the HTML title
52 var $mPagetitle = '';
53
54 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
55 var $mBodytext = '';
56
57 /**
58 * Holds the debug lines that will be output as comments in page source if
59 * $wgDebugComments is enabled. See also $wgShowDebug.
60 * @deprecated since 1.20; use MWDebug class instead.
61 */
62 public $mDebugtext = '';
63
64 /// Should be private. Stores contents of "<title>" tag
65 var $mHTMLtitle = '';
66
67 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
68 var $mIsarticle = false;
69
70 /**
71 * Should be private. Has get/set methods properly documented.
72 * Stores "article flag" toggle.
73 */
74 var $mIsArticleRelated = true;
75
76 /**
77 * Should be private. We have to set isPrintable(). Some pages should
78 * never be printed (ex: redirections).
79 */
80 var $mPrintable = false;
81
82 /**
83 * Should be private. We have set/get/append methods.
84 *
85 * Contains the page subtitle. Special pages usually have some links here.
86 * Don't confuse with site subtitle added by skins.
87 */
88 private $mSubtitle = array();
89
90 var $mRedirect = '';
91 var $mStatusCode;
92
93 /**
94 * mLastModified and mEtag are used for sending cache control.
95 * The whole caching system should probably be moved into its own class.
96 */
97 var $mLastModified = '';
98
99 /**
100 * Should be private. No getter but used in sendCacheControl();
101 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
102 * as a unique identifier for the content. It is later used by the client
103 * to compare its cached version with the server version. Client sends
104 * headers If-Match and If-None-Match containing its locally cached ETAG value.
105 *
106 * To get more information, you will have to look at HTTP/1.1 protocol which
107 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
108 */
109 var $mETag = false;
110
111 var $mCategoryLinks = array();
112 var $mCategories = array();
113
114 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
115 var $mLanguageLinks = array();
116
117 /**
118 * Should be private. Used for JavaScript (pre resource loader)
119 * We should split js / css.
120 * mScripts content is inserted as is in "<head>" by Skin. This might
121 * contains either a link to a stylesheet or inline css.
122 */
123 var $mScripts = '';
124
125 /**
126 * Inline CSS styles. Use addInlineStyle() sparsingly
127 */
128 var $mInlineStyles = '';
129
130 //
131 var $mLinkColours;
132
133 /**
134 * Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
136 */
137 var $mPageLinkTitle = '';
138
139 /// Array of elements in "<head>". Parser might add its own headers!
140 var $mHeadItems = array();
141
142 // @todo FIXME: Next variables probably comes from the resource loader
143 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
144 var $mResourceLoader;
145 var $mJsConfigVars = array();
146
147 /** @todo FIXME: Is this still used ?*/
148 var $mInlineMsg = array();
149
150 var $mTemplateIds = array();
151 var $mImageTimeKeys = array();
152
153 var $mRedirectCode = '';
154
155 var $mFeedLinksAppendQuery = null;
156
157 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
158 # @see ResourceLoaderModule::$origin
159 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
160 protected $mAllowedModules = array(
161 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
162 );
163
164 /**
165 * @EasterEgg I just love the name for this self documenting variable.
166 * @todo document
167 */
168 var $mDoNothing = false;
169
170 // Parser related.
171 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
172
173 /**
174 * lazy initialised, use parserOptions()
175 * @var ParserOptions
176 */
177 protected $mParserOptions = null;
178
179 /**
180 * Handles the atom / rss links.
181 * We probably only support atom in 2011.
182 * Looks like a private variable.
183 * @see $wgAdvertisedFeedTypes
184 */
185 var $mFeedLinks = array();
186
187 // Gwicke work on squid caching? Roughly from 2003.
188 var $mEnableClientCache = true;
189
190 /**
191 * Flag if output should only contain the body of the article.
192 * Should be private.
193 */
194 var $mArticleBodyOnly = false;
195
196 var $mNewSectionLink = false;
197 var $mHideNewSectionLink = false;
198
199 /**
200 * Comes from the parser. This was probably made to load CSS/JS only
201 * if we had "<gallery>". Used directly in CategoryPage.php
202 * Looks like resource loader can replace this.
203 */
204 var $mNoGallery = false;
205
206 // should be private.
207 var $mPageTitleActionText = '';
208 var $mParseWarnings = array();
209
210 // Cache stuff. Looks like mEnableClientCache
211 var $mSquidMaxage = 0;
212
213 // @todo document
214 var $mPreventClickjacking = true;
215
216 /// should be private. To include the variable {{REVISIONID}}
217 var $mRevisionId = null;
218 private $mRevisionTimestamp = null;
219
220 var $mFileVersion = null;
221
222 /**
223 * An array of stylesheet filenames (relative from skins path), with options
224 * for CSS media, IE conditions, and RTL/LTR direction.
225 * For internal use; add settings in the skin via $this->addStyle()
226 *
227 * Style again! This seems like a code duplication since we already have
228 * mStyles. This is what makes OpenSource amazing.
229 */
230 var $styles = array();
231
232 /**
233 * Whether jQuery is already handled.
234 */
235 protected $mJQueryDone = false;
236
237 private $mIndexPolicy = 'index';
238 private $mFollowPolicy = 'follow';
239 private $mVaryHeader = array(
240 'Accept-Encoding' => array( 'list-contains=gzip' ),
241 );
242
243 /**
244 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
245 * of the redirect.
246 *
247 * @var Title
248 */
249 private $mRedirectedFrom = null;
250
251 /**
252 * Additional key => value data
253 */
254 private $mProperties = array();
255
256 /**
257 * Constructor for OutputPage. This should not be called directly.
258 * Instead a new RequestContext should be created and it will implicitly create
259 * a OutputPage tied to that context.
260 */
261 function __construct( IContextSource $context = null ) {
262 if ( $context === null ) {
263 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
264 wfDeprecated( __METHOD__, '1.18' );
265 } else {
266 $this->setContext( $context );
267 }
268 }
269
270 /**
271 * Redirect to $url rather than displaying the normal page
272 *
273 * @param $url String: URL
274 * @param $responsecode String: HTTP status code
275 */
276 public function redirect( $url, $responsecode = '302' ) {
277 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
278 $this->mRedirect = str_replace( "\n", '', $url );
279 $this->mRedirectCode = $responsecode;
280 }
281
282 /**
283 * Get the URL to redirect to, or an empty string if not redirect URL set
284 *
285 * @return String
286 */
287 public function getRedirect() {
288 return $this->mRedirect;
289 }
290
291 /**
292 * Set the HTTP status code to send with the output.
293 *
294 * @param $statusCode Integer
295 */
296 public function setStatusCode( $statusCode ) {
297 $this->mStatusCode = $statusCode;
298 }
299
300 /**
301 * Add a new "<meta>" tag
302 * To add an http-equiv meta tag, precede the name with "http:"
303 *
304 * @param $name String tag name
305 * @param $val String tag value
306 */
307 function addMeta( $name, $val ) {
308 array_push( $this->mMetatags, array( $name, $val ) );
309 }
310
311 /**
312 * Add a keyword or a list of keywords in the page header
313 *
314 * @param $text String or array of strings
315 */
316 function addKeyword( $text ) {
317 if( is_array( $text ) ) {
318 $this->mKeywords = array_merge( $this->mKeywords, $text );
319 } else {
320 array_push( $this->mKeywords, $text );
321 }
322 }
323
324 /**
325 * Add a new \<link\> tag to the page header.
326 *
327 * Note: use setCanonicalUrl() for rel=canonical.
328 *
329 * @param $linkarr Array: associative array of attributes.
330 */
331 function addLink( $linkarr ) {
332 array_push( $this->mLinktags, $linkarr );
333 }
334
335 /**
336 * Add a new \<link\> with "rel" attribute set to "meta"
337 *
338 * @param $linkarr Array: associative array mapping attribute names to their
339 * values, both keys and values will be escaped, and the
340 * "rel" attribute will be automatically added
341 */
342 function addMetadataLink( $linkarr ) {
343 $linkarr['rel'] = $this->getMetadataAttribute();
344 $this->addLink( $linkarr );
345 }
346
347 /**
348 * Set the URL to be used for the <link rel=canonical>. This should be used
349 * in preference to addLink(), to avoid duplicate link tags.
350 */
351 function setCanonicalUrl( $url ) {
352 $this->mCanonicalUrl = $url;
353 }
354
355 /**
356 * Get the value of the "rel" attribute for metadata links
357 *
358 * @return String
359 */
360 public function getMetadataAttribute() {
361 # note: buggy CC software only reads first "meta" link
362 static $haveMeta = false;
363 if ( $haveMeta ) {
364 return 'alternate meta';
365 } else {
366 $haveMeta = true;
367 return 'meta';
368 }
369 }
370
371 /**
372 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
373 *
374 * @param $script String: raw HTML
375 */
376 function addScript( $script ) {
377 $this->mScripts .= $script . "\n";
378 }
379
380 /**
381 * Register and add a stylesheet from an extension directory.
382 *
383 * @param $url String path to sheet. Provide either a full url (beginning
384 * with 'http', etc) or a relative path from the document root
385 * (beginning with '/'). Otherwise it behaves identically to
386 * addStyle() and draws from the /skins folder.
387 */
388 public function addExtensionStyle( $url ) {
389 array_push( $this->mExtStyles, $url );
390 }
391
392 /**
393 * Get all styles added by extensions
394 *
395 * @return Array
396 */
397 function getExtStyle() {
398 return $this->mExtStyles;
399 }
400
401 /**
402 * Add a JavaScript file out of skins/common, or a given relative path.
403 *
404 * @param $file String: filename in skins/common or complete on-server path
405 * (/foo/bar.js)
406 * @param $version String: style version of the file. Defaults to $wgStyleVersion
407 */
408 public function addScriptFile( $file, $version = null ) {
409 global $wgStylePath, $wgStyleVersion;
410 // See if $file parameter is an absolute URL or begins with a slash
411 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
412 $path = $file;
413 } else {
414 $path = "{$wgStylePath}/common/{$file}";
415 }
416 if ( is_null( $version ) )
417 $version = $wgStyleVersion;
418 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
419 }
420
421 /**
422 * Add a self-contained script tag with the given contents
423 *
424 * @param $script String: JavaScript text, no "<script>" tags
425 */
426 public function addInlineScript( $script ) {
427 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
428 }
429
430 /**
431 * Get all registered JS and CSS tags for the header.
432 *
433 * @return String
434 */
435 function getScript() {
436 return $this->mScripts . $this->getHeadItems();
437 }
438
439 /**
440 * Filter an array of modules to remove insufficiently trustworthy members, and modules
441 * which are no longer registered (eg a page is cached before an extension is disabled)
442 * @param $modules Array
443 * @param $position String if not null, only return modules with this position
444 * @param $type string
445 * @return Array
446 */
447 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule::TYPE_COMBINED ) {
448 $resourceLoader = $this->getResourceLoader();
449 $filteredModules = array();
450 foreach( $modules as $val ) {
451 $module = $resourceLoader->getModule( $val );
452 if( $module instanceof ResourceLoaderModule
453 && $module->getOrigin() <= $this->getAllowedModules( $type )
454 && ( is_null( $position ) || $module->getPosition() == $position ) )
455 {
456 $filteredModules[] = $val;
457 }
458 }
459 return $filteredModules;
460 }
461
462 /**
463 * Get the list of modules to include on this page
464 *
465 * @param $filter Bool whether to filter out insufficiently trustworthy modules
466 * @param $position String if not null, only return modules with this position
467 * @param $param string
468 * @return Array of module names
469 */
470 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
471 $modules = array_values( array_unique( $this->$param ) );
472 return $filter
473 ? $this->filterModules( $modules, $position )
474 : $modules;
475 }
476
477 /**
478 * Add one or more modules recognized by the resource loader. Modules added
479 * through this function will be loaded by the resource loader when the
480 * page loads.
481 *
482 * @param $modules Mixed: module name (string) or array of module names
483 */
484 public function addModules( $modules ) {
485 $this->mModules = array_merge( $this->mModules, (array)$modules );
486 }
487
488 /**
489 * Get the list of module JS to include on this page
490 *
491 * @param $filter
492 * @param $position
493 *
494 * @return array of module names
495 */
496 public function getModuleScripts( $filter = false, $position = null ) {
497 return $this->getModules( $filter, $position, 'mModuleScripts' );
498 }
499
500 /**
501 * Add only JS of one or more modules recognized by the resource loader. Module
502 * scripts added through this function will be loaded by the resource loader when
503 * the page loads.
504 *
505 * @param $modules Mixed: module name (string) or array of module names
506 */
507 public function addModuleScripts( $modules ) {
508 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
509 }
510
511 /**
512 * Get the list of module CSS to include on this page
513 *
514 * @param $filter
515 * @param $position
516 *
517 * @return Array of module names
518 */
519 public function getModuleStyles( $filter = false, $position = null ) {
520 return $this->getModules( $filter, $position, 'mModuleStyles' );
521 }
522
523 /**
524 * Add only CSS of one or more modules recognized by the resource loader. Module
525 * styles added through this function will be loaded by the resource loader when
526 * the page loads.
527 *
528 * @param $modules Mixed: module name (string) or array of module names
529 */
530 public function addModuleStyles( $modules ) {
531 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
532 }
533
534 /**
535 * Get the list of module messages to include on this page
536 *
537 * @param $filter
538 * @param $position
539 *
540 * @return Array of module names
541 */
542 public function getModuleMessages( $filter = false, $position = null ) {
543 return $this->getModules( $filter, $position, 'mModuleMessages' );
544 }
545
546 /**
547 * Add only messages of one or more modules recognized by the resource loader.
548 * Module messages added through this function will be loaded by the resource
549 * loader when the page loads.
550 *
551 * @param $modules Mixed: module name (string) or array of module names
552 */
553 public function addModuleMessages( $modules ) {
554 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
555 }
556
557 /**
558 * Get an array of head items
559 *
560 * @return Array
561 */
562 function getHeadItemsArray() {
563 return $this->mHeadItems;
564 }
565
566 /**
567 * Get all header items in a string
568 *
569 * @return String
570 */
571 function getHeadItems() {
572 $s = '';
573 foreach ( $this->mHeadItems as $item ) {
574 $s .= $item;
575 }
576 return $s;
577 }
578
579 /**
580 * Add or replace an header item to the output
581 *
582 * @param $name String: item name
583 * @param $value String: raw HTML
584 */
585 public function addHeadItem( $name, $value ) {
586 $this->mHeadItems[$name] = $value;
587 }
588
589 /**
590 * Check if the header item $name is already set
591 *
592 * @param $name String: item name
593 * @return Boolean
594 */
595 public function hasHeadItem( $name ) {
596 return isset( $this->mHeadItems[$name] );
597 }
598
599 /**
600 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
601 *
602 * @param $tag String: value of "ETag" header
603 */
604 function setETag( $tag ) {
605 $this->mETag = $tag;
606 }
607
608 /**
609 * Set whether the output should only contain the body of the article,
610 * without any skin, sidebar, etc.
611 * Used e.g. when calling with "action=render".
612 *
613 * @param $only Boolean: whether to output only the body of the article
614 */
615 public function setArticleBodyOnly( $only ) {
616 $this->mArticleBodyOnly = $only;
617 }
618
619 /**
620 * Return whether the output will contain only the body of the article
621 *
622 * @return Boolean
623 */
624 public function getArticleBodyOnly() {
625 return $this->mArticleBodyOnly;
626 }
627
628 /**
629 * Set an additional output property
630 * @since 1.21
631 *
632 * @param string $name
633 * @param mixed $value
634 */
635 public function setProperty( $name, $value ) {
636 $this->mProperties[$name] = $value;
637 }
638
639 /**
640 * Get an additional output property
641 * @since 1.21
642 *
643 * @param $name
644 * @return mixed: Property value or null if not found
645 */
646 public function getProperty( $name ) {
647 if ( isset( $this->mProperties[$name] ) ) {
648 return $this->mProperties[$name];
649 } else {
650 return null;
651 }
652 }
653
654 /**
655 * checkLastModified tells the client to use the client-cached page if
656 * possible. If successful, the OutputPage is disabled so that
657 * any future call to OutputPage->output() have no effect.
658 *
659 * Side effect: sets mLastModified for Last-Modified header
660 *
661 * @param $timestamp string
662 *
663 * @return Boolean: true iff cache-ok headers was sent.
664 */
665 public function checkLastModified( $timestamp ) {
666 global $wgCachePages, $wgCacheEpoch;
667
668 if ( !$timestamp || $timestamp == '19700101000000' ) {
669 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
670 return false;
671 }
672 if( !$wgCachePages ) {
673 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
674 return false;
675 }
676 if( $this->getUser()->getOption( 'nocache' ) ) {
677 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
678 return false;
679 }
680
681 $timestamp = wfTimestamp( TS_MW, $timestamp );
682 $modifiedTimes = array(
683 'page' => $timestamp,
684 'user' => $this->getUser()->getTouched(),
685 'epoch' => $wgCacheEpoch
686 );
687 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
688
689 $maxModified = max( $modifiedTimes );
690 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
691
692 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
693 if ( $clientHeader === false ) {
694 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
695 return false;
696 }
697
698 # IE sends sizes after the date like this:
699 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
700 # this breaks strtotime().
701 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
702
703 wfSuppressWarnings(); // E_STRICT system time bitching
704 $clientHeaderTime = strtotime( $clientHeader );
705 wfRestoreWarnings();
706 if ( !$clientHeaderTime ) {
707 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
708 return false;
709 }
710 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
711
712 # Make debug info
713 $info = '';
714 foreach ( $modifiedTimes as $name => $value ) {
715 if ( $info !== '' ) {
716 $info .= ', ';
717 }
718 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
719 }
720
721 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
722 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
723 wfDebug( __METHOD__ . ": effective Last-Modified: " .
724 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
725 if( $clientHeaderTime < $maxModified ) {
726 wfDebug( __METHOD__ . ": STALE, $info\n", false );
727 return false;
728 }
729
730 # Not modified
731 # Give a 304 response code and disable body output
732 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
733 ini_set( 'zlib.output_compression', 0 );
734 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
735 $this->sendCacheControl();
736 $this->disable();
737
738 // Don't output a compressed blob when using ob_gzhandler;
739 // it's technically against HTTP spec and seems to confuse
740 // Firefox when the response gets split over two packets.
741 wfClearOutputBuffers();
742
743 return true;
744 }
745
746 /**
747 * Override the last modified timestamp
748 *
749 * @param $timestamp String: new timestamp, in a format readable by
750 * wfTimestamp()
751 */
752 public function setLastModified( $timestamp ) {
753 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
754 }
755
756 /**
757 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
758 *
759 * @param $policy String: the literal string to output as the contents of
760 * the meta tag. Will be parsed according to the spec and output in
761 * standardized form.
762 * @return null
763 */
764 public function setRobotPolicy( $policy ) {
765 $policy = Article::formatRobotPolicy( $policy );
766
767 if( isset( $policy['index'] ) ) {
768 $this->setIndexPolicy( $policy['index'] );
769 }
770 if( isset( $policy['follow'] ) ) {
771 $this->setFollowPolicy( $policy['follow'] );
772 }
773 }
774
775 /**
776 * Set the index policy for the page, but leave the follow policy un-
777 * touched.
778 *
779 * @param $policy string Either 'index' or 'noindex'.
780 * @return null
781 */
782 public function setIndexPolicy( $policy ) {
783 $policy = trim( $policy );
784 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
785 $this->mIndexPolicy = $policy;
786 }
787 }
788
789 /**
790 * Set the follow policy for the page, but leave the index policy un-
791 * touched.
792 *
793 * @param $policy String: either 'follow' or 'nofollow'.
794 * @return null
795 */
796 public function setFollowPolicy( $policy ) {
797 $policy = trim( $policy );
798 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
799 $this->mFollowPolicy = $policy;
800 }
801 }
802
803 /**
804 * Set the new value of the "action text", this will be added to the
805 * "HTML title", separated from it with " - ".
806 *
807 * @param $text String: new value of the "action text"
808 */
809 public function setPageTitleActionText( $text ) {
810 $this->mPageTitleActionText = $text;
811 }
812
813 /**
814 * Get the value of the "action text"
815 *
816 * @return String
817 */
818 public function getPageTitleActionText() {
819 if ( isset( $this->mPageTitleActionText ) ) {
820 return $this->mPageTitleActionText;
821 }
822 return '';
823 }
824
825 /**
826 * "HTML title" means the contents of "<title>".
827 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
828 *
829 * @param $name string
830 */
831 public function setHTMLTitle( $name ) {
832 if ( $name instanceof Message ) {
833 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
834 } else {
835 $this->mHTMLtitle = $name;
836 }
837 }
838
839 /**
840 * Return the "HTML title", i.e. the content of the "<title>" tag.
841 *
842 * @return String
843 */
844 public function getHTMLTitle() {
845 return $this->mHTMLtitle;
846 }
847
848 /**
849 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
850 *
851 * @param $t Title
852 */
853 public function setRedirectedFrom( $t ) {
854 $this->mRedirectedFrom = $t;
855 }
856
857 /**
858 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
859 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
860 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
861 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
862 *
863 * @param $name string|Message
864 */
865 public function setPageTitle( $name ) {
866 if ( $name instanceof Message ) {
867 $name = $name->setContext( $this->getContext() )->text();
868 }
869
870 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
871 # but leave "<i>foobar</i>" alone
872 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
873 $this->mPagetitle = $nameWithTags;
874
875 # change "<i>foo&amp;bar</i>" to "foo&bar"
876 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) ) );
877 }
878
879 /**
880 * Return the "page title", i.e. the content of the \<h1\> tag.
881 *
882 * @return String
883 */
884 public function getPageTitle() {
885 return $this->mPagetitle;
886 }
887
888 /**
889 * Set the Title object to use
890 *
891 * @param $t Title object
892 */
893 public function setTitle( Title $t ) {
894 $this->getContext()->setTitle( $t );
895 }
896
897 /**
898 * Replace the subtile with $str
899 *
900 * @param $str String|Message: new value of the subtitle. String should be safe HTML.
901 */
902 public function setSubtitle( $str ) {
903 $this->clearSubtitle();
904 $this->addSubtitle( $str );
905 }
906
907 /**
908 * Add $str to the subtitle
909 *
910 * @deprecated in 1.19; use addSubtitle() instead
911 * @param $str String|Message to add to the subtitle
912 */
913 public function appendSubtitle( $str ) {
914 $this->addSubtitle( $str );
915 }
916
917 /**
918 * Add $str to the subtitle
919 *
920 * @param $str String|Message to add to the subtitle. String should be safe HTML.
921 */
922 public function addSubtitle( $str ) {
923 if ( $str instanceof Message ) {
924 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
925 } else {
926 $this->mSubtitle[] = $str;
927 }
928 }
929
930 /**
931 * Add a subtitle containing a backlink to a page
932 *
933 * @param $title Title to link to
934 */
935 public function addBacklinkSubtitle( Title $title ) {
936 $query = array();
937 if ( $title->isRedirect() ) {
938 $query['redirect'] = 'no';
939 }
940 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker::link( $title, null, array(), $query ) ) );
941 }
942
943 /**
944 * Clear the subtitles
945 */
946 public function clearSubtitle() {
947 $this->mSubtitle = array();
948 }
949
950 /**
951 * Get the subtitle
952 *
953 * @return String
954 */
955 public function getSubtitle() {
956 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
957 }
958
959 /**
960 * Set the page as printable, i.e. it'll be displayed with with all
961 * print styles included
962 */
963 public function setPrintable() {
964 $this->mPrintable = true;
965 }
966
967 /**
968 * Return whether the page is "printable"
969 *
970 * @return Boolean
971 */
972 public function isPrintable() {
973 return $this->mPrintable;
974 }
975
976 /**
977 * Disable output completely, i.e. calling output() will have no effect
978 */
979 public function disable() {
980 $this->mDoNothing = true;
981 }
982
983 /**
984 * Return whether the output will be completely disabled
985 *
986 * @return Boolean
987 */
988 public function isDisabled() {
989 return $this->mDoNothing;
990 }
991
992 /**
993 * Show an "add new section" link?
994 *
995 * @return Boolean
996 */
997 public function showNewSectionLink() {
998 return $this->mNewSectionLink;
999 }
1000
1001 /**
1002 * Forcibly hide the new section link?
1003 *
1004 * @return Boolean
1005 */
1006 public function forceHideNewSectionLink() {
1007 return $this->mHideNewSectionLink;
1008 }
1009
1010 /**
1011 * Add or remove feed links in the page header
1012 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1013 * for the new version
1014 * @see addFeedLink()
1015 *
1016 * @param $show Boolean: true: add default feeds, false: remove all feeds
1017 */
1018 public function setSyndicated( $show = true ) {
1019 if ( $show ) {
1020 $this->setFeedAppendQuery( false );
1021 } else {
1022 $this->mFeedLinks = array();
1023 }
1024 }
1025
1026 /**
1027 * Add default feeds to the page header
1028 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1029 * for the new version
1030 * @see addFeedLink()
1031 *
1032 * @param $val String: query to append to feed links or false to output
1033 * default links
1034 */
1035 public function setFeedAppendQuery( $val ) {
1036 global $wgAdvertisedFeedTypes;
1037
1038 $this->mFeedLinks = array();
1039
1040 foreach ( $wgAdvertisedFeedTypes as $type ) {
1041 $query = "feed=$type";
1042 if ( is_string( $val ) ) {
1043 $query .= '&' . $val;
1044 }
1045 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1046 }
1047 }
1048
1049 /**
1050 * Add a feed link to the page header
1051 *
1052 * @param $format String: feed type, should be a key of $wgFeedClasses
1053 * @param $href String: URL
1054 */
1055 public function addFeedLink( $format, $href ) {
1056 global $wgAdvertisedFeedTypes;
1057
1058 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1059 $this->mFeedLinks[$format] = $href;
1060 }
1061 }
1062
1063 /**
1064 * Should we output feed links for this page?
1065 * @return Boolean
1066 */
1067 public function isSyndicated() {
1068 return count( $this->mFeedLinks ) > 0;
1069 }
1070
1071 /**
1072 * Return URLs for each supported syndication format for this page.
1073 * @return array associating format keys with URLs
1074 */
1075 public function getSyndicationLinks() {
1076 return $this->mFeedLinks;
1077 }
1078
1079 /**
1080 * Will currently always return null
1081 *
1082 * @return null
1083 */
1084 public function getFeedAppendQuery() {
1085 return $this->mFeedLinksAppendQuery;
1086 }
1087
1088 /**
1089 * Set whether the displayed content is related to the source of the
1090 * corresponding article on the wiki
1091 * Setting true will cause the change "article related" toggle to true
1092 *
1093 * @param $v Boolean
1094 */
1095 public function setArticleFlag( $v ) {
1096 $this->mIsarticle = $v;
1097 if ( $v ) {
1098 $this->mIsArticleRelated = $v;
1099 }
1100 }
1101
1102 /**
1103 * Return whether the content displayed page is related to the source of
1104 * the corresponding article on the wiki
1105 *
1106 * @return Boolean
1107 */
1108 public function isArticle() {
1109 return $this->mIsarticle;
1110 }
1111
1112 /**
1113 * Set whether this page is related an article on the wiki
1114 * Setting false will cause the change of "article flag" toggle to false
1115 *
1116 * @param $v Boolean
1117 */
1118 public function setArticleRelated( $v ) {
1119 $this->mIsArticleRelated = $v;
1120 if ( !$v ) {
1121 $this->mIsarticle = false;
1122 }
1123 }
1124
1125 /**
1126 * Return whether this page is related an article on the wiki
1127 *
1128 * @return Boolean
1129 */
1130 public function isArticleRelated() {
1131 return $this->mIsArticleRelated;
1132 }
1133
1134 /**
1135 * Add new language links
1136 *
1137 * @param $newLinkArray array Associative array mapping language code to the page
1138 * name
1139 */
1140 public function addLanguageLinks( $newLinkArray ) {
1141 $this->mLanguageLinks += $newLinkArray;
1142 }
1143
1144 /**
1145 * Reset the language links and add new language links
1146 *
1147 * @param $newLinkArray array Associative array mapping language code to the page
1148 * name
1149 */
1150 public function setLanguageLinks( $newLinkArray ) {
1151 $this->mLanguageLinks = $newLinkArray;
1152 }
1153
1154 /**
1155 * Get the list of language links
1156 *
1157 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1158 */
1159 public function getLanguageLinks() {
1160 return $this->mLanguageLinks;
1161 }
1162
1163 /**
1164 * Add an array of categories, with names in the keys
1165 *
1166 * @param $categories Array mapping category name => sort key
1167 */
1168 public function addCategoryLinks( $categories ) {
1169 global $wgContLang;
1170
1171 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1172 return;
1173 }
1174
1175 # Add the links to a LinkBatch
1176 $arr = array( NS_CATEGORY => $categories );
1177 $lb = new LinkBatch;
1178 $lb->setArray( $arr );
1179
1180 # Fetch existence plus the hiddencat property
1181 $dbr = wfGetDB( DB_SLAVE );
1182 $res = $dbr->select( array( 'page', 'page_props' ),
1183 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1184 $lb->constructSet( 'page', $dbr ),
1185 __METHOD__,
1186 array(),
1187 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1188 );
1189
1190 # Add the results to the link cache
1191 $lb->addResultToCache( LinkCache::singleton(), $res );
1192
1193 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1194 $categories = array_combine(
1195 array_keys( $categories ),
1196 array_fill( 0, count( $categories ), 'normal' )
1197 );
1198
1199 # Mark hidden categories
1200 foreach ( $res as $row ) {
1201 if ( isset( $row->pp_value ) ) {
1202 $categories[$row->page_title] = 'hidden';
1203 }
1204 }
1205
1206 # Add the remaining categories to the skin
1207 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1208 foreach ( $categories as $category => $type ) {
1209 $origcategory = $category;
1210 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1211 $wgContLang->findVariantLink( $category, $title, true );
1212 if ( $category != $origcategory ) {
1213 if ( array_key_exists( $category, $categories ) ) {
1214 continue;
1215 }
1216 }
1217 $text = $wgContLang->convertHtml( $title->getText() );
1218 $this->mCategories[] = $title->getText();
1219 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1220 }
1221 }
1222 }
1223
1224 /**
1225 * Reset the category links (but not the category list) and add $categories
1226 *
1227 * @param $categories Array mapping category name => sort key
1228 */
1229 public function setCategoryLinks( $categories ) {
1230 $this->mCategoryLinks = array();
1231 $this->addCategoryLinks( $categories );
1232 }
1233
1234 /**
1235 * Get the list of category links, in a 2-D array with the following format:
1236 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1237 * hidden categories) and $link a HTML fragment with a link to the category
1238 * page
1239 *
1240 * @return Array
1241 */
1242 public function getCategoryLinks() {
1243 return $this->mCategoryLinks;
1244 }
1245
1246 /**
1247 * Get the list of category names this page belongs to
1248 *
1249 * @return Array of strings
1250 */
1251 public function getCategories() {
1252 return $this->mCategories;
1253 }
1254
1255 /**
1256 * Do not allow scripts which can be modified by wiki users to load on this page;
1257 * only allow scripts bundled with, or generated by, the software.
1258 */
1259 public function disallowUserJs() {
1260 $this->reduceAllowedModules(
1261 ResourceLoaderModule::TYPE_SCRIPTS,
1262 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1263 );
1264 }
1265
1266 /**
1267 * Return whether user JavaScript is allowed for this page
1268 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1269 * trustworthiness is identified and enforced automagically.
1270 * Will be removed in 1.20.
1271 * @return Boolean
1272 */
1273 public function isUserJsAllowed() {
1274 wfDeprecated( __METHOD__, '1.18' );
1275 return $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS ) >= ResourceLoaderModule::ORIGIN_USER_INDIVIDUAL;
1276 }
1277
1278 /**
1279 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1280 * @see ResourceLoaderModule::$origin
1281 * @param $type String ResourceLoaderModule TYPE_ constant
1282 * @return Int ResourceLoaderModule ORIGIN_ class constant
1283 */
1284 public function getAllowedModules( $type ) {
1285 if( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1286 return min( array_values( $this->mAllowedModules ) );
1287 } else {
1288 return isset( $this->mAllowedModules[$type] )
1289 ? $this->mAllowedModules[$type]
1290 : ResourceLoaderModule::ORIGIN_ALL;
1291 }
1292 }
1293
1294 /**
1295 * Set the highest level of CSS/JS untrustworthiness allowed
1296 * @param $type String ResourceLoaderModule TYPE_ constant
1297 * @param $level Int ResourceLoaderModule class constant
1298 */
1299 public function setAllowedModules( $type, $level ) {
1300 $this->mAllowedModules[$type] = $level;
1301 }
1302
1303 /**
1304 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1305 * @param $type String
1306 * @param $level Int ResourceLoaderModule class constant
1307 */
1308 public function reduceAllowedModules( $type, $level ) {
1309 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1310 }
1311
1312 /**
1313 * Prepend $text to the body HTML
1314 *
1315 * @param $text String: HTML
1316 */
1317 public function prependHTML( $text ) {
1318 $this->mBodytext = $text . $this->mBodytext;
1319 }
1320
1321 /**
1322 * Append $text to the body HTML
1323 *
1324 * @param $text String: HTML
1325 */
1326 public function addHTML( $text ) {
1327 $this->mBodytext .= $text;
1328 }
1329
1330 /**
1331 * Shortcut for adding an Html::element via addHTML.
1332 *
1333 * @since 1.19
1334 *
1335 * @param $element string
1336 * @param $attribs array
1337 * @param $contents string
1338 */
1339 public function addElement( $element, $attribs = array(), $contents = '' ) {
1340 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1341 }
1342
1343 /**
1344 * Clear the body HTML
1345 */
1346 public function clearHTML() {
1347 $this->mBodytext = '';
1348 }
1349
1350 /**
1351 * Get the body HTML
1352 *
1353 * @return String: HTML
1354 */
1355 public function getHTML() {
1356 return $this->mBodytext;
1357 }
1358
1359 /**
1360 * Get/set the ParserOptions object to use for wikitext parsing
1361 *
1362 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1363 * current ParserOption object
1364 * @return ParserOptions object
1365 */
1366 public function parserOptions( $options = null ) {
1367 if ( !$this->mParserOptions ) {
1368 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1369 $this->mParserOptions->setEditSection( false );
1370 }
1371 return wfSetVar( $this->mParserOptions, $options );
1372 }
1373
1374 /**
1375 * Set the revision ID which will be seen by the wiki text parser
1376 * for things such as embedded {{REVISIONID}} variable use.
1377 *
1378 * @param $revid Mixed: an positive integer, or null
1379 * @return Mixed: previous value
1380 */
1381 public function setRevisionId( $revid ) {
1382 $val = is_null( $revid ) ? null : intval( $revid );
1383 return wfSetVar( $this->mRevisionId, $val );
1384 }
1385
1386 /**
1387 * Get the displayed revision ID
1388 *
1389 * @return Integer
1390 */
1391 public function getRevisionId() {
1392 return $this->mRevisionId;
1393 }
1394
1395 /**
1396 * Set the timestamp of the revision which will be displayed. This is used
1397 * to avoid a extra DB call in Skin::lastModified().
1398 *
1399 * @param $timestamp Mixed: string, or null
1400 * @return Mixed: previous value
1401 */
1402 public function setRevisionTimestamp( $timestamp) {
1403 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1404 }
1405
1406 /**
1407 * Get the timestamp of displayed revision.
1408 * This will be null if not filled by setRevisionTimestamp().
1409 *
1410 * @return String or null
1411 */
1412 public function getRevisionTimestamp() {
1413 return $this->mRevisionTimestamp;
1414 }
1415
1416 /**
1417 * Set the displayed file version
1418 *
1419 * @param $file File|bool
1420 * @return Mixed: previous value
1421 */
1422 public function setFileVersion( $file ) {
1423 $val = null;
1424 if ( $file instanceof File && $file->exists() ) {
1425 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1426 }
1427 return wfSetVar( $this->mFileVersion, $val, true );
1428 }
1429
1430 /**
1431 * Get the displayed file version
1432 *
1433 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1434 */
1435 public function getFileVersion() {
1436 return $this->mFileVersion;
1437 }
1438
1439 /**
1440 * Get the templates used on this page
1441 *
1442 * @return Array (namespace => dbKey => revId)
1443 * @since 1.18
1444 */
1445 public function getTemplateIds() {
1446 return $this->mTemplateIds;
1447 }
1448
1449 /**
1450 * Get the files used on this page
1451 *
1452 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1453 * @since 1.18
1454 */
1455 public function getFileSearchOptions() {
1456 return $this->mImageTimeKeys;
1457 }
1458
1459 /**
1460 * Convert wikitext to HTML and add it to the buffer
1461 * Default assumes that the current page title will be used.
1462 *
1463 * @param $text String
1464 * @param $linestart Boolean: is this the start of a line?
1465 * @param $interface Boolean: is this text in the user interface language?
1466 */
1467 public function addWikiText( $text, $linestart = true, $interface = true ) {
1468 $title = $this->getTitle(); // Work arround E_STRICT
1469 if ( !$title ) {
1470 throw new MWException( 'Title is null' );
1471 }
1472 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1473 }
1474
1475 /**
1476 * Add wikitext with a custom Title object
1477 *
1478 * @param $text String: wikitext
1479 * @param $title Title object
1480 * @param $linestart Boolean: is this the start of a line?
1481 */
1482 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1483 $this->addWikiTextTitle( $text, $title, $linestart );
1484 }
1485
1486 /**
1487 * Add wikitext with a custom Title object and tidy enabled.
1488 *
1489 * @param $text String: wikitext
1490 * @param $title Title object
1491 * @param $linestart Boolean: is this the start of a line?
1492 */
1493 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1494 $this->addWikiTextTitle( $text, $title, $linestart, true );
1495 }
1496
1497 /**
1498 * Add wikitext with tidy enabled
1499 *
1500 * @param $text String: wikitext
1501 * @param $linestart Boolean: is this the start of a line?
1502 */
1503 public function addWikiTextTidy( $text, $linestart = true ) {
1504 $title = $this->getTitle();
1505 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1506 }
1507
1508 /**
1509 * Add wikitext with a custom Title object
1510 *
1511 * @param $text String: wikitext
1512 * @param $title Title object
1513 * @param $linestart Boolean: is this the start of a line?
1514 * @param $tidy Boolean: whether to use tidy
1515 * @param $interface Boolean: whether it is an interface message
1516 * (for example disables conversion)
1517 */
1518 public function addWikiTextTitle( $text, Title $title, $linestart, $tidy = false, $interface = false ) {
1519 global $wgParser;
1520
1521 wfProfileIn( __METHOD__ );
1522
1523 $popts = $this->parserOptions();
1524 $oldTidy = $popts->setTidy( $tidy );
1525 $popts->setInterfaceMessage( (bool) $interface );
1526
1527 $parserOutput = $wgParser->parse(
1528 $text, $title, $popts,
1529 $linestart, true, $this->mRevisionId
1530 );
1531
1532 $popts->setTidy( $oldTidy );
1533
1534 $this->addParserOutput( $parserOutput );
1535
1536 wfProfileOut( __METHOD__ );
1537 }
1538
1539 /**
1540 * Add a ParserOutput object, but without Html
1541 *
1542 * @param $parserOutput ParserOutput object
1543 */
1544 public function addParserOutputNoText( &$parserOutput ) {
1545 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1546 $this->addCategoryLinks( $parserOutput->getCategories() );
1547 $this->mNewSectionLink = $parserOutput->getNewSection();
1548 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1549
1550 $this->mParseWarnings = $parserOutput->getWarnings();
1551 if ( !$parserOutput->isCacheable() ) {
1552 $this->enableClientCache( false );
1553 }
1554 $this->mNoGallery = $parserOutput->getNoGallery();
1555 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1556 $this->addModules( $parserOutput->getModules() );
1557 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1558 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1559 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1560
1561 // Template versioning...
1562 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1563 if ( isset( $this->mTemplateIds[$ns] ) ) {
1564 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1565 } else {
1566 $this->mTemplateIds[$ns] = $dbks;
1567 }
1568 }
1569 // File versioning...
1570 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1571 $this->mImageTimeKeys[$dbk] = $data;
1572 }
1573
1574 // Hooks registered in the object
1575 global $wgParserOutputHooks;
1576 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1577 list( $hookName, $data ) = $hookInfo;
1578 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1579 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1580 }
1581 }
1582
1583 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1584 }
1585
1586 /**
1587 * Add a ParserOutput object
1588 *
1589 * @param $parserOutput ParserOutput
1590 */
1591 function addParserOutput( &$parserOutput ) {
1592 $this->addParserOutputNoText( $parserOutput );
1593 $text = $parserOutput->getText();
1594 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1595 $this->addHTML( $text );
1596 }
1597
1598
1599 /**
1600 * Add the output of a QuickTemplate to the output buffer
1601 *
1602 * @param $template QuickTemplate
1603 */
1604 public function addTemplate( &$template ) {
1605 ob_start();
1606 $template->execute();
1607 $this->addHTML( ob_get_contents() );
1608 ob_end_clean();
1609 }
1610
1611 /**
1612 * Parse wikitext and return the HTML.
1613 *
1614 * @param $text String
1615 * @param $linestart Boolean: is this the start of a line?
1616 * @param $interface Boolean: use interface language ($wgLang instead of
1617 * $wgContLang) while parsing language sensitive magic
1618 * words like GRAMMAR and PLURAL. This also disables
1619 * LanguageConverter.
1620 * @param $language Language object: target language object, will override
1621 * $interface
1622 * @throws MWException
1623 * @return String: HTML
1624 */
1625 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1626 global $wgParser;
1627
1628 if( is_null( $this->getTitle() ) ) {
1629 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1630 }
1631
1632 $popts = $this->parserOptions();
1633 if ( $interface ) {
1634 $popts->setInterfaceMessage( true );
1635 }
1636 if ( $language !== null ) {
1637 $oldLang = $popts->setTargetLanguage( $language );
1638 }
1639
1640 $parserOutput = $wgParser->parse(
1641 $text, $this->getTitle(), $popts,
1642 $linestart, true, $this->mRevisionId
1643 );
1644
1645 if ( $interface ) {
1646 $popts->setInterfaceMessage( false );
1647 }
1648 if ( $language !== null ) {
1649 $popts->setTargetLanguage( $oldLang );
1650 }
1651
1652 return $parserOutput->getText();
1653 }
1654
1655 /**
1656 * Parse wikitext, strip paragraphs, and return the HTML.
1657 *
1658 * @param $text String
1659 * @param $linestart Boolean: is this the start of a line?
1660 * @param $interface Boolean: use interface language ($wgLang instead of
1661 * $wgContLang) while parsing language sensitive magic
1662 * words like GRAMMAR and PLURAL
1663 * @return String: HTML
1664 */
1665 public function parseInline( $text, $linestart = true, $interface = false ) {
1666 $parsed = $this->parse( $text, $linestart, $interface );
1667
1668 $m = array();
1669 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1670 $parsed = $m[1];
1671 }
1672
1673 return $parsed;
1674 }
1675
1676 /**
1677 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1678 *
1679 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1680 */
1681 public function setSquidMaxage( $maxage ) {
1682 $this->mSquidMaxage = $maxage;
1683 }
1684
1685 /**
1686 * Use enableClientCache(false) to force it to send nocache headers
1687 *
1688 * @param $state bool
1689 *
1690 * @return bool
1691 */
1692 public function enableClientCache( $state ) {
1693 return wfSetVar( $this->mEnableClientCache, $state );
1694 }
1695
1696 /**
1697 * Get the list of cookies that will influence on the cache
1698 *
1699 * @return Array
1700 */
1701 function getCacheVaryCookies() {
1702 global $wgCookiePrefix, $wgCacheVaryCookies;
1703 static $cookies;
1704 if ( $cookies === null ) {
1705 $cookies = array_merge(
1706 array(
1707 "{$wgCookiePrefix}Token",
1708 "{$wgCookiePrefix}LoggedOut",
1709 session_name()
1710 ),
1711 $wgCacheVaryCookies
1712 );
1713 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1714 }
1715 return $cookies;
1716 }
1717
1718 /**
1719 * Check if the request has a cache-varying cookie header
1720 * If it does, it's very important that we don't allow public caching
1721 *
1722 * @return Boolean
1723 */
1724 function haveCacheVaryCookies() {
1725 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1726 if ( $cookieHeader === false ) {
1727 return false;
1728 }
1729 $cvCookies = $this->getCacheVaryCookies();
1730 foreach ( $cvCookies as $cookieName ) {
1731 # Check for a simple string match, like the way squid does it
1732 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1733 wfDebug( __METHOD__ . ": found $cookieName\n" );
1734 return true;
1735 }
1736 }
1737 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1738 return false;
1739 }
1740
1741 /**
1742 * Add an HTTP header that will influence on the cache
1743 *
1744 * @param $header String: header name
1745 * @param $option Array|null
1746 * @todo FIXME: Document the $option parameter; it appears to be for
1747 * X-Vary-Options but what format is acceptable?
1748 */
1749 public function addVaryHeader( $header, $option = null ) {
1750 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1751 $this->mVaryHeader[$header] = (array)$option;
1752 } elseif( is_array( $option ) ) {
1753 if( is_array( $this->mVaryHeader[$header] ) ) {
1754 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1755 } else {
1756 $this->mVaryHeader[$header] = $option;
1757 }
1758 }
1759 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1760 }
1761
1762 /**
1763 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1764 * such as Accept-Encoding or Cookie
1765 *
1766 * @return String
1767 */
1768 public function getVaryHeader() {
1769 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1770 }
1771
1772 /**
1773 * Get a complete X-Vary-Options header
1774 *
1775 * @return String
1776 */
1777 public function getXVO() {
1778 $cvCookies = $this->getCacheVaryCookies();
1779
1780 $cookiesOption = array();
1781 foreach ( $cvCookies as $cookieName ) {
1782 $cookiesOption[] = 'string-contains=' . $cookieName;
1783 }
1784 $this->addVaryHeader( 'Cookie', $cookiesOption );
1785
1786 $headers = array();
1787 foreach( $this->mVaryHeader as $header => $option ) {
1788 $newheader = $header;
1789 if ( is_array( $option ) && count( $option ) > 0 ) {
1790 $newheader .= ';' . implode( ';', $option );
1791 }
1792 $headers[] = $newheader;
1793 }
1794 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1795
1796 return $xvo;
1797 }
1798
1799 /**
1800 * bug 21672: Add Accept-Language to Vary and XVO headers
1801 * if there's no 'variant' parameter existed in GET.
1802 *
1803 * For example:
1804 * /w/index.php?title=Main_page should always be served; but
1805 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1806 */
1807 function addAcceptLanguage() {
1808 $lang = $this->getTitle()->getPageLanguage();
1809 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1810 $variants = $lang->getVariants();
1811 $aloption = array();
1812 foreach ( $variants as $variant ) {
1813 if( $variant === $lang->getCode() ) {
1814 continue;
1815 } else {
1816 $aloption[] = 'string-contains=' . $variant;
1817
1818 // IE and some other browsers use BCP 47 standards in
1819 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1820 // We should handle these too.
1821 $variantBCP47 = wfBCP47( $variant );
1822 if ( $variantBCP47 !== $variant ) {
1823 $aloption[] = 'string-contains=' . $variantBCP47;
1824 }
1825 }
1826 }
1827 $this->addVaryHeader( 'Accept-Language', $aloption );
1828 }
1829 }
1830
1831 /**
1832 * Set a flag which will cause an X-Frame-Options header appropriate for
1833 * edit pages to be sent. The header value is controlled by
1834 * $wgEditPageFrameOptions.
1835 *
1836 * This is the default for special pages. If you display a CSRF-protected
1837 * form on an ordinary view page, then you need to call this function.
1838 *
1839 * @param $enable bool
1840 */
1841 public function preventClickjacking( $enable = true ) {
1842 $this->mPreventClickjacking = $enable;
1843 }
1844
1845 /**
1846 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1847 * This can be called from pages which do not contain any CSRF-protected
1848 * HTML form.
1849 */
1850 public function allowClickjacking() {
1851 $this->mPreventClickjacking = false;
1852 }
1853
1854 /**
1855 * Get the X-Frame-Options header value (without the name part), or false
1856 * if there isn't one. This is used by Skin to determine whether to enable
1857 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1858 *
1859 * @return string
1860 */
1861 public function getFrameOptions() {
1862 global $wgBreakFrames, $wgEditPageFrameOptions;
1863 if ( $wgBreakFrames ) {
1864 return 'DENY';
1865 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1866 return $wgEditPageFrameOptions;
1867 }
1868 return false;
1869 }
1870
1871 /**
1872 * Send cache control HTTP headers
1873 */
1874 public function sendCacheControl() {
1875 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1876
1877 $response = $this->getRequest()->response();
1878 if ( $wgUseETag && $this->mETag ) {
1879 $response->header( "ETag: $this->mETag" );
1880 }
1881
1882 $this->addVaryHeader( 'Cookie' );
1883 $this->addAcceptLanguage();
1884
1885 # don't serve compressed data to clients who can't handle it
1886 # maintain different caches for logged-in users and non-logged in ones
1887 $response->header( $this->getVaryHeader() );
1888
1889 if ( $wgUseXVO ) {
1890 # Add an X-Vary-Options header for Squid with Wikimedia patches
1891 $response->header( $this->getXVO() );
1892 }
1893
1894 if( $this->mEnableClientCache ) {
1895 if(
1896 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1897 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1898 )
1899 {
1900 if ( $wgUseESI ) {
1901 # We'll purge the proxy cache explicitly, but require end user agents
1902 # to revalidate against the proxy on each visit.
1903 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1904 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1905 # start with a shorter timeout for initial testing
1906 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1907 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
1908 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1909 } else {
1910 # We'll purge the proxy cache for anons explicitly, but require end user agents
1911 # to revalidate against the proxy on each visit.
1912 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1913 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1914 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1915 # start with a shorter timeout for initial testing
1916 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1917 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0' );
1918 }
1919 } else {
1920 # We do want clients to cache if they can, but they *must* check for updates
1921 # on revisiting the page.
1922 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1923 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1924 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1925 }
1926 if( $this->mLastModified ) {
1927 $response->header( "Last-Modified: {$this->mLastModified}" );
1928 }
1929 } else {
1930 wfDebug( __METHOD__ . ": no caching **\n", false );
1931
1932 # In general, the absence of a last modified header should be enough to prevent
1933 # the client from using its cache. We send a few other things just to make sure.
1934 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1935 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1936 $response->header( 'Pragma: no-cache' );
1937 }
1938 }
1939
1940 /**
1941 * Get the message associed with the HTTP response code $code
1942 *
1943 * @param $code Integer: status code
1944 * @return String or null: message or null if $code is not in the list of
1945 * messages
1946 *
1947 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1948 */
1949 public static function getStatusMessage( $code ) {
1950 wfDeprecated( __METHOD__, '1.18' );
1951 return HttpStatus::getMessage( $code );
1952 }
1953
1954 /**
1955 * Finally, all the text has been munged and accumulated into
1956 * the object, let's actually output it:
1957 */
1958 public function output() {
1959 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1960
1961 if( $this->mDoNothing ) {
1962 return;
1963 }
1964
1965 wfProfileIn( __METHOD__ );
1966
1967 $response = $this->getRequest()->response();
1968
1969 if ( $this->mRedirect != '' ) {
1970 # Standards require redirect URLs to be absolute
1971 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
1972
1973 $redirect = $this->mRedirect;
1974 $code = $this->mRedirectCode;
1975
1976 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1977 if( $code == '301' || $code == '303' ) {
1978 if( !$wgDebugRedirects ) {
1979 $message = HttpStatus::getMessage( $code );
1980 $response->header( "HTTP/1.1 $code $message" );
1981 }
1982 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1983 }
1984 if ( $wgVaryOnXFP ) {
1985 $this->addVaryHeader( 'X-Forwarded-Proto' );
1986 }
1987 $this->sendCacheControl();
1988
1989 $response->header( "Content-Type: text/html; charset=utf-8" );
1990 if( $wgDebugRedirects ) {
1991 $url = htmlspecialchars( $redirect );
1992 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1993 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1994 print "</body>\n</html>\n";
1995 } else {
1996 $response->header( 'Location: ' . $redirect );
1997 }
1998 }
1999
2000 wfProfileOut( __METHOD__ );
2001 return;
2002 } elseif ( $this->mStatusCode ) {
2003 $message = HttpStatus::getMessage( $this->mStatusCode );
2004 if ( $message ) {
2005 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2006 }
2007 }
2008
2009 # Buffer output; final headers may depend on later processing
2010 ob_start();
2011
2012 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2013 $response->header( 'Content-language: ' . $wgLanguageCode );
2014
2015 // Prevent framing, if requested
2016 $frameOptions = $this->getFrameOptions();
2017 if ( $frameOptions ) {
2018 $response->header( "X-Frame-Options: $frameOptions" );
2019 }
2020
2021 if ( $this->mArticleBodyOnly ) {
2022 $this->out( $this->mBodytext );
2023 } else {
2024 $this->addDefaultModules();
2025
2026 $sk = $this->getSkin();
2027
2028 // Hook that allows last minute changes to the output page, e.g.
2029 // adding of CSS or Javascript by extensions.
2030 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2031
2032 wfProfileIn( 'Output-skin' );
2033 $sk->outputPage();
2034 wfProfileOut( 'Output-skin' );
2035 }
2036
2037 // This hook allows last minute changes to final overall output by modifying output buffer
2038 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2039
2040 $this->sendCacheControl();
2041
2042 ob_end_flush();
2043
2044 wfProfileOut( __METHOD__ );
2045 }
2046
2047 /**
2048 * Actually output something with print().
2049 *
2050 * @param $ins String: the string to output
2051 */
2052 public function out( $ins ) {
2053 print $ins;
2054 }
2055
2056 /**
2057 * Produce a "user is blocked" page.
2058 * @deprecated since 1.18
2059 */
2060 function blockedPage() {
2061 throw new UserBlockedError( $this->getUser()->mBlock );
2062 }
2063
2064 /**
2065 * Prepare this object to display an error page; disable caching and
2066 * indexing, clear the current text and redirect, set the page's title
2067 * and optionally an custom HTML title (content of the "<title>" tag).
2068 *
2069 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2070 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2071 * optional, if not passed the "<title>" attribute will be
2072 * based on $pageTitle
2073 */
2074 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2075 $this->setPageTitle( $pageTitle );
2076 if ( $htmlTitle !== false ) {
2077 $this->setHTMLTitle( $htmlTitle );
2078 }
2079 $this->setRobotPolicy( 'noindex,nofollow' );
2080 $this->setArticleRelated( false );
2081 $this->enableClientCache( false );
2082 $this->mRedirect = '';
2083 $this->clearSubtitle();
2084 $this->clearHTML();
2085 }
2086
2087 /**
2088 * Output a standard error page
2089 *
2090 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2091 * showErrorPage( 'titlemsg', $messageObject );
2092 * showErrorPage( $titleMessageObj, $messageObject );
2093 *
2094 * @param $title Mixed: message key (string) for page title, or a Message object
2095 * @param $msg Mixed: message key (string) for page text, or a Message object
2096 * @param $params Array: message parameters; ignored if $msg is a Message object
2097 */
2098 public function showErrorPage( $title, $msg, $params = array() ) {
2099 if( !$title instanceof Message ) {
2100 $title = $this->msg( $title );
2101 }
2102
2103 $this->prepareErrorPage( $title );
2104
2105 if ( $msg instanceof Message ) {
2106 $this->addHTML( $msg->parseAsBlock() );
2107 } else {
2108 $this->addWikiMsgArray( $msg, $params );
2109 }
2110
2111 $this->returnToMain();
2112 }
2113
2114 /**
2115 * Output a standard permission error page
2116 *
2117 * @param $errors Array: error message keys
2118 * @param $action String: action that was denied or null if unknown
2119 */
2120 public function showPermissionsErrorPage( $errors, $action = null ) {
2121 // For some action (read, edit, create and upload), display a "login to do this action"
2122 // error if all of the following conditions are met:
2123 // 1. the user is not logged in
2124 // 2. the only error is insufficient permissions (i.e. no block or something else)
2125 // 3. the error can be avoided simply by logging in
2126 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2127 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2128 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2129 && ( User::groupHasPermission( 'user', $action )
2130 || User::groupHasPermission( 'autoconfirmed', $action ) )
2131 ) {
2132 $displayReturnto = null;
2133
2134 # Due to bug 32276, if a user does not have read permissions,
2135 # $this->getTitle() will just give Special:Badtitle, which is
2136 # not especially useful as a returnto parameter. Use the title
2137 # from the request instead, if there was one.
2138 $request = $this->getRequest();
2139 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2140 if ( $action == 'edit' ) {
2141 $msg = 'whitelistedittext';
2142 $displayReturnto = $returnto;
2143 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2144 $msg = 'nocreatetext';
2145 } elseif ( $action == 'upload' ) {
2146 $msg = 'uploadnologintext';
2147 } else { # Read
2148 $msg = 'loginreqpagetext';
2149 $displayReturnto = Title::newMainPage();
2150 }
2151
2152 $query = array();
2153
2154 if ( $returnto ) {
2155 $query['returnto'] = $returnto->getPrefixedText();
2156
2157 if ( !$request->wasPosted() ) {
2158 $returntoquery = $request->getValues();
2159 unset( $returntoquery['title'] );
2160 unset( $returntoquery['returnto'] );
2161 unset( $returntoquery['returntoquery'] );
2162 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2163 }
2164 }
2165 $loginLink = Linker::linkKnown(
2166 SpecialPage::getTitleFor( 'Userlogin' ),
2167 $this->msg( 'loginreqlink' )->escaped(),
2168 array(),
2169 $query
2170 );
2171
2172 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2173 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2174
2175 # Don't return to a page the user can't read otherwise
2176 # we'll end up in a pointless loop
2177 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2178 $this->returnToMain( null, $displayReturnto );
2179 }
2180 } else {
2181 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2182 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2183 }
2184 }
2185
2186 /**
2187 * Display an error page indicating that a given version of MediaWiki is
2188 * required to use it
2189 *
2190 * @param $version Mixed: the version of MediaWiki needed to use the page
2191 */
2192 public function versionRequired( $version ) {
2193 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2194
2195 $this->addWikiMsg( 'versionrequiredtext', $version );
2196 $this->returnToMain();
2197 }
2198
2199 /**
2200 * Display an error page noting that a given permission bit is required.
2201 * @deprecated since 1.18, just throw the exception directly
2202 * @param $permission String: key required
2203 * @throws PermissionsError
2204 */
2205 public function permissionRequired( $permission ) {
2206 throw new PermissionsError( $permission );
2207 }
2208
2209 /**
2210 * Produce the stock "please login to use the wiki" page
2211 *
2212 * @deprecated in 1.19; throw the exception directly
2213 */
2214 public function loginToUse() {
2215 throw new PermissionsError( 'read' );
2216 }
2217
2218 /**
2219 * Format a list of error messages
2220 *
2221 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2222 * @param $action String: action that was denied or null if unknown
2223 * @return String: the wikitext error-messages, formatted into a list.
2224 */
2225 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2226 if ( $action == null ) {
2227 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2228 } else {
2229 $action_desc = $this->msg( "action-$action" )->plain();
2230 $text = $this->msg(
2231 'permissionserrorstext-withaction',
2232 count( $errors ),
2233 $action_desc
2234 )->plain() . "\n\n";
2235 }
2236
2237 if ( count( $errors ) > 1 ) {
2238 $text .= '<ul class="permissions-errors">' . "\n";
2239
2240 foreach( $errors as $error ) {
2241 $text .= '<li>';
2242 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2243 $text .= "</li>\n";
2244 }
2245 $text .= '</ul>';
2246 } else {
2247 $text .= "<div class=\"permissions-errors\">\n" .
2248 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2249 "\n</div>";
2250 }
2251
2252 return $text;
2253 }
2254
2255 /**
2256 * Display a page stating that the Wiki is in read-only mode,
2257 * and optionally show the source of the page that the user
2258 * was trying to edit. Should only be called (for this
2259 * purpose) after wfReadOnly() has returned true.
2260 *
2261 * For historical reasons, this function is _also_ used to
2262 * show the error message when a user tries to edit a page
2263 * they are not allowed to edit. (Unless it's because they're
2264 * blocked, then we show blockedPage() instead.) In this
2265 * case, the second parameter should be set to true and a list
2266 * of reasons supplied as the third parameter.
2267 *
2268 * @todo Needs to be split into multiple functions.
2269 *
2270 * @param $source String: source code to show (or null).
2271 * @param $protected Boolean: is this a permissions error?
2272 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2273 * @param $action String: action that was denied or null if unknown
2274 * @throws ReadOnlyError
2275 */
2276 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2277 $this->setRobotPolicy( 'noindex,nofollow' );
2278 $this->setArticleRelated( false );
2279
2280 // If no reason is given, just supply a default "I can't let you do
2281 // that, Dave" message. Should only occur if called by legacy code.
2282 if ( $protected && empty( $reasons ) ) {
2283 $reasons[] = array( 'badaccess-group0' );
2284 }
2285
2286 if ( !empty( $reasons ) ) {
2287 // Permissions error
2288 if( $source ) {
2289 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2290 $this->addBacklinkSubtitle( $this->getTitle() );
2291 } else {
2292 $this->setPageTitle( $this->msg( 'badaccess' ) );
2293 }
2294 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2295 } else {
2296 // Wiki is read only
2297 throw new ReadOnlyError;
2298 }
2299
2300 // Show source, if supplied
2301 if( is_string( $source ) ) {
2302 $this->addWikiMsg( 'viewsourcetext' );
2303
2304 $pageLang = $this->getTitle()->getPageLanguage();
2305 $params = array(
2306 'id' => 'wpTextbox1',
2307 'name' => 'wpTextbox1',
2308 'cols' => $this->getUser()->getOption( 'cols' ),
2309 'rows' => $this->getUser()->getOption( 'rows' ),
2310 'readonly' => 'readonly',
2311 'lang' => $pageLang->getHtmlCode(),
2312 'dir' => $pageLang->getDir(),
2313 );
2314 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2315
2316 // Show templates used by this article
2317 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2318 $this->addHTML( "<div class='templatesUsed'>
2319 $templates
2320 </div>
2321 " );
2322 }
2323
2324 # If the title doesn't exist, it's fairly pointless to print a return
2325 # link to it. After all, you just tried editing it and couldn't, so
2326 # what's there to do there?
2327 if( $this->getTitle()->exists() ) {
2328 $this->returnToMain( null, $this->getTitle() );
2329 }
2330 }
2331
2332 /**
2333 * Turn off regular page output and return an error reponse
2334 * for when rate limiting has triggered.
2335 */
2336 public function rateLimited() {
2337 throw new ThrottledError;
2338 }
2339
2340 /**
2341 * Show a warning about slave lag
2342 *
2343 * If the lag is higher than $wgSlaveLagCritical seconds,
2344 * then the warning is a bit more obvious. If the lag is
2345 * lower than $wgSlaveLagWarning, then no warning is shown.
2346 *
2347 * @param $lag Integer: slave lag
2348 */
2349 public function showLagWarning( $lag ) {
2350 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2351 if( $lag >= $wgSlaveLagWarning ) {
2352 $message = $lag < $wgSlaveLagCritical
2353 ? 'lag-warn-normal'
2354 : 'lag-warn-high';
2355 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2356 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2357 }
2358 }
2359
2360 public function showFatalError( $message ) {
2361 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2362
2363 $this->addHTML( $message );
2364 }
2365
2366 public function showUnexpectedValueError( $name, $val ) {
2367 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2368 }
2369
2370 public function showFileCopyError( $old, $new ) {
2371 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2372 }
2373
2374 public function showFileRenameError( $old, $new ) {
2375 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2376 }
2377
2378 public function showFileDeleteError( $name ) {
2379 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2380 }
2381
2382 public function showFileNotFoundError( $name ) {
2383 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2384 }
2385
2386 /**
2387 * Add a "return to" link pointing to a specified title
2388 *
2389 * @param $title Title to link
2390 * @param $query Array query string parameters
2391 * @param $text String text of the link (input is not escaped)
2392 * @param $options Options array to pass to Linker
2393 */
2394 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2395 if( in_array( 'http', $options ) ) {
2396 $proto = PROTO_HTTP;
2397 } elseif( in_array( 'https', $options ) ) {
2398 $proto = PROTO_HTTPS;
2399 } else {
2400 $proto = PROTO_RELATIVE;
2401 }
2402
2403 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL( '', false, $proto ) ) );
2404 $link = $this->msg( 'returnto' )->rawParams(
2405 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2406 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2407 }
2408
2409 /**
2410 * Add a "return to" link pointing to a specified title,
2411 * or the title indicated in the request, or else the main page
2412 *
2413 * @param $unused
2414 * @param $returnto Title or String to return to
2415 * @param $returntoquery String: query string for the return to link
2416 */
2417 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2418 if ( $returnto == null ) {
2419 $returnto = $this->getRequest()->getText( 'returnto' );
2420 }
2421
2422 if ( $returntoquery == null ) {
2423 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2424 }
2425
2426 if ( $returnto === '' ) {
2427 $returnto = Title::newMainPage();
2428 }
2429
2430 if ( is_object( $returnto ) ) {
2431 $titleObj = $returnto;
2432 } else {
2433 $titleObj = Title::newFromText( $returnto );
2434 }
2435 if ( !is_object( $titleObj ) ) {
2436 $titleObj = Title::newMainPage();
2437 }
2438
2439 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2440 }
2441
2442 /**
2443 * @param $sk Skin The given Skin
2444 * @param $includeStyle Boolean: unused
2445 * @return String: The doctype, opening "<html>", and head element.
2446 */
2447 public function headElement( Skin $sk, $includeStyle = true ) {
2448 global $wgContLang;
2449
2450 $userdir = $this->getLanguage()->getDir();
2451 $sitedir = $wgContLang->getDir();
2452
2453 if ( $sk->commonPrintStylesheet() ) {
2454 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2455 }
2456
2457 $ret = Html::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2458
2459 if ( $this->getHTMLTitle() == '' ) {
2460 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2461 }
2462
2463 $openHead = Html::openElement( 'head' );
2464 if ( $openHead ) {
2465 # Don't bother with the newline if $head == ''
2466 $ret .= "$openHead\n";
2467 }
2468
2469 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2470
2471 $ret .= implode( "\n", array(
2472 $this->getHeadLinks( null, true ),
2473 $this->buildCssLinks(),
2474 $this->getHeadScripts(),
2475 $this->getHeadItems()
2476 ) );
2477
2478 $closeHead = Html::closeElement( 'head' );
2479 if ( $closeHead ) {
2480 $ret .= "$closeHead\n";
2481 }
2482
2483 $bodyAttrs = array();
2484
2485 # Classes for LTR/RTL directionality support
2486 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2487
2488 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2489 # A <body> class is probably not the best way to do this . . .
2490 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2491 }
2492 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2493 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2494 $bodyAttrs['class'] .= ' action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2495
2496 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2497 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2498
2499 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2500
2501 return $ret;
2502 }
2503
2504 /**
2505 * Add the default ResourceLoader modules to this object
2506 */
2507 private function addDefaultModules() {
2508 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2509 $wgAjaxWatch, $wgResponsiveImages;
2510
2511 // Add base resources
2512 $this->addModules( array(
2513 'mediawiki.user',
2514 'mediawiki.page.startup',
2515 'mediawiki.page.ready',
2516 ) );
2517 if ( $wgIncludeLegacyJavaScript ) {
2518 $this->addModules( 'mediawiki.legacy.wikibits' );
2519 }
2520
2521 if ( $wgPreloadJavaScriptMwUtil ) {
2522 $this->addModules( 'mediawiki.util' );
2523 }
2524
2525 MWDebug::addModules( $this );
2526
2527 // Add various resources if required
2528 if ( $wgUseAjax ) {
2529 $this->addModules( 'mediawiki.legacy.ajax' );
2530
2531 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2532
2533 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2534 $this->addModules( 'mediawiki.page.watch.ajax' );
2535 }
2536
2537 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2538 $this->addModules( 'mediawiki.searchSuggest' );
2539 }
2540 }
2541
2542 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2543 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2544 }
2545
2546 # Crazy edit-on-double-click stuff
2547 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2548 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2549 }
2550
2551 // Support for high-density display images
2552 if ( $wgResponsiveImages ) {
2553 $this->addModules( 'mediawiki.hidpi' );
2554 }
2555 }
2556
2557 /**
2558 * Get a ResourceLoader object associated with this OutputPage
2559 *
2560 * @return ResourceLoader
2561 */
2562 public function getResourceLoader() {
2563 if ( is_null( $this->mResourceLoader ) ) {
2564 $this->mResourceLoader = new ResourceLoader();
2565 }
2566 return $this->mResourceLoader;
2567 }
2568
2569 /**
2570 * TODO: Document
2571 * @param $modules Array/string with the module name(s)
2572 * @param $only String ResourceLoaderModule TYPE_ class constant
2573 * @param $useESI boolean
2574 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2575 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2576 * @return string html "<script>" and "<style>" tags
2577 */
2578 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2579 global $wgResourceLoaderUseESI;
2580
2581 $modules = (array) $modules;
2582
2583 if ( !count( $modules ) ) {
2584 return '';
2585 }
2586
2587 if ( count( $modules ) > 1 ) {
2588 // Remove duplicate module requests
2589 $modules = array_unique( $modules );
2590 // Sort module names so requests are more uniform
2591 sort( $modules );
2592
2593 if ( ResourceLoader::inDebugMode() ) {
2594 // Recursively call us for every item
2595 $links = '';
2596 foreach ( $modules as $name ) {
2597 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2598 }
2599 return $links;
2600 }
2601 }
2602
2603 // Create keyed-by-group list of module objects from modules list
2604 $groups = array();
2605 $resourceLoader = $this->getResourceLoader();
2606 foreach ( $modules as $name ) {
2607 $module = $resourceLoader->getModule( $name );
2608 # Check that we're allowed to include this module on this page
2609 if ( !$module
2610 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2611 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2612 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2613 && $only == ResourceLoaderModule::TYPE_STYLES )
2614 )
2615 {
2616 continue;
2617 }
2618
2619 $group = $module->getGroup();
2620 if ( !isset( $groups[$group] ) ) {
2621 $groups[$group] = array();
2622 }
2623 $groups[$group][$name] = $module;
2624 }
2625
2626 $links = '';
2627 foreach ( $groups as $group => $grpModules ) {
2628 // Special handling for user-specific groups
2629 $user = null;
2630 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2631 $user = $this->getUser()->getName();
2632 }
2633
2634 // Create a fake request based on the one we are about to make so modules return
2635 // correct timestamp and emptiness data
2636 $query = ResourceLoader::makeLoaderQuery(
2637 array(), // modules; not determined yet
2638 $this->getLanguage()->getCode(),
2639 $this->getSkin()->getSkinName(),
2640 $user,
2641 null, // version; not determined yet
2642 ResourceLoader::inDebugMode(),
2643 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2644 $this->isPrintable(),
2645 $this->getRequest()->getBool( 'handheld' ),
2646 $extraQuery
2647 );
2648 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2649 // Extract modules that know they're empty
2650 $emptyModules = array ();
2651 foreach ( $grpModules as $key => $module ) {
2652 if ( $module->isKnownEmpty( $context ) ) {
2653 $emptyModules[$key] = 'ready';
2654 unset( $grpModules[$key] );
2655 }
2656 }
2657 // Inline empty modules: since they're empty, just mark them as 'ready'
2658 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule::TYPE_STYLES ) {
2659 // If we're only getting the styles, we don't need to do anything for empty modules.
2660 $links .= Html::inlineScript(
2661
2662 ResourceLoader::makeLoaderConditionalScript(
2663
2664 ResourceLoader::makeLoaderStateScript( $emptyModules )
2665
2666 )
2667
2668 ) . "\n";
2669 }
2670
2671 // If there are no modules left, skip this group
2672 if ( count( $grpModules ) === 0 ) {
2673 continue;
2674 }
2675
2676 // Inline private modules. These can't be loaded through load.php for security
2677 // reasons, see bug 34907. Note that these modules should be loaded from
2678 // getHeadScripts() before the first loader call. Otherwise other modules can't
2679 // properly use them as dependencies (bug 30914)
2680 if ( $group === 'private' ) {
2681 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2682 $links .= Html::inlineStyle(
2683 $resourceLoader->makeModuleResponse( $context, $grpModules )
2684 );
2685 } else {
2686 $links .= Html::inlineScript(
2687 ResourceLoader::makeLoaderConditionalScript(
2688 $resourceLoader->makeModuleResponse( $context, $grpModules )
2689 )
2690 );
2691 }
2692 $links .= "\n";
2693 continue;
2694 }
2695 // Special handling for the user group; because users might change their stuff
2696 // on-wiki like user pages, or user preferences; we need to find the highest
2697 // timestamp of these user-changable modules so we can ensure cache misses on change
2698 // This should NOT be done for the site group (bug 27564) because anons get that too
2699 // and we shouldn't be putting timestamps in Squid-cached HTML
2700 $version = null;
2701 if ( $group === 'user' ) {
2702 // Get the maximum timestamp
2703 $timestamp = 1;
2704 foreach ( $grpModules as $module ) {
2705 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2706 }
2707 // Add a version parameter so cache will break when things change
2708 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2709 }
2710
2711 $url = ResourceLoader::makeLoaderURL(
2712 array_keys( $grpModules ),
2713 $this->getLanguage()->getCode(),
2714 $this->getSkin()->getSkinName(),
2715 $user,
2716 $version,
2717 ResourceLoader::inDebugMode(),
2718 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2719 $this->isPrintable(),
2720 $this->getRequest()->getBool( 'handheld' ),
2721 $extraQuery
2722 );
2723 if ( $useESI && $wgResourceLoaderUseESI ) {
2724 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2725 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2726 $link = Html::inlineStyle( $esi );
2727 } else {
2728 $link = Html::inlineScript( $esi );
2729 }
2730 } else {
2731 // Automatically select style/script elements
2732 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2733 $link = Html::linkedStyle( $url );
2734 } else if ( $loadCall ) {
2735 $link = Html::inlineScript(
2736 ResourceLoader::makeLoaderConditionalScript(
2737 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2738 )
2739 );
2740 } else {
2741 $link = Html::linkedScript( $url );
2742 }
2743 }
2744
2745 if( $group == 'noscript' ) {
2746 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2747 } else {
2748 $links .= $link . "\n";
2749 }
2750 }
2751 return $links;
2752 }
2753
2754 /**
2755 * JS stuff to put in the "<head>". This is the startup module, config
2756 * vars and modules marked with position 'top'
2757 *
2758 * @return String: HTML fragment
2759 */
2760 function getHeadScripts() {
2761 global $wgResourceLoaderExperimentalAsyncLoading;
2762
2763 // Startup - this will immediately load jquery and mediawiki modules
2764 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2765
2766 // Load config before anything else
2767 $scripts .= Html::inlineScript(
2768 ResourceLoader::makeLoaderConditionalScript(
2769 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2770 )
2771 );
2772
2773 // Load embeddable private modules before any loader links
2774 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2775 // in mw.loader.implement() calls and deferred until mw.user is available
2776 $embedScripts = array( 'user.options', 'user.tokens' );
2777 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2778
2779 // Script and Messages "only" requests marked for top inclusion
2780 // Messages should go first
2781 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2782 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2783
2784 // Modules requests - let the client calculate dependencies and batch requests as it likes
2785 // Only load modules that have marked themselves for loading at the top
2786 $modules = $this->getModules( true, 'top' );
2787 if ( $modules ) {
2788 $scripts .= Html::inlineScript(
2789 ResourceLoader::makeLoaderConditionalScript(
2790 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2791 )
2792 );
2793 }
2794
2795 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2796 $scripts .= $this->getScriptsForBottomQueue( true );
2797 }
2798
2799 return $scripts;
2800 }
2801
2802 /**
2803 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2804 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2805 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2806 * user preferences, site JS and user JS
2807 *
2808 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2809 * @return string
2810 */
2811 function getScriptsForBottomQueue( $inHead ) {
2812 global $wgUseSiteJs, $wgAllowUserJs;
2813
2814 // Script and Messages "only" requests marked for bottom inclusion
2815 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2816 // Messages should go first
2817 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2818 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2819 /* $loadCall = */ $inHead
2820 );
2821 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2822 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2823 /* $loadCall = */ $inHead
2824 );
2825
2826 // Modules requests - let the client calculate dependencies and batch requests as it likes
2827 // Only load modules that have marked themselves for loading at the bottom
2828 $modules = $this->getModules( true, 'bottom' );
2829 if ( $modules ) {
2830 $scripts .= Html::inlineScript(
2831 ResourceLoader::makeLoaderConditionalScript(
2832 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2833 )
2834 );
2835 }
2836
2837 // Legacy Scripts
2838 $scripts .= "\n" . $this->mScripts;
2839
2840 $defaultModules = array();
2841
2842 // Add site JS if enabled
2843 if ( $wgUseSiteJs ) {
2844 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2845 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2846 );
2847 $defaultModules['site'] = 'loading';
2848 } else {
2849 // The wiki is configured to not allow a site module.
2850 $defaultModules['site'] = 'missing';
2851 }
2852
2853 // Add user JS if enabled
2854 if ( $wgAllowUserJs ) {
2855 if ( $this->getUser()->isLoggedIn() ) {
2856 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2857 # XXX: additional security check/prompt?
2858 // We're on a preview of a JS subpage
2859 // Exclude this page from the user module in case it's in there (bug 26283)
2860 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2861 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2862 );
2863 // Load the previewed JS
2864 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2865 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2866 // asynchronously and may arrive *after* the inline script here. So the previewed code
2867 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2868 } else {
2869 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2870 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
2871 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2872 );
2873 }
2874 $defaultModules['user'] = 'loading';
2875 } else {
2876 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2877 // blocking default gadgets that might depend on it. Although arguably default-enabled
2878 // gadgets should not depend on the user module, it's harmless and less error-prone to
2879 // handle this case.
2880 $defaultModules['user'] = 'ready';
2881 }
2882 } else {
2883 // User JS disabled
2884 $defaultModules['user'] = 'missing';
2885 }
2886
2887 // Group JS is only enabled if site JS is enabled.
2888 if ( $wgUseSiteJs ) {
2889 if ( $this->getUser()->isLoggedIn() ) {
2890 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
2891 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2892 );
2893 $defaultModules['user.groups'] = 'loading';
2894 } else {
2895 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2896 // avoid blocking gadgets that might depend upon the module.
2897 $defaultModules['user.groups'] = 'ready';
2898 }
2899 } else {
2900 // Site (and group JS) disabled
2901 $defaultModules['user.groups'] = 'missing';
2902 }
2903
2904 $loaderInit = '';
2905 if ( $inHead ) {
2906 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2907 foreach ( $defaultModules as $m => $state ) {
2908 if ( $state == 'loading' ) {
2909 unset( $defaultModules[$m] );
2910 }
2911 }
2912 }
2913 if ( count( $defaultModules ) > 0 ) {
2914 $loaderInit = Html::inlineScript(
2915 ResourceLoader::makeLoaderConditionalScript(
2916 ResourceLoader::makeLoaderStateScript( $defaultModules )
2917 )
2918 ) . "\n";
2919 }
2920 return $loaderInit . $scripts;
2921 }
2922
2923 /**
2924 * JS stuff to put at the bottom of the "<body>"
2925 * @return string
2926 */
2927 function getBottomScripts() {
2928 global $wgResourceLoaderExperimentalAsyncLoading;
2929 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2930 return $this->getScriptsForBottomQueue( false );
2931 } else {
2932 return '';
2933 }
2934 }
2935
2936 /**
2937 * Add one or more variables to be set in mw.config in JavaScript.
2938 *
2939 * @param $keys {String|Array} Key or array of key/value pairs.
2940 * @param $value {Mixed} [optional] Value of the configuration variable.
2941 */
2942 public function addJsConfigVars( $keys, $value = null ) {
2943 if ( is_array( $keys ) ) {
2944 foreach ( $keys as $key => $value ) {
2945 $this->mJsConfigVars[$key] = $value;
2946 }
2947 return;
2948 }
2949
2950 $this->mJsConfigVars[$keys] = $value;
2951 }
2952
2953
2954 /**
2955 * Get an array containing the variables to be set in mw.config in JavaScript.
2956 *
2957 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2958 * This is only public until that function is removed. You have been warned.
2959 *
2960 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2961 * - in other words, page-independent/site-wide variables (without state).
2962 * You will only be adding bloat to the html page and causing page caches to
2963 * have to be purged on configuration changes.
2964 * @return array
2965 */
2966 public function getJSVars() {
2967 global $wgContLang;
2968
2969 $latestRevID = 0;
2970 $pageID = 0;
2971 $canonicalName = false; # bug 21115
2972
2973 $title = $this->getTitle();
2974 $ns = $title->getNamespace();
2975 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2976
2977 // Get the relevant title so that AJAX features can use the correct page name
2978 // when making API requests from certain special pages (bug 34972).
2979 $relevantTitle = $this->getSkin()->getRelevantTitle();
2980
2981 if ( $ns == NS_SPECIAL ) {
2982 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2983 } elseif ( $this->canUseWikiPage() ) {
2984 $wikiPage = $this->getWikiPage();
2985 $latestRevID = $wikiPage->getLatest();
2986 $pageID = $wikiPage->getId();
2987 }
2988
2989 $lang = $title->getPageLanguage();
2990
2991 // Pre-process information
2992 $separatorTransTable = $lang->separatorTransformTable();
2993 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
2994 $compactSeparatorTransTable = array(
2995 implode( "\t", array_keys( $separatorTransTable ) ),
2996 implode( "\t", $separatorTransTable ),
2997 );
2998 $digitTransTable = $lang->digitTransformTable();
2999 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3000 $compactDigitTransTable = array(
3001 implode( "\t", array_keys( $digitTransTable ) ),
3002 implode( "\t", $digitTransTable ),
3003 );
3004
3005 $vars = array(
3006 'wgCanonicalNamespace' => $nsname,
3007 'wgCanonicalSpecialPageName' => $canonicalName,
3008 'wgNamespaceNumber' => $title->getNamespace(),
3009 'wgPageName' => $title->getPrefixedDBKey(),
3010 'wgTitle' => $title->getText(),
3011 'wgCurRevisionId' => $latestRevID,
3012 'wgArticleId' => $pageID,
3013 'wgIsArticle' => $this->isArticle(),
3014 'wgAction' => Action::getActionName( $this->getContext() ),
3015 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
3016 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
3017 'wgCategories' => $this->getCategories(),
3018 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3019 'wgPageContentLanguage' => $lang->getCode(),
3020 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3021 'wgDigitTransformTable' => $compactDigitTransTable,
3022 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3023 'wgMonthNames' => $lang->getMonthNamesArray(),
3024 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3025 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
3026 );
3027 if ( $wgContLang->hasVariants() ) {
3028 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3029 }
3030 foreach ( $title->getRestrictionTypes() as $type ) {
3031 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3032 }
3033 if ( $title->isMainPage() ) {
3034 $vars['wgIsMainPage'] = true;
3035 }
3036 if ( $this->mRedirectedFrom ) {
3037 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBKey();
3038 }
3039
3040 // Allow extensions to add their custom variables to the mw.config map.
3041 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3042 // page-dependant but site-wide (without state).
3043 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3044 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3045
3046 // Merge in variables from addJsConfigVars last
3047 return array_merge( $vars, $this->mJsConfigVars );
3048 }
3049
3050 /**
3051 * To make it harder for someone to slip a user a fake
3052 * user-JavaScript or user-CSS preview, a random token
3053 * is associated with the login session. If it's not
3054 * passed back with the preview request, we won't render
3055 * the code.
3056 *
3057 * @return bool
3058 */
3059 public function userCanPreview() {
3060 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3061 || !$this->getRequest()->wasPosted()
3062 || !$this->getUser()->matchEditToken(
3063 $this->getRequest()->getVal( 'wpEditToken' ) )
3064 ) {
3065 return false;
3066 }
3067 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3068 return false;
3069 }
3070
3071 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3072 }
3073
3074 /**
3075 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3076 *
3077 * @return array in format "link name or number => 'link html'".
3078 */
3079 public function getHeadLinksArray( $addContentType = false ) {
3080 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3081 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3082 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3083 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3084 $wgRightsPage, $wgRightsUrl;
3085
3086 $tags = array();
3087
3088 $canonicalUrl = $this->mCanonicalUrl;
3089
3090 if ( $addContentType ) {
3091 if ( $wgHtml5 ) {
3092 # More succinct than <meta http-equiv=Content-Type>, has the
3093 # same effect
3094 $tags['meta-charset'] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
3095 } else {
3096 $tags['meta-content-type'] = Html::element( 'meta', array(
3097 'http-equiv' => 'Content-Type',
3098 'content' => "$wgMimeType; charset=UTF-8"
3099 ) );
3100 $tags['meta-content-style-type'] = Html::element( 'meta', array( // bug 15835
3101 'http-equiv' => 'Content-Style-Type',
3102 'content' => 'text/css'
3103 ) );
3104 }
3105 }
3106
3107 $tags['meta-generator'] = Html::element( 'meta', array(
3108 'name' => 'generator',
3109 'content' => "MediaWiki $wgVersion",
3110 ) );
3111
3112 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3113 if( $p !== 'index,follow' ) {
3114 // http://www.robotstxt.org/wc/meta-user.html
3115 // Only show if it's different from the default robots policy
3116 $tags['meta-robots'] = Html::element( 'meta', array(
3117 'name' => 'robots',
3118 'content' => $p,
3119 ) );
3120 }
3121
3122 if ( count( $this->mKeywords ) > 0 ) {
3123 $strip = array(
3124 "/<.*?" . ">/" => '',
3125 "/_/" => ' '
3126 );
3127 $tags['meta-keywords'] = Html::element( 'meta', array(
3128 'name' => 'keywords',
3129 'content' => preg_replace(
3130 array_keys( $strip ),
3131 array_values( $strip ),
3132 implode( ',', $this->mKeywords )
3133 )
3134 ) );
3135 }
3136
3137 foreach ( $this->mMetatags as $tag ) {
3138 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3139 $a = 'http-equiv';
3140 $tag[0] = substr( $tag[0], 5 );
3141 } else {
3142 $a = 'name';
3143 }
3144 $tagName = "meta-{$tag[0]}";
3145 if ( isset( $tags[$tagName] ) ) {
3146 $tagName .= $tag[1];
3147 }
3148 $tags[$tagName] = Html::element( 'meta',
3149 array(
3150 $a => $tag[0],
3151 'content' => $tag[1]
3152 )
3153 );
3154 }
3155
3156 foreach ( $this->mLinktags as $tag ) {
3157 $tags[] = Html::element( 'link', $tag );
3158 }
3159
3160 # Universal edit button
3161 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3162 $user = $this->getUser();
3163 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3164 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3165 // Original UniversalEditButton
3166 $msg = $this->msg( 'edit' )->text();
3167 $tags['universal-edit-button'] = Html::element( 'link', array(
3168 'rel' => 'alternate',
3169 'type' => 'application/x-wiki',
3170 'title' => $msg,
3171 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3172 ) );
3173 // Alternate edit link
3174 $tags['alternative-edit'] = Html::element( 'link', array(
3175 'rel' => 'edit',
3176 'title' => $msg,
3177 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3178 ) );
3179 }
3180 }
3181
3182 # Generally the order of the favicon and apple-touch-icon links
3183 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3184 # uses whichever one appears later in the HTML source. Make sure
3185 # apple-touch-icon is specified first to avoid this.
3186 if ( $wgAppleTouchIcon !== false ) {
3187 $tags['apple-touch-icon'] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3188 }
3189
3190 if ( $wgFavicon !== false ) {
3191 $tags['favicon'] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3192 }
3193
3194 # OpenSearch description link
3195 $tags['opensearch'] = Html::element( 'link', array(
3196 'rel' => 'search',
3197 'type' => 'application/opensearchdescription+xml',
3198 'href' => wfScript( 'opensearch_desc' ),
3199 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3200 ) );
3201
3202 if ( $wgEnableAPI ) {
3203 # Real Simple Discovery link, provides auto-discovery information
3204 # for the MediaWiki API (and potentially additional custom API
3205 # support such as WordPress or Twitter-compatible APIs for a
3206 # blogging extension, etc)
3207 $tags['rsd'] = Html::element( 'link', array(
3208 'rel' => 'EditURI',
3209 'type' => 'application/rsd+xml',
3210 // Output a protocol-relative URL here if $wgServer is protocol-relative
3211 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3212 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
3213 ) );
3214 }
3215
3216
3217 # Language variants
3218 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3219 $lang = $this->getTitle()->getPageLanguage();
3220 if ( $lang->hasVariants() ) {
3221
3222 $urlvar = $lang->getURLVariant();
3223
3224 if ( !$urlvar ) {
3225 $variants = $lang->getVariants();
3226 foreach ( $variants as $_v ) {
3227 $tags["variant-$_v"] = Html::element( 'link', array(
3228 'rel' => 'alternate',
3229 'hreflang' => $_v,
3230 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3231 );
3232 }
3233 } else {
3234 $canonicalUrl = $this->getTitle()->getLocalURL();
3235 }
3236 }
3237 }
3238
3239 # Copyright
3240 $copyright = '';
3241 if ( $wgRightsPage ) {
3242 $copy = Title::newFromText( $wgRightsPage );
3243
3244 if ( $copy ) {
3245 $copyright = $copy->getLocalURL();
3246 }
3247 }
3248
3249 if ( !$copyright && $wgRightsUrl ) {
3250 $copyright = $wgRightsUrl;
3251 }
3252
3253 if ( $copyright ) {
3254 $tags['copyright'] = Html::element( 'link', array(
3255 'rel' => 'copyright',
3256 'href' => $copyright )
3257 );
3258 }
3259
3260 # Feeds
3261 if ( $wgFeed ) {
3262 foreach( $this->getSyndicationLinks() as $format => $link ) {
3263 # Use the page name for the title. In principle, this could
3264 # lead to issues with having the same name for different feeds
3265 # corresponding to the same page, but we can't avoid that at
3266 # this low a level.
3267
3268 $tags[] = $this->feedLink(
3269 $format,
3270 $link,
3271 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3272 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3273 );
3274 }
3275
3276 # Recent changes feed should appear on every page (except recentchanges,
3277 # that would be redundant). Put it after the per-page feed to avoid
3278 # changing existing behavior. It's still available, probably via a
3279 # menu in your browser. Some sites might have a different feed they'd
3280 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3281 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3282 # If so, use it instead.
3283 if ( $wgOverrideSiteFeed ) {
3284 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3285 // Note, this->feedLink escapes the url.
3286 $tags[] = $this->feedLink(
3287 $type,
3288 $feedUrl,
3289 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3290 );
3291 }
3292 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3293 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3294 foreach ( $wgAdvertisedFeedTypes as $format ) {
3295 $tags[] = $this->feedLink(
3296 $format,
3297 $rctitle->getLocalURL( "feed={$format}" ),
3298 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3299 );
3300 }
3301 }
3302 }
3303
3304 # Canonical URL
3305 global $wgEnableCanonicalServerLink;
3306 if ( $wgEnableCanonicalServerLink ) {
3307 if ( $canonicalUrl !== false ) {
3308 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3309 } else {
3310 $reqUrl = $this->getRequest()->getRequestURL();
3311 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3312 }
3313 }
3314 if ( $canonicalUrl !== false ) {
3315 $tags[] = Html::element( 'link', array(
3316 'rel' => 'canonical',
3317 'href' => $canonicalUrl
3318 ) );
3319 }
3320
3321 return $tags;
3322 }
3323
3324 /**
3325 * @param $unused
3326 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3327 *
3328 * @return string HTML tag links to be put in the header.
3329 */
3330 public function getHeadLinks( $unused = null, $addContentType = false ) {
3331 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3332 }
3333
3334 /**
3335 * Generate a "<link rel/>" for a feed.
3336 *
3337 * @param $type String: feed type
3338 * @param $url String: URL to the feed
3339 * @param $text String: value of the "title" attribute
3340 * @return String: HTML fragment
3341 */
3342 private function feedLink( $type, $url, $text ) {
3343 return Html::element( 'link', array(
3344 'rel' => 'alternate',
3345 'type' => "application/$type+xml",
3346 'title' => $text,
3347 'href' => $url )
3348 );
3349 }
3350
3351 /**
3352 * Add a local or specified stylesheet, with the given media options.
3353 * Meant primarily for internal use...
3354 *
3355 * @param $style String: URL to the file
3356 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3357 * @param $condition String: for IE conditional comments, specifying an IE version
3358 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3359 */
3360 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3361 $options = array();
3362 // Even though we expect the media type to be lowercase, but here we
3363 // force it to lowercase to be safe.
3364 if( $media ) {
3365 $options['media'] = $media;
3366 }
3367 if( $condition ) {
3368 $options['condition'] = $condition;
3369 }
3370 if( $dir ) {
3371 $options['dir'] = $dir;
3372 }
3373 $this->styles[$style] = $options;
3374 }
3375
3376 /**
3377 * Adds inline CSS styles
3378 * @param $style_css Mixed: inline CSS
3379 * @param $flip String: Set to 'flip' to flip the CSS if needed
3380 */
3381 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3382 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3383 # If wanted, and the interface is right-to-left, flip the CSS
3384 $style_css = CSSJanus::transform( $style_css, true, false );
3385 }
3386 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3387 }
3388
3389 /**
3390 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3391 * These will be applied to various media & IE conditionals.
3392 *
3393 * @return string
3394 */
3395 public function buildCssLinks() {
3396 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3397 $wgLang, $wgContLang;
3398
3399 $this->getSkin()->setupSkinUserCss( $this );
3400
3401 // Add ResourceLoader styles
3402 // Split the styles into four groups
3403 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3404 $otherTags = ''; // Tags to append after the normal <link> tags
3405 $resourceLoader = $this->getResourceLoader();
3406
3407 $moduleStyles = $this->getModuleStyles();
3408
3409 // Per-site custom styles
3410 if ( $wgUseSiteCss ) {
3411 $moduleStyles[] = 'site';
3412 $moduleStyles[] = 'noscript';
3413 if( $this->getUser()->isLoggedIn() ) {
3414 $moduleStyles[] = 'user.groups';
3415 }
3416 }
3417
3418 // Per-user custom styles
3419 if ( $wgAllowUserCss ) {
3420 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3421 // We're on a preview of a CSS subpage
3422 // Exclude this page from the user module in case it's in there (bug 26283)
3423 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3424 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3425 );
3426
3427 // Load the previewed CSS
3428 // If needed, Janus it first. This is user-supplied CSS, so it's
3429 // assumed to be right for the content language directionality.
3430 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3431 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3432 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3433 }
3434 $otherTags .= Html::inlineStyle( $previewedCSS );
3435 } else {
3436 // Load the user styles normally
3437 $moduleStyles[] = 'user';
3438 }
3439 }
3440
3441 // Per-user preference styles
3442 if ( $wgAllowUserCssPrefs ) {
3443 $moduleStyles[] = 'user.cssprefs';
3444 }
3445
3446 foreach ( $moduleStyles as $name ) {
3447 $module = $resourceLoader->getModule( $name );
3448 if ( !$module ) {
3449 continue;
3450 }
3451 $group = $module->getGroup();
3452 // Modules in groups named "other" or anything different than "user", "site" or "private"
3453 // will be placed in the "other" group
3454 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3455 }
3456
3457 // We want site, private and user styles to override dynamically added styles from modules, but we want
3458 // dynamically added styles to override statically added styles from other modules. So the order
3459 // has to be other, dynamic, site, private, user
3460 // Add statically added styles for other modules
3461 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3462 // Add normal styles added through addStyle()/addInlineStyle() here
3463 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3464 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3465 // We use a <meta> tag with a made-up name for this because that's valid HTML
3466 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3467
3468 // Add site, private and user styles
3469 // 'private' at present only contains user.options, so put that before 'user'
3470 // Any future private modules will likely have a similar user-specific character
3471 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3472 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3473 ResourceLoaderModule::TYPE_STYLES
3474 );
3475 }
3476
3477 // Add stuff in $otherTags (previewed user CSS if applicable)
3478 $ret .= $otherTags;
3479 return $ret;
3480 }
3481
3482 /**
3483 * @return Array
3484 */
3485 public function buildCssLinksArray() {
3486 $links = array();
3487
3488 // Add any extension CSS
3489 foreach ( $this->mExtStyles as $url ) {
3490 $this->addStyle( $url );
3491 }
3492 $this->mExtStyles = array();
3493
3494 foreach( $this->styles as $file => $options ) {
3495 $link = $this->styleLink( $file, $options );
3496 if( $link ) {
3497 $links[$file] = $link;
3498 }
3499 }
3500 return $links;
3501 }
3502
3503 /**
3504 * Generate \<link\> tags for stylesheets
3505 *
3506 * @param $style String: URL to the file
3507 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3508 * keys
3509 * @return String: HTML fragment
3510 */
3511 protected function styleLink( $style, $options ) {
3512 if( isset( $options['dir'] ) ) {
3513 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3514 return '';
3515 }
3516 }
3517
3518 if( isset( $options['media'] ) ) {
3519 $media = self::transformCssMedia( $options['media'] );
3520 if( is_null( $media ) ) {
3521 return '';
3522 }
3523 } else {
3524 $media = 'all';
3525 }
3526
3527 if( substr( $style, 0, 1 ) == '/' ||
3528 substr( $style, 0, 5 ) == 'http:' ||
3529 substr( $style, 0, 6 ) == 'https:' ) {
3530 $url = $style;
3531 } else {
3532 global $wgStylePath, $wgStyleVersion;
3533 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3534 }
3535
3536 $link = Html::linkedStyle( $url, $media );
3537
3538 if( isset( $options['condition'] ) ) {
3539 $condition = htmlspecialchars( $options['condition'] );
3540 $link = "<!--[if $condition]>$link<![endif]-->";
3541 }
3542 return $link;
3543 }
3544
3545 /**
3546 * Transform "media" attribute based on request parameters
3547 *
3548 * @param $media String: current value of the "media" attribute
3549 * @return String: modified value of the "media" attribute, or null to skip
3550 * this stylesheet
3551 */
3552 public static function transformCssMedia( $media ) {
3553 global $wgRequest, $wgHandheldForIPhone;
3554
3555 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3556 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3557
3558 // Switch in on-screen display for media testing
3559 $switches = array(
3560 'printable' => 'print',
3561 'handheld' => 'handheld',
3562 );
3563 foreach( $switches as $switch => $targetMedia ) {
3564 if( $wgRequest->getBool( $switch ) ) {
3565 if( $media == $targetMedia ) {
3566 $media = '';
3567 } elseif( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3568 // This regex will not attempt to understand a comma-separated media_query_list
3569 //
3570 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3571 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3572 //
3573 // If it's a print request, we never want any kind of screen styesheets
3574 // If it's a handheld request (currently the only other choice with a switch),
3575 // we don't want simple 'screen' but we might want screen queries that
3576 // have a max-width or something, so we'll pass all others on and let the
3577 // client do the query.
3578 if( $targetMedia == 'print' || $media == 'screen' ) {
3579 return null;
3580 }
3581 }
3582 }
3583 }
3584
3585 // Expand longer media queries as iPhone doesn't grok 'handheld'
3586 if( $wgHandheldForIPhone ) {
3587 $mediaAliases = array(
3588 'screen' => 'screen and (min-device-width: 481px)',
3589 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3590 );
3591
3592 if( isset( $mediaAliases[$media] ) ) {
3593 $media = $mediaAliases[$media];
3594 }
3595 }
3596
3597 return $media;
3598 }
3599
3600 /**
3601 * Add a wikitext-formatted message to the output.
3602 * This is equivalent to:
3603 *
3604 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3605 */
3606 public function addWikiMsg( /*...*/ ) {
3607 $args = func_get_args();
3608 $name = array_shift( $args );
3609 $this->addWikiMsgArray( $name, $args );
3610 }
3611
3612 /**
3613 * Add a wikitext-formatted message to the output.
3614 * Like addWikiMsg() except the parameters are taken as an array
3615 * instead of a variable argument list.
3616 *
3617 * @param $name string
3618 * @param $args array
3619 */
3620 public function addWikiMsgArray( $name, $args ) {
3621 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3622 }
3623
3624 /**
3625 * This function takes a number of message/argument specifications, wraps them in
3626 * some overall structure, and then parses the result and adds it to the output.
3627 *
3628 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3629 * on. The subsequent arguments may either be strings, in which case they are the
3630 * message names, or arrays, in which case the first element is the message name,
3631 * and subsequent elements are the parameters to that message.
3632 *
3633 * Don't use this for messages that are not in users interface language.
3634 *
3635 * For example:
3636 *
3637 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3638 *
3639 * Is equivalent to:
3640 *
3641 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3642 *
3643 * The newline after opening div is needed in some wikitext. See bug 19226.
3644 *
3645 * @param $wrap string
3646 */
3647 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3648 $msgSpecs = func_get_args();
3649 array_shift( $msgSpecs );
3650 $msgSpecs = array_values( $msgSpecs );
3651 $s = $wrap;
3652 foreach ( $msgSpecs as $n => $spec ) {
3653 if ( is_array( $spec ) ) {
3654 $args = $spec;
3655 $name = array_shift( $args );
3656 if ( isset( $args['options'] ) ) {
3657 unset( $args['options'] );
3658 wfDeprecated(
3659 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3660 '1.20'
3661 );
3662 }
3663 } else {
3664 $args = array();
3665 $name = $spec;
3666 }
3667 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3668 }
3669 $this->addWikiText( $s );
3670 }
3671
3672 /**
3673 * Include jQuery core. Use this to avoid loading it multiple times
3674 * before we get a usable script loader.
3675 *
3676 * @param $modules Array: list of jQuery modules which should be loaded
3677 * @return Array: the list of modules which were not loaded.
3678 * @since 1.16
3679 * @deprecated since 1.17
3680 */
3681 public function includeJQuery( $modules = array() ) {
3682 return array();
3683 }
3684
3685 }