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