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