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