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