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