Merge "Fix SpecialPageFactory list handling"
[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 * and optionally show the source of the page that the user
2419 * was trying to edit. Should only be called (for this
2420 * purpose) after wfReadOnly() has returned true.
2421 *
2422 * For historical reasons, this function is _also_ used to
2423 * show the error message when a user tries to edit a page
2424 * they are not allowed to edit. (Unless it's because they're
2425 * blocked, then we show blockedPage() instead.) In this
2426 * case, the second parameter should be set to true and a list
2427 * of reasons supplied as the third parameter.
2428 *
2429 * @todo Needs to be split into multiple functions.
2430 *
2431 * @param string $source Source code to show (or null).
2432 * @param bool $protected Is this a permissions error?
2433 * @param array $reasons List of reasons for this error, as returned by
2434 * Title::getUserPermissionsErrors().
2435 * @param string $action Action that was denied or null if unknown
2436 * @throws ReadOnlyError
2437 */
2438 public function readOnlyPage( $source = null, $protected = false,
2439 array $reasons = array(), $action = null
2440 ) {
2441 $this->setRobotPolicy( 'noindex,nofollow' );
2442 $this->setArticleRelated( false );
2443
2444 // If no reason is given, just supply a default "I can't let you do
2445 // that, Dave" message. Should only occur if called by legacy code.
2446 if ( $protected && empty( $reasons ) ) {
2447 $reasons[] = array( 'badaccess-group0' );
2448 }
2449
2450 if ( !empty( $reasons ) ) {
2451 // Permissions error
2452 if ( $source ) {
2453 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2454 $this->addBacklinkSubtitle( $this->getTitle() );
2455 } else {
2456 $this->setPageTitle( $this->msg( 'badaccess' ) );
2457 }
2458 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2459 } else {
2460 // Wiki is read only
2461 throw new ReadOnlyError;
2462 }
2463
2464 // Show source, if supplied
2465 if ( is_string( $source ) ) {
2466 $this->addWikiMsg( 'viewsourcetext' );
2467
2468 $pageLang = $this->getTitle()->getPageLanguage();
2469 $params = array(
2470 'id' => 'wpTextbox1',
2471 'name' => 'wpTextbox1',
2472 'cols' => $this->getUser()->getOption( 'cols' ),
2473 'rows' => $this->getUser()->getOption( 'rows' ),
2474 'readonly' => 'readonly',
2475 'lang' => $pageLang->getHtmlCode(),
2476 'dir' => $pageLang->getDir(),
2477 );
2478 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2479
2480 // Show templates used by this article
2481 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2482 $this->addHTML( "<div class='templatesUsed'>
2483 $templates
2484 </div>
2485 " );
2486 }
2487
2488 # If the title doesn't exist, it's fairly pointless to print a return
2489 # link to it. After all, you just tried editing it and couldn't, so
2490 # what's there to do there?
2491 if ( $this->getTitle()->exists() ) {
2492 $this->returnToMain( null, $this->getTitle() );
2493 }
2494 }
2495
2496 /**
2497 * Turn off regular page output and return an error response
2498 * for when rate limiting has triggered.
2499 */
2500 public function rateLimited() {
2501 throw new ThrottledError;
2502 }
2503
2504 /**
2505 * Show a warning about slave lag
2506 *
2507 * If the lag is higher than $wgSlaveLagCritical seconds,
2508 * then the warning is a bit more obvious. If the lag is
2509 * lower than $wgSlaveLagWarning, then no warning is shown.
2510 *
2511 * @param int $lag Slave lag
2512 */
2513 public function showLagWarning( $lag ) {
2514 $config = $this->getConfig();
2515 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2516 $message = $lag < $config->get( 'SlaveLagCritical' )
2517 ? 'lag-warn-normal'
2518 : 'lag-warn-high';
2519 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2520 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2521 }
2522 }
2523
2524 public function showFatalError( $message ) {
2525 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2526
2527 $this->addHTML( $message );
2528 }
2529
2530 public function showUnexpectedValueError( $name, $val ) {
2531 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2532 }
2533
2534 public function showFileCopyError( $old, $new ) {
2535 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2536 }
2537
2538 public function showFileRenameError( $old, $new ) {
2539 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2540 }
2541
2542 public function showFileDeleteError( $name ) {
2543 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2544 }
2545
2546 public function showFileNotFoundError( $name ) {
2547 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2548 }
2549
2550 /**
2551 * Add a "return to" link pointing to a specified title
2552 *
2553 * @param Title $title Title to link
2554 * @param array $query Query string parameters
2555 * @param string $text Text of the link (input is not escaped)
2556 * @param array $options Options array to pass to Linker
2557 */
2558 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2559 $link = $this->msg( 'returnto' )->rawParams(
2560 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2561 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2562 }
2563
2564 /**
2565 * Add a "return to" link pointing to a specified title,
2566 * or the title indicated in the request, or else the main page
2567 *
2568 * @param mixed $unused
2569 * @param Title|string $returnto Title or String to return to
2570 * @param string $returntoquery Query string for the return to link
2571 */
2572 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2573 if ( $returnto == null ) {
2574 $returnto = $this->getRequest()->getText( 'returnto' );
2575 }
2576
2577 if ( $returntoquery == null ) {
2578 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2579 }
2580
2581 if ( $returnto === '' ) {
2582 $returnto = Title::newMainPage();
2583 }
2584
2585 if ( is_object( $returnto ) ) {
2586 $titleObj = $returnto;
2587 } else {
2588 $titleObj = Title::newFromText( $returnto );
2589 }
2590 if ( !is_object( $titleObj ) ) {
2591 $titleObj = Title::newMainPage();
2592 }
2593
2594 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2595 }
2596
2597 /**
2598 * @param Skin $sk The given Skin
2599 * @param bool $includeStyle Unused
2600 * @return string The doctype, opening "<html>", and head element.
2601 */
2602 public function headElement( Skin $sk, $includeStyle = true ) {
2603 global $wgContLang;
2604
2605 $userdir = $this->getLanguage()->getDir();
2606 $sitedir = $wgContLang->getDir();
2607
2608 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2609
2610 if ( $this->getHTMLTitle() == '' ) {
2611 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2612 }
2613
2614 $openHead = Html::openElement( 'head' );
2615 if ( $openHead ) {
2616 # Don't bother with the newline if $head == ''
2617 $ret .= "$openHead\n";
2618 }
2619
2620 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2621 // Add <meta charset="UTF-8">
2622 // This should be before <title> since it defines the charset used by
2623 // text including the text inside <title>.
2624 // The spec recommends defining XHTML5's charset using the XML declaration
2625 // instead of meta.
2626 // Our XML declaration is output by Html::htmlHeader.
2627 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2628 // http://www.whatwg.org/html/semantics.html#charset
2629 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2630 }
2631
2632 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2633
2634 foreach ( $this->getHeadLinksArray() as $item ) {
2635 $ret .= $item . "\n";
2636 }
2637
2638 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2639 $ret .= $this->buildCssLinks();
2640
2641 $ret .= $this->getHeadScripts() . "\n";
2642
2643 foreach ( $this->mHeadItems as $item ) {
2644 $ret .= $item . "\n";
2645 }
2646
2647 $closeHead = Html::closeElement( 'head' );
2648 if ( $closeHead ) {
2649 $ret .= "$closeHead\n";
2650 }
2651
2652 $bodyClasses = array();
2653 $bodyClasses[] = 'mediawiki';
2654
2655 # Classes for LTR/RTL directionality support
2656 $bodyClasses[] = $userdir;
2657 $bodyClasses[] = "sitedir-$sitedir";
2658
2659 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2660 # A <body> class is probably not the best way to do this . . .
2661 $bodyClasses[] = 'capitalize-all-nouns';
2662 }
2663
2664 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2665 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2666 $bodyClasses[] =
2667 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2668
2669 $bodyAttrs = array();
2670 // While the implode() is not strictly needed, it's used for backwards compatibility
2671 // (this used to be built as a string and hooks likely still expect that).
2672 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2673
2674 // Allow skins and extensions to add body attributes they need
2675 $sk->addToBodyAttributes( $this, $bodyAttrs );
2676 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2677
2678 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2679
2680 return $ret;
2681 }
2682
2683 /**
2684 * Get a ResourceLoader object associated with this OutputPage
2685 *
2686 * @return ResourceLoader
2687 */
2688 public function getResourceLoader() {
2689 if ( is_null( $this->mResourceLoader ) ) {
2690 $this->mResourceLoader = new ResourceLoader( $this->getConfig() );
2691 }
2692 return $this->mResourceLoader;
2693 }
2694
2695 /**
2696 * @todo Document
2697 * @param array|string $modules One or more module names
2698 * @param string $only ResourceLoaderModule TYPE_ class constant
2699 * @param bool $useESI
2700 * @param array $extraQuery Array with extra query parameters to add to each
2701 * request. array( param => value ).
2702 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2703 * call rather than a "<script src='...'>" tag.
2704 * @return string The html "<script>", "<link>" and "<style>" tags
2705 */
2706 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2707 array $extraQuery = array(), $loadCall = false
2708 ) {
2709 $modules = (array)$modules;
2710
2711 $links = array(
2712 'html' => '',
2713 'states' => array(),
2714 );
2715
2716 if ( !count( $modules ) ) {
2717 return $links;
2718 }
2719
2720 if ( count( $modules ) > 1 ) {
2721 // Remove duplicate module requests
2722 $modules = array_unique( $modules );
2723 // Sort module names so requests are more uniform
2724 sort( $modules );
2725
2726 if ( ResourceLoader::inDebugMode() ) {
2727 // Recursively call us for every item
2728 foreach ( $modules as $name ) {
2729 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2730 $links['html'] .= $link['html'];
2731 $links['states'] += $link['states'];
2732 }
2733 return $links;
2734 }
2735 }
2736
2737 if ( !is_null( $this->mTarget ) ) {
2738 $extraQuery['target'] = $this->mTarget;
2739 }
2740
2741 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2742 $sortedModules = array();
2743 $resourceLoader = $this->getResourceLoader();
2744 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2745 foreach ( $modules as $name ) {
2746 $module = $resourceLoader->getModule( $name );
2747 # Check that we're allowed to include this module on this page
2748 if ( !$module
2749 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2750 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2751 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2752 && $only == ResourceLoaderModule::TYPE_STYLES )
2753 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2754 && $only == ResourceLoaderModule::TYPE_COMBINED )
2755 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2756 ) {
2757 continue;
2758 }
2759
2760 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2761 }
2762
2763 foreach ( $sortedModules as $source => $groups ) {
2764 foreach ( $groups as $group => $grpModules ) {
2765 // Special handling for user-specific groups
2766 $user = null;
2767 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2768 $user = $this->getUser()->getName();
2769 }
2770
2771 // Create a fake request based on the one we are about to make so modules return
2772 // correct timestamp and emptiness data
2773 $query = ResourceLoader::makeLoaderQuery(
2774 array(), // modules; not determined yet
2775 $this->getLanguage()->getCode(),
2776 $this->getSkin()->getSkinName(),
2777 $user,
2778 null, // version; not determined yet
2779 ResourceLoader::inDebugMode(),
2780 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2781 $this->isPrintable(),
2782 $this->getRequest()->getBool( 'handheld' ),
2783 $extraQuery
2784 );
2785 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2786
2787 // Extract modules that know they're empty and see if we have one or more
2788 // raw modules
2789 $isRaw = false;
2790 foreach ( $grpModules as $key => $module ) {
2791 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2792 // If we're only getting the styles, we don't need to do anything for empty modules.
2793 if ( $module->isKnownEmpty( $context ) ) {
2794 unset( $grpModules[$key] );
2795 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2796 $links['states'][$key] = 'ready';
2797 }
2798 }
2799
2800 $isRaw |= $module->isRaw();
2801 }
2802
2803 // If there are no non-empty modules, skip this group
2804 if ( count( $grpModules ) === 0 ) {
2805 continue;
2806 }
2807
2808 // Inline private modules. These can't be loaded through load.php for security
2809 // reasons, see bug 34907. Note that these modules should be loaded from
2810 // getHeadScripts() before the first loader call. Otherwise other modules can't
2811 // properly use them as dependencies (bug 30914)
2812 if ( $group === 'private' ) {
2813 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2814 $links['html'] .= Html::inlineStyle(
2815 $resourceLoader->makeModuleResponse( $context, $grpModules )
2816 );
2817 } else {
2818 $links['html'] .= Html::inlineScript(
2819 ResourceLoader::makeLoaderConditionalScript(
2820 $resourceLoader->makeModuleResponse( $context, $grpModules )
2821 )
2822 );
2823 }
2824 $links['html'] .= "\n";
2825 continue;
2826 }
2827
2828 // Special handling for the user group; because users might change their stuff
2829 // on-wiki like user pages, or user preferences; we need to find the highest
2830 // timestamp of these user-changeable modules so we can ensure cache misses on change
2831 // This should NOT be done for the site group (bug 27564) because anons get that too
2832 // and we shouldn't be putting timestamps in Squid-cached HTML
2833 $version = null;
2834 if ( $group === 'user' ) {
2835 // Get the maximum timestamp
2836 $timestamp = 1;
2837 foreach ( $grpModules as $module ) {
2838 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2839 }
2840 // Add a version parameter so cache will break when things change
2841 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2842 }
2843
2844 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2845 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2846 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2847
2848 if ( $useESI && $resourceLoaderUseESI ) {
2849 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2850 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2851 $link = Html::inlineStyle( $esi );
2852 } else {
2853 $link = Html::inlineScript( $esi );
2854 }
2855 } else {
2856 // Automatically select style/script elements
2857 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2858 $link = Html::linkedStyle( $url );
2859 } elseif ( $loadCall ) {
2860 $link = Html::inlineScript(
2861 ResourceLoader::makeLoaderConditionalScript(
2862 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2863 )
2864 );
2865 } else {
2866 $link = Html::linkedScript( $url );
2867 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2868 // Wrap only=script requests in a conditional as browsers not supported
2869 // by the startup module would unconditionally execute this module.
2870 // Otherwise users will get "ReferenceError: mw is undefined" or
2871 // "jQuery is undefined" from e.g. a "site" module.
2872 $link = Html::inlineScript(
2873 ResourceLoader::makeLoaderConditionalScript(
2874 Xml::encodeJsCall( 'document.write', array( $link ) )
2875 )
2876 );
2877 }
2878
2879 // For modules requested directly in the html via <link> or <script>,
2880 // tell mw.loader they are being loading to prevent duplicate requests.
2881 foreach ( $grpModules as $key => $module ) {
2882 // Don't output state=loading for the startup module..
2883 if ( $key !== 'startup' ) {
2884 $links['states'][$key] = 'loading';
2885 }
2886 }
2887 }
2888 }
2889
2890 if ( $group == 'noscript' ) {
2891 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2892 } else {
2893 $links['html'] .= $link . "\n";
2894 }
2895 }
2896 }
2897
2898 return $links;
2899 }
2900
2901 /**
2902 * Build html output from an array of links from makeResourceLoaderLink.
2903 * @param array $links
2904 * @return string HTML
2905 */
2906 protected static function getHtmlFromLoaderLinks( array $links ) {
2907 $html = '';
2908 $states = array();
2909 foreach ( $links as $link ) {
2910 if ( !is_array( $link ) ) {
2911 $html .= $link;
2912 } else {
2913 $html .= $link['html'];
2914 $states += $link['states'];
2915 }
2916 }
2917
2918 if ( count( $states ) ) {
2919 $html = Html::inlineScript(
2920 ResourceLoader::makeLoaderConditionalScript(
2921 ResourceLoader::makeLoaderStateScript( $states )
2922 )
2923 ) . "\n" . $html;
2924 }
2925
2926 return $html;
2927 }
2928
2929 /**
2930 * JS stuff to put in the "<head>". This is the startup module, config
2931 * vars and modules marked with position 'top'
2932 *
2933 * @return string HTML fragment
2934 */
2935 function getHeadScripts() {
2936 // Startup - this will immediately load jquery and mediawiki modules
2937 $links = array();
2938 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2939
2940 // Load config before anything else
2941 $links[] = Html::inlineScript(
2942 ResourceLoader::makeLoaderConditionalScript(
2943 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2944 )
2945 );
2946
2947 // Load embeddable private modules before any loader links
2948 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2949 // in mw.loader.implement() calls and deferred until mw.user is available
2950 $embedScripts = array( 'user.options', 'user.tokens' );
2951 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2952
2953 // Scripts and messages "only" requests marked for top inclusion
2954 // Messages should go first
2955 $links[] = $this->makeResourceLoaderLink(
2956 $this->getModuleMessages( true, 'top' ),
2957 ResourceLoaderModule::TYPE_MESSAGES
2958 );
2959 $links[] = $this->makeResourceLoaderLink(
2960 $this->getModuleScripts( true, 'top' ),
2961 ResourceLoaderModule::TYPE_SCRIPTS
2962 );
2963
2964 // Modules requests - let the client calculate dependencies and batch requests as it likes
2965 // Only load modules that have marked themselves for loading at the top
2966 $modules = $this->getModules( true, 'top' );
2967 if ( $modules ) {
2968 $links[] = Html::inlineScript(
2969 ResourceLoader::makeLoaderConditionalScript(
2970 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2971 )
2972 );
2973 }
2974
2975 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2976 $links[] = $this->getScriptsForBottomQueue( true );
2977 }
2978
2979 return self::getHtmlFromLoaderLinks( $links );
2980 }
2981
2982 /**
2983 * JS stuff to put at the 'bottom', which can either be the bottom of the
2984 * "<body>" or the bottom of the "<head>" depending on
2985 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2986 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2987 * and user JS.
2988 *
2989 * @param bool $inHead If true, this HTML goes into the "<head>",
2990 * if false it goes into the "<body>".
2991 * @return string
2992 */
2993 function getScriptsForBottomQueue( $inHead ) {
2994 // Scripts and messages "only" requests marked for bottom inclusion
2995 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2996 // Messages should go first
2997 $links = array();
2998 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2999 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
3000 /* $loadCall = */ $inHead
3001 );
3002 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3003 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
3004 /* $loadCall = */ $inHead
3005 );
3006
3007 // Modules requests - let the client calculate dependencies and batch requests as it likes
3008 // Only load modules that have marked themselves for loading at the bottom
3009 $modules = $this->getModules( true, 'bottom' );
3010 if ( $modules ) {
3011 $links[] = Html::inlineScript(
3012 ResourceLoader::makeLoaderConditionalScript(
3013 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3014 )
3015 );
3016 }
3017
3018 // Legacy Scripts
3019 $links[] = "\n" . $this->mScripts;
3020
3021 // Add site JS if enabled
3022 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
3023 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3024 );
3025
3026 // Add user JS if enabled
3027 if ( $this->getConfig()->get( 'AllowUserJs' )
3028 && $this->getUser()->isLoggedIn()
3029 && $this->getTitle()
3030 && $this->getTitle()->isJsSubpage()
3031 && $this->userCanPreview()
3032 ) {
3033 # XXX: additional security check/prompt?
3034 // We're on a preview of a JS subpage
3035 // Exclude this page from the user module in case it's in there (bug 26283)
3036 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3037 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3038 );
3039 // Load the previewed JS
3040 $links[] = Html::inlineScript( "\n"
3041 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3042
3043 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3044 // asynchronously and may arrive *after* the inline script here. So the previewed code
3045 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3046 } else {
3047 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3048 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3049 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3050 );
3051 }
3052
3053 // Group JS is only enabled if site JS is enabled.
3054 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3055 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3056 );
3057
3058 return self::getHtmlFromLoaderLinks( $links );
3059 }
3060
3061 /**
3062 * JS stuff to put at the bottom of the "<body>"
3063 * @return string
3064 */
3065 function getBottomScripts() {
3066 // Optimise jQuery ready event cross-browser.
3067 // This also enforces $.isReady to be true at </body> which fixes the
3068 // mw.loader bug in Firefox with using document.write between </body>
3069 // and the DOMContentReady event (bug 47457).
3070 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
3071
3072 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3073 $html .= $this->getScriptsForBottomQueue( false );
3074 }
3075
3076 return $html;
3077 }
3078
3079 /**
3080 * Get the javascript config vars to include on this page
3081 *
3082 * @return array Array of javascript config vars
3083 * @since 1.23
3084 */
3085 public function getJsConfigVars() {
3086 return $this->mJsConfigVars;
3087 }
3088
3089 /**
3090 * Add one or more variables to be set in mw.config in JavaScript
3091 *
3092 * @param string|array $keys Key or array of key/value pairs
3093 * @param mixed $value [optional] Value of the configuration variable
3094 */
3095 public function addJsConfigVars( $keys, $value = null ) {
3096 if ( is_array( $keys ) ) {
3097 foreach ( $keys as $key => $value ) {
3098 $this->mJsConfigVars[$key] = $value;
3099 }
3100 return;
3101 }
3102
3103 $this->mJsConfigVars[$keys] = $value;
3104 }
3105
3106 /**
3107 * Get an array containing the variables to be set in mw.config in JavaScript.
3108 *
3109 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3110 * - in other words, page-independent/site-wide variables (without state).
3111 * You will only be adding bloat to the html page and causing page caches to
3112 * have to be purged on configuration changes.
3113 * @return array
3114 */
3115 private function getJSVars() {
3116 global $wgContLang;
3117
3118 $curRevisionId = 0;
3119 $articleId = 0;
3120 $canonicalSpecialPageName = false; # bug 21115
3121
3122 $title = $this->getTitle();
3123 $ns = $title->getNamespace();
3124 $canonicalNamespace = MWNamespace::exists( $ns )
3125 ? MWNamespace::getCanonicalName( $ns )
3126 : $title->getNsText();
3127
3128 $sk = $this->getSkin();
3129 // Get the relevant title so that AJAX features can use the correct page name
3130 // when making API requests from certain special pages (bug 34972).
3131 $relevantTitle = $sk->getRelevantTitle();
3132 $relevantUser = $sk->getRelevantUser();
3133
3134 if ( $ns == NS_SPECIAL ) {
3135 list( $canonicalSpecialPageName, /*...*/ ) =
3136 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3137 } elseif ( $this->canUseWikiPage() ) {
3138 $wikiPage = $this->getWikiPage();
3139 $curRevisionId = $wikiPage->getLatest();
3140 $articleId = $wikiPage->getId();
3141 }
3142
3143 $lang = $title->getPageLanguage();
3144
3145 // Pre-process information
3146 $separatorTransTable = $lang->separatorTransformTable();
3147 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3148 $compactSeparatorTransTable = array(
3149 implode( "\t", array_keys( $separatorTransTable ) ),
3150 implode( "\t", $separatorTransTable ),
3151 );
3152 $digitTransTable = $lang->digitTransformTable();
3153 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3154 $compactDigitTransTable = array(
3155 implode( "\t", array_keys( $digitTransTable ) ),
3156 implode( "\t", $digitTransTable ),
3157 );
3158
3159 $user = $this->getUser();
3160
3161 $vars = array(
3162 'wgCanonicalNamespace' => $canonicalNamespace,
3163 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3164 'wgNamespaceNumber' => $title->getNamespace(),
3165 'wgPageName' => $title->getPrefixedDBkey(),
3166 'wgTitle' => $title->getText(),
3167 'wgCurRevisionId' => $curRevisionId,
3168 'wgRevisionId' => (int)$this->getRevisionId(),
3169 'wgArticleId' => $articleId,
3170 'wgIsArticle' => $this->isArticle(),
3171 'wgIsRedirect' => $title->isRedirect(),
3172 'wgAction' => Action::getActionName( $this->getContext() ),
3173 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3174 'wgUserGroups' => $user->getEffectiveGroups(),
3175 'wgCategories' => $this->getCategories(),
3176 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3177 'wgPageContentLanguage' => $lang->getCode(),
3178 'wgPageContentModel' => $title->getContentModel(),
3179 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3180 'wgDigitTransformTable' => $compactDigitTransTable,
3181 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3182 'wgMonthNames' => $lang->getMonthNamesArray(),
3183 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3184 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3185 );
3186
3187 if ( $user->isLoggedIn() ) {
3188 $vars['wgUserId'] = $user->getId();
3189 $vars['wgUserEditCount'] = $user->getEditCount();
3190 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3191 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3192 // Get the revision ID of the oldest new message on the user's talk
3193 // page. This can be used for constructing new message alerts on
3194 // the client side.
3195 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3196 }
3197
3198 if ( $wgContLang->hasVariants() ) {
3199 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3200 }
3201 // Same test as SkinTemplate
3202 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3203 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3204
3205 foreach ( $title->getRestrictionTypes() as $type ) {
3206 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3207 }
3208
3209 if ( $title->isMainPage() ) {
3210 $vars['wgIsMainPage'] = true;
3211 }
3212
3213 if ( $this->mRedirectedFrom ) {
3214 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3215 }
3216
3217 if ( $relevantUser ) {
3218 $vars['wgRelevantUserName'] = $relevantUser->getName();
3219 }
3220
3221 // Allow extensions to add their custom variables to the mw.config map.
3222 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3223 // page-dependant but site-wide (without state).
3224 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3225 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3226
3227 // Merge in variables from addJsConfigVars last
3228 return array_merge( $vars, $this->getJsConfigVars() );
3229 }
3230
3231 /**
3232 * To make it harder for someone to slip a user a fake
3233 * user-JavaScript or user-CSS preview, a random token
3234 * is associated with the login session. If it's not
3235 * passed back with the preview request, we won't render
3236 * the code.
3237 *
3238 * @return bool
3239 */
3240 public function userCanPreview() {
3241 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3242 || !$this->getRequest()->wasPosted()
3243 || !$this->getUser()->matchEditToken(
3244 $this->getRequest()->getVal( 'wpEditToken' ) )
3245 ) {
3246 return false;
3247 }
3248 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3249 return false;
3250 }
3251
3252 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3253 }
3254
3255 /**
3256 * @return array Array in format "link name or number => 'link html'".
3257 */
3258 public function getHeadLinksArray() {
3259 global $wgVersion;
3260
3261 $tags = array();
3262 $config = $this->getConfig();
3263
3264 $canonicalUrl = $this->mCanonicalUrl;
3265
3266 $tags['meta-generator'] = Html::element( 'meta', array(
3267 'name' => 'generator',
3268 'content' => "MediaWiki $wgVersion",
3269 ) );
3270
3271 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3272 if ( $p !== 'index,follow' ) {
3273 // http://www.robotstxt.org/wc/meta-user.html
3274 // Only show if it's different from the default robots policy
3275 $tags['meta-robots'] = Html::element( 'meta', array(
3276 'name' => 'robots',
3277 'content' => $p,
3278 ) );
3279 }
3280
3281 foreach ( $this->mMetatags as $tag ) {
3282 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3283 $a = 'http-equiv';
3284 $tag[0] = substr( $tag[0], 5 );
3285 } else {
3286 $a = 'name';
3287 }
3288 $tagName = "meta-{$tag[0]}";
3289 if ( isset( $tags[$tagName] ) ) {
3290 $tagName .= $tag[1];
3291 }
3292 $tags[$tagName] = Html::element( 'meta',
3293 array(
3294 $a => $tag[0],
3295 'content' => $tag[1]
3296 )
3297 );
3298 }
3299
3300 foreach ( $this->mLinktags as $tag ) {
3301 $tags[] = Html::element( 'link', $tag );
3302 }
3303
3304 # Universal edit button
3305 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3306 $user = $this->getUser();
3307 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3308 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3309 // Original UniversalEditButton
3310 $msg = $this->msg( 'edit' )->text();
3311 $tags['universal-edit-button'] = Html::element( 'link', array(
3312 'rel' => 'alternate',
3313 'type' => 'application/x-wiki',
3314 'title' => $msg,
3315 'href' => $this->getTitle()->getEditURL(),
3316 ) );
3317 // Alternate edit link
3318 $tags['alternative-edit'] = Html::element( 'link', array(
3319 'rel' => 'edit',
3320 'title' => $msg,
3321 'href' => $this->getTitle()->getEditURL(),
3322 ) );
3323 }
3324 }
3325
3326 # Generally the order of the favicon and apple-touch-icon links
3327 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3328 # uses whichever one appears later in the HTML source. Make sure
3329 # apple-touch-icon is specified first to avoid this.
3330 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3331 $tags['apple-touch-icon'] = Html::element( 'link', array(
3332 'rel' => 'apple-touch-icon',
3333 'href' => $config->get( 'AppleTouchIcon' )
3334 ) );
3335 }
3336
3337 if ( $config->get( 'Favicon' ) !== false ) {
3338 $tags['favicon'] = Html::element( 'link', array(
3339 'rel' => 'shortcut icon',
3340 'href' => $config->get( 'Favicon' )
3341 ) );
3342 }
3343
3344 # OpenSearch description link
3345 $tags['opensearch'] = Html::element( 'link', array(
3346 'rel' => 'search',
3347 'type' => 'application/opensearchdescription+xml',
3348 'href' => wfScript( 'opensearch_desc' ),
3349 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3350 ) );
3351
3352 if ( $config->get( 'EnableAPI' ) ) {
3353 # Real Simple Discovery link, provides auto-discovery information
3354 # for the MediaWiki API (and potentially additional custom API
3355 # support such as WordPress or Twitter-compatible APIs for a
3356 # blogging extension, etc)
3357 $tags['rsd'] = Html::element( 'link', array(
3358 'rel' => 'EditURI',
3359 'type' => 'application/rsd+xml',
3360 // Output a protocol-relative URL here if $wgServer is protocol-relative
3361 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3362 'href' => wfExpandUrl( wfAppendQuery(
3363 wfScript( 'api' ),
3364 array( 'action' => 'rsd' ) ),
3365 PROTO_RELATIVE
3366 ),
3367 ) );
3368 }
3369
3370 # Language variants
3371 if ( !$config->get( 'DisableLangConversion' ) ) {
3372 $lang = $this->getTitle()->getPageLanguage();
3373 if ( $lang->hasVariants() ) {
3374 $variants = $lang->getVariants();
3375 foreach ( $variants as $_v ) {
3376 $tags["variant-$_v"] = Html::element( 'link', array(
3377 'rel' => 'alternate',
3378 'hreflang' => wfBCP47( $_v ),
3379 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3380 );
3381 }
3382 }
3383 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3384 $tags["variant-x-default"] = Html::element( 'link', array(
3385 'rel' => 'alternate',
3386 'hreflang' => 'x-default',
3387 'href' => $this->getTitle()->getLocalURL() ) );
3388 }
3389
3390 # Copyright
3391 $copyright = '';
3392 if ( $config->get( 'RightsPage' ) ) {
3393 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3394
3395 if ( $copy ) {
3396 $copyright = $copy->getLocalURL();
3397 }
3398 }
3399
3400 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3401 $copyright = $config->get( 'RightsUrl' );
3402 }
3403
3404 if ( $copyright ) {
3405 $tags['copyright'] = Html::element( 'link', array(
3406 'rel' => 'copyright',
3407 'href' => $copyright )
3408 );
3409 }
3410
3411 # Feeds
3412 if ( $config->get( 'Feed' ) ) {
3413 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3414 # Use the page name for the title. In principle, this could
3415 # lead to issues with having the same name for different feeds
3416 # corresponding to the same page, but we can't avoid that at
3417 # this low a level.
3418
3419 $tags[] = $this->feedLink(
3420 $format,
3421 $link,
3422 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3423 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3424 );
3425 }
3426
3427 # Recent changes feed should appear on every page (except recentchanges,
3428 # that would be redundant). Put it after the per-page feed to avoid
3429 # changing existing behavior. It's still available, probably via a
3430 # menu in your browser. Some sites might have a different feed they'd
3431 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3432 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3433 # If so, use it instead.
3434 $sitename = $config->get( 'Sitename' );
3435 if ( $config->get( 'OverrideSiteFeed' ) ) {
3436 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3437 // Note, this->feedLink escapes the url.
3438 $tags[] = $this->feedLink(
3439 $type,
3440 $feedUrl,
3441 $this->msg( "site-{$type}-feed", $sitename )->text()
3442 );
3443 }
3444 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3445 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3446 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3447 $tags[] = $this->feedLink(
3448 $format,
3449 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3450 # For grep: 'site-rss-feed', 'site-atom-feed'
3451 $this->msg( "site-{$format}-feed", $sitename )->text()
3452 );
3453 }
3454 }
3455 }
3456
3457 # Canonical URL
3458 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3459 if ( $canonicalUrl !== false ) {
3460 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3461 } else {
3462 $reqUrl = $this->getRequest()->getRequestURL();
3463 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3464 }
3465 }
3466 if ( $canonicalUrl !== false ) {
3467 $tags[] = Html::element( 'link', array(
3468 'rel' => 'canonical',
3469 'href' => $canonicalUrl
3470 ) );
3471 }
3472
3473 return $tags;
3474 }
3475
3476 /**
3477 * @return string HTML tag links to be put in the header.
3478 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3479 * OutputPage::getHeadLinksArray directly.
3480 */
3481 public function getHeadLinks() {
3482 wfDeprecated( __METHOD__, '1.24' );
3483 return implode( "\n", $this->getHeadLinksArray() );
3484 }
3485
3486 /**
3487 * Generate a "<link rel/>" for a feed.
3488 *
3489 * @param string $type Feed type
3490 * @param string $url URL to the feed
3491 * @param string $text Value of the "title" attribute
3492 * @return string HTML fragment
3493 */
3494 private function feedLink( $type, $url, $text ) {
3495 return Html::element( 'link', array(
3496 'rel' => 'alternate',
3497 'type' => "application/$type+xml",
3498 'title' => $text,
3499 'href' => $url )
3500 );
3501 }
3502
3503 /**
3504 * Add a local or specified stylesheet, with the given media options.
3505 * Meant primarily for internal use...
3506 *
3507 * @param string $style URL to the file
3508 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3509 * @param string $condition For IE conditional comments, specifying an IE version
3510 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3511 */
3512 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3513 $options = array();
3514 // Even though we expect the media type to be lowercase, but here we
3515 // force it to lowercase to be safe.
3516 if ( $media ) {
3517 $options['media'] = $media;
3518 }
3519 if ( $condition ) {
3520 $options['condition'] = $condition;
3521 }
3522 if ( $dir ) {
3523 $options['dir'] = $dir;
3524 }
3525 $this->styles[$style] = $options;
3526 }
3527
3528 /**
3529 * Adds inline CSS styles
3530 * @param mixed $style_css Inline CSS
3531 * @param string $flip Set to 'flip' to flip the CSS if needed
3532 */
3533 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3534 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3535 # If wanted, and the interface is right-to-left, flip the CSS
3536 $style_css = CSSJanus::transform( $style_css, true, false );
3537 }
3538 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3539 }
3540
3541 /**
3542 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3543 * These will be applied to various media & IE conditionals.
3544 *
3545 * @return string
3546 */
3547 public function buildCssLinks() {
3548 global $wgContLang;
3549
3550 $this->getSkin()->setupSkinUserCss( $this );
3551
3552 // Add ResourceLoader styles
3553 // Split the styles into these groups
3554 $styles = array(
3555 'other' => array(),
3556 'user' => array(),
3557 'site' => array(),
3558 'private' => array(),
3559 'noscript' => array()
3560 );
3561 $links = array();
3562 $otherTags = ''; // Tags to append after the normal <link> tags
3563 $resourceLoader = $this->getResourceLoader();
3564
3565 $moduleStyles = $this->getModuleStyles();
3566
3567 // Per-site custom styles
3568 $moduleStyles[] = 'site';
3569 $moduleStyles[] = 'noscript';
3570 $moduleStyles[] = 'user.groups';
3571
3572 // Per-user custom styles
3573 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3574 // We're on a preview of a CSS subpage
3575 // Exclude this page from the user module in case it's in there (bug 26283)
3576 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3577 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3578 );
3579 $otherTags .= $link['html'];
3580
3581 // Load the previewed CSS
3582 // If needed, Janus it first. This is user-supplied CSS, so it's
3583 // assumed to be right for the content language directionality.
3584 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3585 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3586 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3587 }
3588 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3589 } else {
3590 // Load the user styles normally
3591 $moduleStyles[] = 'user';
3592 }
3593
3594 // Per-user preference styles
3595 $moduleStyles[] = 'user.cssprefs';
3596
3597 foreach ( $moduleStyles as $name ) {
3598 $module = $resourceLoader->getModule( $name );
3599 if ( !$module ) {
3600 continue;
3601 }
3602 $group = $module->getGroup();
3603 // Modules in groups different than the ones listed on top (see $styles assignment)
3604 // will be placed in the "other" group
3605 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3606 }
3607
3608 // We want site, private and user styles to override dynamically added
3609 // styles from modules, but we want dynamically added styles to override
3610 // statically added styles from other modules. So the order has to be
3611 // other, dynamic, site, private, user. Add statically added styles for
3612 // other modules
3613 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3614 // Add normal styles added through addStyle()/addInlineStyle() here
3615 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3616 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3617 // We use a <meta> tag with a made-up name for this because that's valid HTML
3618 $links[] = Html::element(
3619 'meta',
3620 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3621 ) . "\n";
3622
3623 // Add site, private and user styles
3624 // 'private' at present only contains user.options, so put that before 'user'
3625 // Any future private modules will likely have a similar user-specific character
3626 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3627 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3628 ResourceLoaderModule::TYPE_STYLES
3629 );
3630 }
3631
3632 // Add stuff in $otherTags (previewed user CSS if applicable)
3633 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3634 }
3635
3636 /**
3637 * @return array
3638 */
3639 public function buildCssLinksArray() {
3640 $links = array();
3641
3642 // Add any extension CSS
3643 foreach ( $this->mExtStyles as $url ) {
3644 $this->addStyle( $url );
3645 }
3646 $this->mExtStyles = array();
3647
3648 foreach ( $this->styles as $file => $options ) {
3649 $link = $this->styleLink( $file, $options );
3650 if ( $link ) {
3651 $links[$file] = $link;
3652 }
3653 }
3654 return $links;
3655 }
3656
3657 /**
3658 * Generate \<link\> tags for stylesheets
3659 *
3660 * @param string $style URL to the file
3661 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3662 * @return string HTML fragment
3663 */
3664 protected function styleLink( $style, array $options ) {
3665 if ( isset( $options['dir'] ) ) {
3666 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3667 return '';
3668 }
3669 }
3670
3671 if ( isset( $options['media'] ) ) {
3672 $media = self::transformCssMedia( $options['media'] );
3673 if ( is_null( $media ) ) {
3674 return '';
3675 }
3676 } else {
3677 $media = 'all';
3678 }
3679
3680 if ( substr( $style, 0, 1 ) == '/' ||
3681 substr( $style, 0, 5 ) == 'http:' ||
3682 substr( $style, 0, 6 ) == 'https:' ) {
3683 $url = $style;
3684 } else {
3685 $config = $this->getConfig();
3686 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3687 }
3688
3689 $link = Html::linkedStyle( $url, $media );
3690
3691 if ( isset( $options['condition'] ) ) {
3692 $condition = htmlspecialchars( $options['condition'] );
3693 $link = "<!--[if $condition]>$link<![endif]-->";
3694 }
3695 return $link;
3696 }
3697
3698 /**
3699 * Transform "media" attribute based on request parameters
3700 *
3701 * @param string $media Current value of the "media" attribute
3702 * @return string Modified value of the "media" attribute, or null to skip
3703 * this stylesheet
3704 */
3705 public static function transformCssMedia( $media ) {
3706 global $wgRequest;
3707
3708 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3709 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3710
3711 // Switch in on-screen display for media testing
3712 $switches = array(
3713 'printable' => 'print',
3714 'handheld' => 'handheld',
3715 );
3716 foreach ( $switches as $switch => $targetMedia ) {
3717 if ( $wgRequest->getBool( $switch ) ) {
3718 if ( $media == $targetMedia ) {
3719 $media = '';
3720 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3721 // This regex will not attempt to understand a comma-separated media_query_list
3722 //
3723 // Example supported values for $media:
3724 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3725 // Example NOT supported value for $media:
3726 // '3d-glasses, screen, print and resolution > 90dpi'
3727 //
3728 // If it's a print request, we never want any kind of screen stylesheets
3729 // If it's a handheld request (currently the only other choice with a switch),
3730 // we don't want simple 'screen' but we might want screen queries that
3731 // have a max-width or something, so we'll pass all others on and let the
3732 // client do the query.
3733 if ( $targetMedia == 'print' || $media == 'screen' ) {
3734 return null;
3735 }
3736 }
3737 }
3738 }
3739
3740 return $media;
3741 }
3742
3743 /**
3744 * Add a wikitext-formatted message to the output.
3745 * This is equivalent to:
3746 *
3747 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3748 */
3749 public function addWikiMsg( /*...*/ ) {
3750 $args = func_get_args();
3751 $name = array_shift( $args );
3752 $this->addWikiMsgArray( $name, $args );
3753 }
3754
3755 /**
3756 * Add a wikitext-formatted message to the output.
3757 * Like addWikiMsg() except the parameters are taken as an array
3758 * instead of a variable argument list.
3759 *
3760 * @param string $name
3761 * @param array $args
3762 */
3763 public function addWikiMsgArray( $name, $args ) {
3764 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3765 }
3766
3767 /**
3768 * This function takes a number of message/argument specifications, wraps them in
3769 * some overall structure, and then parses the result and adds it to the output.
3770 *
3771 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3772 * on. The subsequent arguments may either be strings, in which case they are the
3773 * message names, or arrays, in which case the first element is the message name,
3774 * and subsequent elements are the parameters to that message.
3775 *
3776 * Don't use this for messages that are not in users interface language.
3777 *
3778 * For example:
3779 *
3780 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3781 *
3782 * Is equivalent to:
3783 *
3784 * $wgOut->addWikiText( "<div class='error'>\n"
3785 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3786 *
3787 * The newline after opening div is needed in some wikitext. See bug 19226.
3788 *
3789 * @param string $wrap
3790 */
3791 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3792 $msgSpecs = func_get_args();
3793 array_shift( $msgSpecs );
3794 $msgSpecs = array_values( $msgSpecs );
3795 $s = $wrap;
3796 foreach ( $msgSpecs as $n => $spec ) {
3797 if ( is_array( $spec ) ) {
3798 $args = $spec;
3799 $name = array_shift( $args );
3800 if ( isset( $args['options'] ) ) {
3801 unset( $args['options'] );
3802 wfDeprecated(
3803 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3804 '1.20'
3805 );
3806 }
3807 } else {
3808 $args = array();
3809 $name = $spec;
3810 }
3811 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3812 }
3813 $this->addWikiText( $s );
3814 }
3815
3816 /**
3817 * Include jQuery core. Use this to avoid loading it multiple times
3818 * before we get a usable script loader.
3819 *
3820 * @param array $modules List of jQuery modules which should be loaded
3821 * @return array The list of modules which were not loaded.
3822 * @since 1.16
3823 * @deprecated since 1.17
3824 */
3825 public function includeJQuery( array $modules = array() ) {
3826 return array();
3827 }
3828
3829 /**
3830 * Enables/disables TOC, doesn't override __NOTOC__
3831 * @param bool $flag
3832 * @since 1.22
3833 */
3834 public function enableTOC( $flag = true ) {
3835 $this->mEnableTOC = $flag;
3836 }
3837
3838 /**
3839 * @return bool
3840 * @since 1.22
3841 */
3842 public function isTOCEnabled() {
3843 return $this->mEnableTOC;
3844 }
3845
3846 /**
3847 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3848 * @param bool $flag
3849 * @since 1.23
3850 */
3851 public function enableSectionEditLinks( $flag = true ) {
3852 $this->mEnableSectionEditLinks = $flag;
3853 }
3854
3855 /**
3856 * @return bool
3857 * @since 1.23
3858 */
3859 public function sectionEditLinksEnabled() {
3860 return $this->mEnableSectionEditLinks;
3861 }
3862 }