Merge "Make "/*@noflip*/ /*@embed*/" annotation work"
[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 // See if $file parameter is an absolute URL or begins with a slash
453 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
454 $path = $file;
455 } else {
456 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
457 }
458 if ( is_null( $version ) ) {
459 $version = $this->getConfig()->get( 'StyleVersion' );
460 }
461 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
462 }
463
464 /**
465 * Add a self-contained script tag with the given contents
466 *
467 * @param string $script JavaScript text, no "<script>" tags
468 */
469 public function addInlineScript( $script ) {
470 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
471 }
472
473 /**
474 * Get all registered JS and CSS tags for the header.
475 *
476 * @return string
477 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
478 */
479 function getScript() {
480 wfDeprecated( __METHOD__, '1.24' );
481 return $this->mScripts . $this->getHeadItems();
482 }
483
484 /**
485 * Filter an array of modules to remove insufficiently trustworthy members, and modules
486 * which are no longer registered (eg a page is cached before an extension is disabled)
487 * @param array $modules
488 * @param string|null $position If not null, only return modules with this position
489 * @param string $type
490 * @return array
491 */
492 protected function filterModules( array $modules, $position = null,
493 $type = ResourceLoaderModule::TYPE_COMBINED
494 ) {
495 $resourceLoader = $this->getResourceLoader();
496 $filteredModules = array();
497 foreach ( $modules as $val ) {
498 $module = $resourceLoader->getModule( $val );
499 if ( $module instanceof ResourceLoaderModule
500 && $module->getOrigin() <= $this->getAllowedModules( $type )
501 && ( is_null( $position ) || $module->getPosition() == $position )
502 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) )
503 ) {
504 $filteredModules[] = $val;
505 }
506 }
507 return $filteredModules;
508 }
509
510 /**
511 * Get the list of modules to include on this page
512 *
513 * @param bool $filter Whether to filter out insufficiently trustworthy modules
514 * @param string|null $position If not null, only return modules with this position
515 * @param string $param
516 * @return array Array of module names
517 */
518 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
519 $modules = array_values( array_unique( $this->$param ) );
520 return $filter
521 ? $this->filterModules( $modules, $position )
522 : $modules;
523 }
524
525 /**
526 * Add one or more modules recognized by the resource loader. Modules added
527 * through this function will be loaded by the resource loader when the
528 * page loads.
529 *
530 * @param string|array $modules Module name (string) or array of module names
531 */
532 public function addModules( $modules ) {
533 $this->mModules = array_merge( $this->mModules, (array)$modules );
534 }
535
536 /**
537 * Get the list of module JS to include on this page
538 *
539 * @param bool $filter
540 * @param string|null $position
541 *
542 * @return array Array of module names
543 */
544 public function getModuleScripts( $filter = false, $position = null ) {
545 return $this->getModules( $filter, $position, 'mModuleScripts' );
546 }
547
548 /**
549 * Add only JS of one or more modules recognized by the resource loader. Module
550 * scripts added through this function will be loaded by the resource loader when
551 * the page loads.
552 *
553 * @param string|array $modules Module name (string) or array of module names
554 */
555 public function addModuleScripts( $modules ) {
556 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
557 }
558
559 /**
560 * Get the list of module CSS to include on this page
561 *
562 * @param bool $filter
563 * @param string|null $position
564 *
565 * @return array Array of module names
566 */
567 public function getModuleStyles( $filter = false, $position = null ) {
568 return $this->getModules( $filter, $position, 'mModuleStyles' );
569 }
570
571 /**
572 * Add only CSS of one or more modules recognized by the resource loader.
573 *
574 * Module styles added through this function will be added using standard link CSS
575 * tags, rather than as a combined Javascript and CSS package. Thus, they will
576 * load when JavaScript is disabled (unless CSS also happens to be disabled).
577 *
578 * @param string|array $modules Module name (string) or array of module names
579 */
580 public function addModuleStyles( $modules ) {
581 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
582 }
583
584 /**
585 * Get the list of module messages to include on this page
586 *
587 * @param bool $filter
588 * @param string|null $position
589 *
590 * @return array Array of module names
591 */
592 public function getModuleMessages( $filter = false, $position = null ) {
593 return $this->getModules( $filter, $position, 'mModuleMessages' );
594 }
595
596 /**
597 * Add only messages of one or more modules recognized by the resource loader.
598 * Module messages added through this function will be loaded by the resource
599 * loader when the page loads.
600 *
601 * @param string|array $modules Module name (string) or array of module names
602 */
603 public function addModuleMessages( $modules ) {
604 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
605 }
606
607 /**
608 * @return null|string ResourceLoader target
609 */
610 public function getTarget() {
611 return $this->mTarget;
612 }
613
614 /**
615 * Sets ResourceLoader target for load.php links. If null, will be omitted
616 *
617 * @param string|null $target
618 */
619 public function setTarget( $target ) {
620 $this->mTarget = $target;
621 }
622
623 /**
624 * Get an array of head items
625 *
626 * @return array
627 */
628 function getHeadItemsArray() {
629 return $this->mHeadItems;
630 }
631
632 /**
633 * Get all header items in a string
634 *
635 * @return string
636 * @deprecated since 1.24 Use OutputPage::headElement or
637 * if absolutely necessary use OutputPage::getHeadItemsArray
638 */
639 function getHeadItems() {
640 wfDeprecated( __METHOD__, '1.24' );
641 $s = '';
642 foreach ( $this->mHeadItems as $item ) {
643 $s .= $item;
644 }
645 return $s;
646 }
647
648 /**
649 * Add or replace an header item to the output
650 *
651 * @param string $name Item name
652 * @param string $value Raw HTML
653 */
654 public function addHeadItem( $name, $value ) {
655 $this->mHeadItems[$name] = $value;
656 }
657
658 /**
659 * Check if the header item $name is already set
660 *
661 * @param string $name Item name
662 * @return bool
663 */
664 public function hasHeadItem( $name ) {
665 return isset( $this->mHeadItems[$name] );
666 }
667
668 /**
669 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
670 *
671 * @param string $tag Value of "ETag" header
672 */
673 function setETag( $tag ) {
674 $this->mETag = $tag;
675 }
676
677 /**
678 * Set whether the output should only contain the body of the article,
679 * without any skin, sidebar, etc.
680 * Used e.g. when calling with "action=render".
681 *
682 * @param bool $only Whether to output only the body of the article
683 */
684 public function setArticleBodyOnly( $only ) {
685 $this->mArticleBodyOnly = $only;
686 }
687
688 /**
689 * Return whether the output will contain only the body of the article
690 *
691 * @return bool
692 */
693 public function getArticleBodyOnly() {
694 return $this->mArticleBodyOnly;
695 }
696
697 /**
698 * Set an additional output property
699 * @since 1.21
700 *
701 * @param string $name
702 * @param mixed $value
703 */
704 public function setProperty( $name, $value ) {
705 $this->mProperties[$name] = $value;
706 }
707
708 /**
709 * Get an additional output property
710 * @since 1.21
711 *
712 * @param string $name
713 * @return mixed Property value or null if not found
714 */
715 public function getProperty( $name ) {
716 if ( isset( $this->mProperties[$name] ) ) {
717 return $this->mProperties[$name];
718 } else {
719 return null;
720 }
721 }
722
723 /**
724 * checkLastModified tells the client to use the client-cached page if
725 * possible. If successful, the OutputPage is disabled so that
726 * any future call to OutputPage->output() have no effect.
727 *
728 * Side effect: sets mLastModified for Last-Modified header
729 *
730 * @param string $timestamp
731 *
732 * @return bool True if cache-ok headers was sent.
733 */
734 public function checkLastModified( $timestamp ) {
735 if ( !$timestamp || $timestamp == '19700101000000' ) {
736 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
737 return false;
738 }
739 $config = $this->getConfig();
740 if ( !$config->get( 'CachePages' ) ) {
741 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
742 return false;
743 }
744
745 $timestamp = wfTimestamp( TS_MW, $timestamp );
746 $modifiedTimes = array(
747 'page' => $timestamp,
748 'user' => $this->getUser()->getTouched(),
749 'epoch' => $config->get( 'CacheEpoch' )
750 );
751 if ( $config->get( 'UseSquid' ) ) {
752 // bug 44570: the core page itself may not change, but resources might
753 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
754 }
755 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
756
757 $maxModified = max( $modifiedTimes );
758 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
759
760 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
761 if ( $clientHeader === false ) {
762 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", 'log' );
763 return false;
764 }
765
766 # IE sends sizes after the date like this:
767 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
768 # this breaks strtotime().
769 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
770
771 wfSuppressWarnings(); // E_STRICT system time bitching
772 $clientHeaderTime = strtotime( $clientHeader );
773 wfRestoreWarnings();
774 if ( !$clientHeaderTime ) {
775 wfDebug( __METHOD__
776 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
777 return false;
778 }
779 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
780
781 # Make debug info
782 $info = '';
783 foreach ( $modifiedTimes as $name => $value ) {
784 if ( $info !== '' ) {
785 $info .= ', ';
786 }
787 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
788 }
789
790 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
791 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", 'log' );
792 wfDebug( __METHOD__ . ": effective Last-Modified: " .
793 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", 'log' );
794 if ( $clientHeaderTime < $maxModified ) {
795 wfDebug( __METHOD__ . ": STALE, $info\n", 'log' );
796 return false;
797 }
798
799 # Not modified
800 # Give a 304 response code and disable body output
801 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", 'log' );
802 ini_set( 'zlib.output_compression', 0 );
803 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
804 $this->sendCacheControl();
805 $this->disable();
806
807 // Don't output a compressed blob when using ob_gzhandler;
808 // it's technically against HTTP spec and seems to confuse
809 // Firefox when the response gets split over two packets.
810 wfClearOutputBuffers();
811
812 return true;
813 }
814
815 /**
816 * Override the last modified timestamp
817 *
818 * @param string $timestamp New timestamp, in a format readable by
819 * wfTimestamp()
820 */
821 public function setLastModified( $timestamp ) {
822 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
823 }
824
825 /**
826 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
827 *
828 * @param string $policy The literal string to output as the contents of
829 * the meta tag. Will be parsed according to the spec and output in
830 * standardized form.
831 * @return null
832 */
833 public function setRobotPolicy( $policy ) {
834 $policy = Article::formatRobotPolicy( $policy );
835
836 if ( isset( $policy['index'] ) ) {
837 $this->setIndexPolicy( $policy['index'] );
838 }
839 if ( isset( $policy['follow'] ) ) {
840 $this->setFollowPolicy( $policy['follow'] );
841 }
842 }
843
844 /**
845 * Set the index policy for the page, but leave the follow policy un-
846 * touched.
847 *
848 * @param string $policy Either 'index' or 'noindex'.
849 * @return null
850 */
851 public function setIndexPolicy( $policy ) {
852 $policy = trim( $policy );
853 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
854 $this->mIndexPolicy = $policy;
855 }
856 }
857
858 /**
859 * Set the follow policy for the page, but leave the index policy un-
860 * touched.
861 *
862 * @param string $policy Either 'follow' or 'nofollow'.
863 * @return null
864 */
865 public function setFollowPolicy( $policy ) {
866 $policy = trim( $policy );
867 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
868 $this->mFollowPolicy = $policy;
869 }
870 }
871
872 /**
873 * Set the new value of the "action text", this will be added to the
874 * "HTML title", separated from it with " - ".
875 *
876 * @param string $text New value of the "action text"
877 */
878 public function setPageTitleActionText( $text ) {
879 $this->mPageTitleActionText = $text;
880 }
881
882 /**
883 * Get the value of the "action text"
884 *
885 * @return string
886 */
887 public function getPageTitleActionText() {
888 return $this->mPageTitleActionText;
889 }
890
891 /**
892 * "HTML title" means the contents of "<title>".
893 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
894 *
895 * @param string|Message $name
896 */
897 public function setHTMLTitle( $name ) {
898 if ( $name instanceof Message ) {
899 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
900 } else {
901 $this->mHTMLtitle = $name;
902 }
903 }
904
905 /**
906 * Return the "HTML title", i.e. the content of the "<title>" tag.
907 *
908 * @return string
909 */
910 public function getHTMLTitle() {
911 return $this->mHTMLtitle;
912 }
913
914 /**
915 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
916 *
917 * @param Title $t
918 */
919 public function setRedirectedFrom( $t ) {
920 $this->mRedirectedFrom = $t;
921 }
922
923 /**
924 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
925 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
926 * but not bad tags like \<script\>. This function automatically sets
927 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
928 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
929 * good tags like \<i\> will be dropped entirely.
930 *
931 * @param string|Message $name
932 */
933 public function setPageTitle( $name ) {
934 if ( $name instanceof Message ) {
935 $name = $name->setContext( $this->getContext() )->text();
936 }
937
938 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
939 # but leave "<i>foobar</i>" alone
940 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
941 $this->mPagetitle = $nameWithTags;
942
943 # change "<i>foo&amp;bar</i>" to "foo&bar"
944 $this->setHTMLTitle(
945 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
946 ->inContentLanguage()
947 );
948 }
949
950 /**
951 * Return the "page title", i.e. the content of the \<h1\> tag.
952 *
953 * @return string
954 */
955 public function getPageTitle() {
956 return $this->mPagetitle;
957 }
958
959 /**
960 * Set the Title object to use
961 *
962 * @param Title $t
963 */
964 public function setTitle( Title $t ) {
965 $this->getContext()->setTitle( $t );
966 }
967
968 /**
969 * Replace the subtitle with $str
970 *
971 * @param string|Message $str New value of the subtitle. String should be safe HTML.
972 */
973 public function setSubtitle( $str ) {
974 $this->clearSubtitle();
975 $this->addSubtitle( $str );
976 }
977
978 /**
979 * Add $str to the subtitle
980 *
981 * @deprecated since 1.19; use addSubtitle() instead
982 * @param string|Message $str String or Message to add to the subtitle
983 */
984 public function appendSubtitle( $str ) {
985 $this->addSubtitle( $str );
986 }
987
988 /**
989 * Add $str to the subtitle
990 *
991 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
992 */
993 public function addSubtitle( $str ) {
994 if ( $str instanceof Message ) {
995 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
996 } else {
997 $this->mSubtitle[] = $str;
998 }
999 }
1000
1001 /**
1002 * Add a subtitle containing a backlink to a page
1003 *
1004 * @param Title $title Title to link to
1005 * @param array $query Array of additional parameters to include in the link
1006 */
1007 public function addBacklinkSubtitle( Title $title, $query = array() ) {
1008 if ( $title->isRedirect() ) {
1009 $query['redirect'] = 'no';
1010 }
1011 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1012 ->rawParams( Linker::link( $title, null, array(), $query ) ) );
1013 }
1014
1015 /**
1016 * Clear the subtitles
1017 */
1018 public function clearSubtitle() {
1019 $this->mSubtitle = array();
1020 }
1021
1022 /**
1023 * Get the subtitle
1024 *
1025 * @return string
1026 */
1027 public function getSubtitle() {
1028 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1029 }
1030
1031 /**
1032 * Set the page as printable, i.e. it'll be displayed with with all
1033 * print styles included
1034 */
1035 public function setPrintable() {
1036 $this->mPrintable = true;
1037 }
1038
1039 /**
1040 * Return whether the page is "printable"
1041 *
1042 * @return bool
1043 */
1044 public function isPrintable() {
1045 return $this->mPrintable;
1046 }
1047
1048 /**
1049 * Disable output completely, i.e. calling output() will have no effect
1050 */
1051 public function disable() {
1052 $this->mDoNothing = true;
1053 }
1054
1055 /**
1056 * Return whether the output will be completely disabled
1057 *
1058 * @return bool
1059 */
1060 public function isDisabled() {
1061 return $this->mDoNothing;
1062 }
1063
1064 /**
1065 * Show an "add new section" link?
1066 *
1067 * @return bool
1068 */
1069 public function showNewSectionLink() {
1070 return $this->mNewSectionLink;
1071 }
1072
1073 /**
1074 * Forcibly hide the new section link?
1075 *
1076 * @return bool
1077 */
1078 public function forceHideNewSectionLink() {
1079 return $this->mHideNewSectionLink;
1080 }
1081
1082 /**
1083 * Add or remove feed links in the page header
1084 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1085 * for the new version
1086 * @see addFeedLink()
1087 *
1088 * @param bool $show True: add default feeds, false: remove all feeds
1089 */
1090 public function setSyndicated( $show = true ) {
1091 if ( $show ) {
1092 $this->setFeedAppendQuery( false );
1093 } else {
1094 $this->mFeedLinks = array();
1095 }
1096 }
1097
1098 /**
1099 * Add default feeds to the page header
1100 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1101 * for the new version
1102 * @see addFeedLink()
1103 *
1104 * @param string $val Query to append to feed links or false to output
1105 * default links
1106 */
1107 public function setFeedAppendQuery( $val ) {
1108 $this->mFeedLinks = array();
1109
1110 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1111 $query = "feed=$type";
1112 if ( is_string( $val ) ) {
1113 $query .= '&' . $val;
1114 }
1115 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1116 }
1117 }
1118
1119 /**
1120 * Add a feed link to the page header
1121 *
1122 * @param string $format Feed type, should be a key of $wgFeedClasses
1123 * @param string $href URL
1124 */
1125 public function addFeedLink( $format, $href ) {
1126 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1127 $this->mFeedLinks[$format] = $href;
1128 }
1129 }
1130
1131 /**
1132 * Should we output feed links for this page?
1133 * @return bool
1134 */
1135 public function isSyndicated() {
1136 return count( $this->mFeedLinks ) > 0;
1137 }
1138
1139 /**
1140 * Return URLs for each supported syndication format for this page.
1141 * @return array Associating format keys with URLs
1142 */
1143 public function getSyndicationLinks() {
1144 return $this->mFeedLinks;
1145 }
1146
1147 /**
1148 * Will currently always return null
1149 *
1150 * @return null
1151 */
1152 public function getFeedAppendQuery() {
1153 return $this->mFeedLinksAppendQuery;
1154 }
1155
1156 /**
1157 * Set whether the displayed content is related to the source of the
1158 * corresponding article on the wiki
1159 * Setting true will cause the change "article related" toggle to true
1160 *
1161 * @param bool $v
1162 */
1163 public function setArticleFlag( $v ) {
1164 $this->mIsarticle = $v;
1165 if ( $v ) {
1166 $this->mIsArticleRelated = $v;
1167 }
1168 }
1169
1170 /**
1171 * Return whether the content displayed page is related to the source of
1172 * the corresponding article on the wiki
1173 *
1174 * @return bool
1175 */
1176 public function isArticle() {
1177 return $this->mIsarticle;
1178 }
1179
1180 /**
1181 * Set whether this page is related an article on the wiki
1182 * Setting false will cause the change of "article flag" toggle to false
1183 *
1184 * @param bool $v
1185 */
1186 public function setArticleRelated( $v ) {
1187 $this->mIsArticleRelated = $v;
1188 if ( !$v ) {
1189 $this->mIsarticle = false;
1190 }
1191 }
1192
1193 /**
1194 * Return whether this page is related an article on the wiki
1195 *
1196 * @return bool
1197 */
1198 public function isArticleRelated() {
1199 return $this->mIsArticleRelated;
1200 }
1201
1202 /**
1203 * Add new language links
1204 *
1205 * @param array $newLinkArray Associative array mapping language code to the page
1206 * name
1207 */
1208 public function addLanguageLinks( array $newLinkArray ) {
1209 $this->mLanguageLinks += $newLinkArray;
1210 }
1211
1212 /**
1213 * Reset the language links and add new language links
1214 *
1215 * @param array $newLinkArray Associative array mapping language code to the page
1216 * name
1217 */
1218 public function setLanguageLinks( array $newLinkArray ) {
1219 $this->mLanguageLinks = $newLinkArray;
1220 }
1221
1222 /**
1223 * Get the list of language links
1224 *
1225 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1226 */
1227 public function getLanguageLinks() {
1228 return $this->mLanguageLinks;
1229 }
1230
1231 /**
1232 * Add an array of categories, with names in the keys
1233 *
1234 * @param array $categories Mapping category name => sort key
1235 */
1236 public function addCategoryLinks( array $categories ) {
1237 global $wgContLang;
1238
1239 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1240 return;
1241 }
1242
1243 # Add the links to a LinkBatch
1244 $arr = array( NS_CATEGORY => $categories );
1245 $lb = new LinkBatch;
1246 $lb->setArray( $arr );
1247
1248 # Fetch existence plus the hiddencat property
1249 $dbr = wfGetDB( DB_SLAVE );
1250 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1251 'page_is_redirect', 'page_latest', 'pp_value' );
1252
1253 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1254 $fields[] = 'page_content_model';
1255 }
1256
1257 $res = $dbr->select( array( 'page', 'page_props' ),
1258 $fields,
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 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1661 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1662 list( $hookName, $data ) = $hookInfo;
1663 if ( isset( $parserOutputHooks[$hookName] ) ) {
1664 call_user_func( $parserOutputHooks[$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 static $cookies;
1815 if ( $cookies === null ) {
1816 $config = $this->getConfig();
1817 $cookies = array_merge(
1818 array(
1819 $config->get( 'CookiePrefix' ) . 'Token',
1820 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1821 "forceHTTPS",
1822 session_name()
1823 ),
1824 $config->get( 'CacheVaryCookies' )
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 $config = $this->getConfig();
1991 if ( $config->get( 'BreakFrames' ) ) {
1992 return 'DENY';
1993 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
1994 return $config->get( 'EditPageFrameOptions' );
1995 }
1996 return false;
1997 }
1998
1999 /**
2000 * Send cache control HTTP headers
2001 */
2002 public function sendCacheControl() {
2003 $response = $this->getRequest()->response();
2004 $config = $this->getConfig();
2005 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2006 $response->header( "ETag: $this->mETag" );
2007 }
2008
2009 $this->addVaryHeader( 'Cookie' );
2010 $this->addAcceptLanguage();
2011
2012 # don't serve compressed data to clients who can't handle it
2013 # maintain different caches for logged-in users and non-logged in ones
2014 $response->header( $this->getVaryHeader() );
2015
2016 if ( $config->get( 'UseXVO' ) ) {
2017 # Add an X-Vary-Options header for Squid with Wikimedia patches
2018 $response->header( $this->getXVO() );
2019 }
2020
2021 if ( $this->mEnableClientCache ) {
2022 if (
2023 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2024 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2025 ) {
2026 if ( $config->get( 'UseESI' ) ) {
2027 # We'll purge the proxy cache explicitly, but require end user agents
2028 # to revalidate against the proxy on each visit.
2029 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2030 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2031 # start with a shorter timeout for initial testing
2032 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2033 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2034 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2035 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2036 } else {
2037 # We'll purge the proxy cache for anons explicitly, but require end user agents
2038 # to revalidate against the proxy on each visit.
2039 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2040 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2041 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2042 # start with a shorter timeout for initial testing
2043 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2044 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2045 . ', must-revalidate, max-age=0' );
2046 }
2047 } else {
2048 # We do want clients to cache if they can, but they *must* check for updates
2049 # on revisiting the page.
2050 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2051 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2052 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2053 }
2054 if ( $this->mLastModified ) {
2055 $response->header( "Last-Modified: {$this->mLastModified}" );
2056 }
2057 } else {
2058 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2059
2060 # In general, the absence of a last modified header should be enough to prevent
2061 # the client from using its cache. We send a few other things just to make sure.
2062 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2063 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2064 $response->header( 'Pragma: no-cache' );
2065 }
2066 }
2067
2068 /**
2069 * Finally, all the text has been munged and accumulated into
2070 * the object, let's actually output it:
2071 */
2072 public function output() {
2073 global $wgLanguageCode;
2074
2075 if ( $this->mDoNothing ) {
2076 return;
2077 }
2078
2079 wfProfileIn( __METHOD__ );
2080
2081 $response = $this->getRequest()->response();
2082 $config = $this->getConfig();
2083
2084 if ( $this->mRedirect != '' ) {
2085 # Standards require redirect URLs to be absolute
2086 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2087
2088 $redirect = $this->mRedirect;
2089 $code = $this->mRedirectCode;
2090
2091 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2092 if ( $code == '301' || $code == '303' ) {
2093 if ( !$config->get( 'DebugRedirects' ) ) {
2094 $message = HttpStatus::getMessage( $code );
2095 $response->header( "HTTP/1.1 $code $message" );
2096 }
2097 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2098 }
2099 if ( $config->get( 'VaryOnXFP' ) ) {
2100 $this->addVaryHeader( 'X-Forwarded-Proto' );
2101 }
2102 $this->sendCacheControl();
2103
2104 $response->header( "Content-Type: text/html; charset=utf-8" );
2105 if ( $config->get( 'DebugRedirects' ) ) {
2106 $url = htmlspecialchars( $redirect );
2107 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2108 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2109 print "</body>\n</html>\n";
2110 } else {
2111 $response->header( 'Location: ' . $redirect );
2112 }
2113 }
2114
2115 wfProfileOut( __METHOD__ );
2116 return;
2117 } elseif ( $this->mStatusCode ) {
2118 $message = HttpStatus::getMessage( $this->mStatusCode );
2119 if ( $message ) {
2120 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2121 }
2122 }
2123
2124 # Buffer output; final headers may depend on later processing
2125 ob_start();
2126
2127 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2128 $response->header( 'Content-language: ' . $wgLanguageCode );
2129
2130 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2131 // jQuery etc. can work correctly.
2132 $response->header( 'X-UA-Compatible: IE=Edge' );
2133
2134 // Prevent framing, if requested
2135 $frameOptions = $this->getFrameOptions();
2136 if ( $frameOptions ) {
2137 $response->header( "X-Frame-Options: $frameOptions" );
2138 }
2139
2140 if ( $this->mArticleBodyOnly ) {
2141 echo $this->mBodytext;
2142 } else {
2143
2144 $sk = $this->getSkin();
2145 // add skin specific modules
2146 $modules = $sk->getDefaultModules();
2147
2148 // enforce various default modules for all skins
2149 $coreModules = array(
2150 // keep this list as small as possible
2151 'mediawiki.page.startup',
2152 'mediawiki.user',
2153 );
2154
2155 // Support for high-density display images if enabled
2156 if ( $config->get( 'ResponsiveImages' ) ) {
2157 $coreModules[] = 'mediawiki.hidpi';
2158 }
2159
2160 $this->addModules( $coreModules );
2161 foreach ( $modules as $group ) {
2162 $this->addModules( $group );
2163 }
2164 MWDebug::addModules( $this );
2165
2166 // Hook that allows last minute changes to the output page, e.g.
2167 // adding of CSS or Javascript by extensions.
2168 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2169
2170 wfProfileIn( 'Output-skin' );
2171 $sk->outputPage();
2172 wfProfileOut( 'Output-skin' );
2173 }
2174
2175 // This hook allows last minute changes to final overall output by modifying output buffer
2176 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2177
2178 $this->sendCacheControl();
2179
2180 ob_end_flush();
2181
2182 wfProfileOut( __METHOD__ );
2183 }
2184
2185 /**
2186 * Actually output something with print.
2187 *
2188 * @param string $ins The string to output
2189 * @deprecated since 1.22 Use echo yourself.
2190 */
2191 public function out( $ins ) {
2192 wfDeprecated( __METHOD__, '1.22' );
2193 print $ins;
2194 }
2195
2196 /**
2197 * Produce a "user is blocked" page.
2198 * @deprecated since 1.18
2199 */
2200 function blockedPage() {
2201 throw new UserBlockedError( $this->getUser()->mBlock );
2202 }
2203
2204 /**
2205 * Prepare this object to display an error page; disable caching and
2206 * indexing, clear the current text and redirect, set the page's title
2207 * and optionally an custom HTML title (content of the "<title>" tag).
2208 *
2209 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2210 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2211 * optional, if not passed the "<title>" attribute will be
2212 * based on $pageTitle
2213 */
2214 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2215 $this->setPageTitle( $pageTitle );
2216 if ( $htmlTitle !== false ) {
2217 $this->setHTMLTitle( $htmlTitle );
2218 }
2219 $this->setRobotPolicy( 'noindex,nofollow' );
2220 $this->setArticleRelated( false );
2221 $this->enableClientCache( false );
2222 $this->mRedirect = '';
2223 $this->clearSubtitle();
2224 $this->clearHTML();
2225 }
2226
2227 /**
2228 * Output a standard error page
2229 *
2230 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2231 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2232 * showErrorPage( 'titlemsg', $messageObject );
2233 * showErrorPage( $titleMessageObject, $messageObject );
2234 *
2235 * @param string|Message $title Message key (string) for page title, or a Message object
2236 * @param string|Message $msg Message key (string) for page text, or a Message object
2237 * @param array $params Message parameters; ignored if $msg is a Message object
2238 */
2239 public function showErrorPage( $title, $msg, $params = array() ) {
2240 if ( !$title instanceof Message ) {
2241 $title = $this->msg( $title );
2242 }
2243
2244 $this->prepareErrorPage( $title );
2245
2246 if ( $msg instanceof Message ) {
2247 if ( $params !== array() ) {
2248 trigger_error( 'Argument ignored: $params. The message parameters argument '
2249 . 'is discarded when the $msg argument is a Message object instead of '
2250 . 'a string.', E_USER_NOTICE );
2251 }
2252 $this->addHTML( $msg->parseAsBlock() );
2253 } else {
2254 $this->addWikiMsgArray( $msg, $params );
2255 }
2256
2257 $this->returnToMain();
2258 }
2259
2260 /**
2261 * Output a standard permission error page
2262 *
2263 * @param array $errors Error message keys
2264 * @param string $action Action that was denied or null if unknown
2265 */
2266 public function showPermissionsErrorPage( array $errors, $action = null ) {
2267 // For some action (read, edit, create and upload), display a "login to do this action"
2268 // error if all of the following conditions are met:
2269 // 1. the user is not logged in
2270 // 2. the only error is insufficient permissions (i.e. no block or something else)
2271 // 3. the error can be avoided simply by logging in
2272 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2273 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2274 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2275 && ( User::groupHasPermission( 'user', $action )
2276 || User::groupHasPermission( 'autoconfirmed', $action ) )
2277 ) {
2278 $displayReturnto = null;
2279
2280 # Due to bug 32276, if a user does not have read permissions,
2281 # $this->getTitle() will just give Special:Badtitle, which is
2282 # not especially useful as a returnto parameter. Use the title
2283 # from the request instead, if there was one.
2284 $request = $this->getRequest();
2285 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2286 if ( $action == 'edit' ) {
2287 $msg = 'whitelistedittext';
2288 $displayReturnto = $returnto;
2289 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2290 $msg = 'nocreatetext';
2291 } elseif ( $action == 'upload' ) {
2292 $msg = 'uploadnologintext';
2293 } else { # Read
2294 $msg = 'loginreqpagetext';
2295 $displayReturnto = Title::newMainPage();
2296 }
2297
2298 $query = array();
2299
2300 if ( $returnto ) {
2301 $query['returnto'] = $returnto->getPrefixedText();
2302
2303 if ( !$request->wasPosted() ) {
2304 $returntoquery = $request->getValues();
2305 unset( $returntoquery['title'] );
2306 unset( $returntoquery['returnto'] );
2307 unset( $returntoquery['returntoquery'] );
2308 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2309 }
2310 }
2311 $loginLink = Linker::linkKnown(
2312 SpecialPage::getTitleFor( 'Userlogin' ),
2313 $this->msg( 'loginreqlink' )->escaped(),
2314 array(),
2315 $query
2316 );
2317
2318 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2319 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2320
2321 # Don't return to a page the user can't read otherwise
2322 # we'll end up in a pointless loop
2323 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2324 $this->returnToMain( null, $displayReturnto );
2325 }
2326 } else {
2327 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2328 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2329 }
2330 }
2331
2332 /**
2333 * Display an error page indicating that a given version of MediaWiki is
2334 * required to use it
2335 *
2336 * @param mixed $version The version of MediaWiki needed to use the page
2337 */
2338 public function versionRequired( $version ) {
2339 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2340
2341 $this->addWikiMsg( 'versionrequiredtext', $version );
2342 $this->returnToMain();
2343 }
2344
2345 /**
2346 * Display an error page noting that a given permission bit is required.
2347 * @deprecated since 1.18, just throw the exception directly
2348 * @param string $permission Key required
2349 * @throws PermissionsError
2350 */
2351 public function permissionRequired( $permission ) {
2352 throw new PermissionsError( $permission );
2353 }
2354
2355 /**
2356 * Produce the stock "please login to use the wiki" page
2357 *
2358 * @deprecated since 1.19; throw the exception directly
2359 */
2360 public function loginToUse() {
2361 throw new PermissionsError( 'read' );
2362 }
2363
2364 /**
2365 * Format a list of error messages
2366 *
2367 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2368 * @param string $action Action that was denied or null if unknown
2369 * @return string The wikitext error-messages, formatted into a list.
2370 */
2371 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2372 if ( $action == null ) {
2373 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2374 } else {
2375 $action_desc = $this->msg( "action-$action" )->plain();
2376 $text = $this->msg(
2377 'permissionserrorstext-withaction',
2378 count( $errors ),
2379 $action_desc
2380 )->plain() . "\n\n";
2381 }
2382
2383 if ( count( $errors ) > 1 ) {
2384 $text .= '<ul class="permissions-errors">' . "\n";
2385
2386 foreach ( $errors as $error ) {
2387 $text .= '<li>';
2388 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2389 $text .= "</li>\n";
2390 }
2391 $text .= '</ul>';
2392 } else {
2393 $text .= "<div class=\"permissions-errors\">\n" .
2394 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2395 "\n</div>";
2396 }
2397
2398 return $text;
2399 }
2400
2401 /**
2402 * Display a page stating that the Wiki is in read-only mode,
2403 * and optionally show the source of the page that the user
2404 * was trying to edit. Should only be called (for this
2405 * purpose) after wfReadOnly() has returned true.
2406 *
2407 * For historical reasons, this function is _also_ used to
2408 * show the error message when a user tries to edit a page
2409 * they are not allowed to edit. (Unless it's because they're
2410 * blocked, then we show blockedPage() instead.) In this
2411 * case, the second parameter should be set to true and a list
2412 * of reasons supplied as the third parameter.
2413 *
2414 * @todo Needs to be split into multiple functions.
2415 *
2416 * @param string $source Source code to show (or null).
2417 * @param bool $protected Is this a permissions error?
2418 * @param array $reasons List of reasons for this error, as returned by
2419 * Title::getUserPermissionsErrors().
2420 * @param string $action Action that was denied or null if unknown
2421 * @throws ReadOnlyError
2422 */
2423 public function readOnlyPage( $source = null, $protected = false,
2424 array $reasons = array(), $action = null
2425 ) {
2426 $this->setRobotPolicy( 'noindex,nofollow' );
2427 $this->setArticleRelated( false );
2428
2429 // If no reason is given, just supply a default "I can't let you do
2430 // that, Dave" message. Should only occur if called by legacy code.
2431 if ( $protected && empty( $reasons ) ) {
2432 $reasons[] = array( 'badaccess-group0' );
2433 }
2434
2435 if ( !empty( $reasons ) ) {
2436 // Permissions error
2437 if ( $source ) {
2438 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2439 $this->addBacklinkSubtitle( $this->getTitle() );
2440 } else {
2441 $this->setPageTitle( $this->msg( 'badaccess' ) );
2442 }
2443 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2444 } else {
2445 // Wiki is read only
2446 throw new ReadOnlyError;
2447 }
2448
2449 // Show source, if supplied
2450 if ( is_string( $source ) ) {
2451 $this->addWikiMsg( 'viewsourcetext' );
2452
2453 $pageLang = $this->getTitle()->getPageLanguage();
2454 $params = array(
2455 'id' => 'wpTextbox1',
2456 'name' => 'wpTextbox1',
2457 'cols' => $this->getUser()->getOption( 'cols' ),
2458 'rows' => $this->getUser()->getOption( 'rows' ),
2459 'readonly' => 'readonly',
2460 'lang' => $pageLang->getHtmlCode(),
2461 'dir' => $pageLang->getDir(),
2462 );
2463 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2464
2465 // Show templates used by this article
2466 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2467 $this->addHTML( "<div class='templatesUsed'>
2468 $templates
2469 </div>
2470 " );
2471 }
2472
2473 # If the title doesn't exist, it's fairly pointless to print a return
2474 # link to it. After all, you just tried editing it and couldn't, so
2475 # what's there to do there?
2476 if ( $this->getTitle()->exists() ) {
2477 $this->returnToMain( null, $this->getTitle() );
2478 }
2479 }
2480
2481 /**
2482 * Turn off regular page output and return an error response
2483 * for when rate limiting has triggered.
2484 */
2485 public function rateLimited() {
2486 throw new ThrottledError;
2487 }
2488
2489 /**
2490 * Show a warning about slave lag
2491 *
2492 * If the lag is higher than $wgSlaveLagCritical seconds,
2493 * then the warning is a bit more obvious. If the lag is
2494 * lower than $wgSlaveLagWarning, then no warning is shown.
2495 *
2496 * @param int $lag Slave lag
2497 */
2498 public function showLagWarning( $lag ) {
2499 $config = $this->getConfig();
2500 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2501 $message = $lag < $config->get( 'SlaveLagCritical' )
2502 ? 'lag-warn-normal'
2503 : 'lag-warn-high';
2504 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2505 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2506 }
2507 }
2508
2509 public function showFatalError( $message ) {
2510 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2511
2512 $this->addHTML( $message );
2513 }
2514
2515 public function showUnexpectedValueError( $name, $val ) {
2516 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2517 }
2518
2519 public function showFileCopyError( $old, $new ) {
2520 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2521 }
2522
2523 public function showFileRenameError( $old, $new ) {
2524 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2525 }
2526
2527 public function showFileDeleteError( $name ) {
2528 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2529 }
2530
2531 public function showFileNotFoundError( $name ) {
2532 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2533 }
2534
2535 /**
2536 * Add a "return to" link pointing to a specified title
2537 *
2538 * @param Title $title Title to link
2539 * @param array $query Query string parameters
2540 * @param string $text Text of the link (input is not escaped)
2541 * @param array $options Options array to pass to Linker
2542 */
2543 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2544 $link = $this->msg( 'returnto' )->rawParams(
2545 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2546 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2547 }
2548
2549 /**
2550 * Add a "return to" link pointing to a specified title,
2551 * or the title indicated in the request, or else the main page
2552 *
2553 * @param mixed $unused
2554 * @param Title|string $returnto Title or String to return to
2555 * @param string $returntoquery Query string for the return to link
2556 */
2557 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2558 if ( $returnto == null ) {
2559 $returnto = $this->getRequest()->getText( 'returnto' );
2560 }
2561
2562 if ( $returntoquery == null ) {
2563 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2564 }
2565
2566 if ( $returnto === '' ) {
2567 $returnto = Title::newMainPage();
2568 }
2569
2570 if ( is_object( $returnto ) ) {
2571 $titleObj = $returnto;
2572 } else {
2573 $titleObj = Title::newFromText( $returnto );
2574 }
2575 if ( !is_object( $titleObj ) ) {
2576 $titleObj = Title::newMainPage();
2577 }
2578
2579 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2580 }
2581
2582 /**
2583 * @param Skin $sk The given Skin
2584 * @param bool $includeStyle Unused
2585 * @return string The doctype, opening "<html>", and head element.
2586 */
2587 public function headElement( Skin $sk, $includeStyle = true ) {
2588 global $wgContLang;
2589
2590 $userdir = $this->getLanguage()->getDir();
2591 $sitedir = $wgContLang->getDir();
2592
2593 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2594
2595 if ( $this->getHTMLTitle() == '' ) {
2596 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2597 }
2598
2599 $openHead = Html::openElement( 'head' );
2600 if ( $openHead ) {
2601 # Don't bother with the newline if $head == ''
2602 $ret .= "$openHead\n";
2603 }
2604
2605 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2606 // Add <meta charset="UTF-8">
2607 // This should be before <title> since it defines the charset used by
2608 // text including the text inside <title>.
2609 // The spec recommends defining XHTML5's charset using the XML declaration
2610 // instead of meta.
2611 // Our XML declaration is output by Html::htmlHeader.
2612 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2613 // http://www.whatwg.org/html/semantics.html#charset
2614 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2615 }
2616
2617 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2618
2619 foreach ( $this->getHeadLinksArray() as $item ) {
2620 $ret .= $item . "\n";
2621 }
2622
2623 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2624 $ret .= $this->buildCssLinks();
2625
2626 $ret .= $this->getHeadScripts() . "\n";
2627
2628 foreach ( $this->mHeadItems as $item ) {
2629 $ret .= $item . "\n";
2630 }
2631
2632 $closeHead = Html::closeElement( 'head' );
2633 if ( $closeHead ) {
2634 $ret .= "$closeHead\n";
2635 }
2636
2637 $bodyClasses = array();
2638 $bodyClasses[] = 'mediawiki';
2639
2640 # Classes for LTR/RTL directionality support
2641 $bodyClasses[] = $userdir;
2642 $bodyClasses[] = "sitedir-$sitedir";
2643
2644 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2645 # A <body> class is probably not the best way to do this . . .
2646 $bodyClasses[] = 'capitalize-all-nouns';
2647 }
2648
2649 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2650 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2651 $bodyClasses[] =
2652 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2653
2654 $bodyAttrs = array();
2655 // While the implode() is not strictly needed, it's used for backwards compatibility
2656 // (this used to be built as a string and hooks likely still expect that).
2657 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2658
2659 // Allow skins and extensions to add body attributes they need
2660 $sk->addToBodyAttributes( $this, $bodyAttrs );
2661 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2662
2663 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2664
2665 return $ret;
2666 }
2667
2668 /**
2669 * Get a ResourceLoader object associated with this OutputPage
2670 *
2671 * @return ResourceLoader
2672 */
2673 public function getResourceLoader() {
2674 if ( is_null( $this->mResourceLoader ) ) {
2675 $this->mResourceLoader = new ResourceLoader( $this->getConfig() );
2676 }
2677 return $this->mResourceLoader;
2678 }
2679
2680 /**
2681 * @todo Document
2682 * @param array|string $modules One or more module names
2683 * @param string $only ResourceLoaderModule TYPE_ class constant
2684 * @param bool $useESI
2685 * @param array $extraQuery Array with extra query parameters to add to each
2686 * request. array( param => value ).
2687 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2688 * call rather than a "<script src='...'>" tag.
2689 * @return string The html "<script>", "<link>" and "<style>" tags
2690 */
2691 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2692 array $extraQuery = array(), $loadCall = false
2693 ) {
2694 $modules = (array)$modules;
2695
2696 $links = array(
2697 'html' => '',
2698 'states' => array(),
2699 );
2700
2701 if ( !count( $modules ) ) {
2702 return $links;
2703 }
2704
2705 if ( count( $modules ) > 1 ) {
2706 // Remove duplicate module requests
2707 $modules = array_unique( $modules );
2708 // Sort module names so requests are more uniform
2709 sort( $modules );
2710
2711 if ( ResourceLoader::inDebugMode() ) {
2712 // Recursively call us for every item
2713 foreach ( $modules as $name ) {
2714 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2715 $links['html'] .= $link['html'];
2716 $links['states'] += $link['states'];
2717 }
2718 return $links;
2719 }
2720 }
2721
2722 if ( !is_null( $this->mTarget ) ) {
2723 $extraQuery['target'] = $this->mTarget;
2724 }
2725
2726 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2727 $sortedModules = array();
2728 $resourceLoader = $this->getResourceLoader();
2729 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2730 foreach ( $modules as $name ) {
2731 $module = $resourceLoader->getModule( $name );
2732 # Check that we're allowed to include this module on this page
2733 if ( !$module
2734 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2735 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2736 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2737 && $only == ResourceLoaderModule::TYPE_STYLES )
2738 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2739 && $only == ResourceLoaderModule::TYPE_COMBINED )
2740 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2741 ) {
2742 continue;
2743 }
2744
2745 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2746 }
2747
2748 foreach ( $sortedModules as $source => $groups ) {
2749 foreach ( $groups as $group => $grpModules ) {
2750 // Special handling for user-specific groups
2751 $user = null;
2752 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2753 $user = $this->getUser()->getName();
2754 }
2755
2756 // Create a fake request based on the one we are about to make so modules return
2757 // correct timestamp and emptiness data
2758 $query = ResourceLoader::makeLoaderQuery(
2759 array(), // modules; not determined yet
2760 $this->getLanguage()->getCode(),
2761 $this->getSkin()->getSkinName(),
2762 $user,
2763 null, // version; not determined yet
2764 ResourceLoader::inDebugMode(),
2765 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2766 $this->isPrintable(),
2767 $this->getRequest()->getBool( 'handheld' ),
2768 $extraQuery
2769 );
2770 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2771
2772 // Extract modules that know they're empty
2773 foreach ( $grpModules as $key => $module ) {
2774 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2775 // If we're only getting the styles, we don't need to do anything for empty modules.
2776 if ( $module->isKnownEmpty( $context ) ) {
2777 unset( $grpModules[$key] );
2778 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2779 $links['states'][$key] = 'ready';
2780 }
2781 }
2782 }
2783
2784 // If there are no non-empty modules, skip this group
2785 if ( count( $grpModules ) === 0 ) {
2786 continue;
2787 }
2788
2789 // Inline private modules. These can't be loaded through load.php for security
2790 // reasons, see bug 34907. Note that these modules should be loaded from
2791 // getHeadScripts() before the first loader call. Otherwise other modules can't
2792 // properly use them as dependencies (bug 30914)
2793 if ( $group === 'private' ) {
2794 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2795 $links['html'] .= Html::inlineStyle(
2796 $resourceLoader->makeModuleResponse( $context, $grpModules )
2797 );
2798 } else {
2799 $links['html'] .= Html::inlineScript(
2800 $resourceLoader->makeModuleResponse( $context, $grpModules )
2801 );
2802 }
2803 $links['html'] .= "\n";
2804 continue;
2805 }
2806
2807 // Special handling for the user group; because users might change their stuff
2808 // on-wiki like user pages, or user preferences; we need to find the highest
2809 // timestamp of these user-changeable modules so we can ensure cache misses on change
2810 // This should NOT be done for the site group (bug 27564) because anons get that too
2811 // and we shouldn't be putting timestamps in Squid-cached HTML
2812 $version = null;
2813 if ( $group === 'user' ) {
2814 // Get the maximum timestamp
2815 $timestamp = 1;
2816 foreach ( $grpModules as $module ) {
2817 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2818 }
2819 // Add a version parameter so cache will break when things change
2820 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2821 }
2822
2823 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2824 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2825 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2826
2827 if ( $useESI && $resourceLoaderUseESI ) {
2828 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2829 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2830 $link = Html::inlineStyle( $esi );
2831 } else {
2832 $link = Html::inlineScript( $esi );
2833 }
2834 } else {
2835 // Automatically select style/script elements
2836 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2837 $link = Html::linkedStyle( $url );
2838 } elseif ( $loadCall ) {
2839 $link = Html::inlineScript(
2840 ResourceLoader::makeLoaderConditionalScript(
2841 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2842 )
2843 );
2844 } else {
2845 $link = Html::linkedScript( $url );
2846
2847 // For modules requested directly in the html via <link> or <script>,
2848 // tell mw.loader they are being loading to prevent duplicate requests.
2849 foreach ( $grpModules as $key => $module ) {
2850 // Don't output state=loading for the startup module..
2851 if ( $key !== 'startup' ) {
2852 $links['states'][$key] = 'loading';
2853 }
2854 }
2855 }
2856 }
2857
2858 if ( $group == 'noscript' ) {
2859 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2860 } else {
2861 $links['html'] .= $link . "\n";
2862 }
2863 }
2864 }
2865
2866 return $links;
2867 }
2868
2869 /**
2870 * Build html output from an array of links from makeResourceLoaderLink.
2871 * @param array $links
2872 * @return string HTML
2873 */
2874 protected static function getHtmlFromLoaderLinks( array $links ) {
2875 $html = '';
2876 $states = array();
2877 foreach ( $links as $link ) {
2878 if ( !is_array( $link ) ) {
2879 $html .= $link;
2880 } else {
2881 $html .= $link['html'];
2882 $states += $link['states'];
2883 }
2884 }
2885
2886 if ( count( $states ) ) {
2887 $html = Html::inlineScript(
2888 ResourceLoader::makeLoaderConditionalScript(
2889 ResourceLoader::makeLoaderStateScript( $states )
2890 )
2891 ) . "\n" . $html;
2892 }
2893
2894 return $html;
2895 }
2896
2897 /**
2898 * JS stuff to put in the "<head>". This is the startup module, config
2899 * vars and modules marked with position 'top'
2900 *
2901 * @return string HTML fragment
2902 */
2903 function getHeadScripts() {
2904 // Startup - this will immediately load jquery and mediawiki modules
2905 $links = array();
2906 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2907
2908 // Load config before anything else
2909 $links[] = Html::inlineScript(
2910 ResourceLoader::makeLoaderConditionalScript(
2911 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2912 )
2913 );
2914
2915 // Load embeddable private modules before any loader links
2916 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2917 // in mw.loader.implement() calls and deferred until mw.user is available
2918 $embedScripts = array( 'user.options', 'user.tokens' );
2919 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2920
2921 // Scripts and messages "only" requests marked for top inclusion
2922 // Messages should go first
2923 $links[] = $this->makeResourceLoaderLink(
2924 $this->getModuleMessages( true, 'top' ),
2925 ResourceLoaderModule::TYPE_MESSAGES
2926 );
2927 $links[] = $this->makeResourceLoaderLink(
2928 $this->getModuleScripts( true, 'top' ),
2929 ResourceLoaderModule::TYPE_SCRIPTS
2930 );
2931
2932 // Modules requests - let the client calculate dependencies and batch requests as it likes
2933 // Only load modules that have marked themselves for loading at the top
2934 $modules = $this->getModules( true, 'top' );
2935 if ( $modules ) {
2936 $links[] = Html::inlineScript(
2937 ResourceLoader::makeLoaderConditionalScript(
2938 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2939 )
2940 );
2941 }
2942
2943 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2944 $links[] = $this->getScriptsForBottomQueue( true );
2945 }
2946
2947 return self::getHtmlFromLoaderLinks( $links );
2948 }
2949
2950 /**
2951 * JS stuff to put at the 'bottom', which can either be the bottom of the
2952 * "<body>" or the bottom of the "<head>" depending on
2953 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2954 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2955 * and user JS.
2956 *
2957 * @param bool $inHead If true, this HTML goes into the "<head>",
2958 * if false it goes into the "<body>".
2959 * @return string
2960 */
2961 function getScriptsForBottomQueue( $inHead ) {
2962 // Scripts and messages "only" requests marked for bottom inclusion
2963 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2964 // Messages should go first
2965 $links = array();
2966 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2967 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2968 /* $loadCall = */ $inHead
2969 );
2970 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2971 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2972 /* $loadCall = */ $inHead
2973 );
2974
2975 // Modules requests - let the client calculate dependencies and batch requests as it likes
2976 // Only load modules that have marked themselves for loading at the bottom
2977 $modules = $this->getModules( true, 'bottom' );
2978 if ( $modules ) {
2979 $links[] = Html::inlineScript(
2980 ResourceLoader::makeLoaderConditionalScript(
2981 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2982 )
2983 );
2984 }
2985
2986 // Legacy Scripts
2987 $links[] = "\n" . $this->mScripts;
2988
2989 // Add site JS if enabled
2990 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2991 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2992 );
2993
2994 // Add user JS if enabled
2995 if ( $this->getConfig()->get( 'AllowUserJs' )
2996 && $this->getUser()->isLoggedIn()
2997 && $this->getTitle()
2998 && $this->getTitle()->isJsSubpage()
2999 && $this->userCanPreview()
3000 ) {
3001 # XXX: additional security check/prompt?
3002 // We're on a preview of a JS subpage
3003 // Exclude this page from the user module in case it's in there (bug 26283)
3004 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3005 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3006 );
3007 // Load the previewed JS
3008 $links[] = Html::inlineScript( "\n"
3009 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3010
3011 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3012 // asynchronously and may arrive *after* the inline script here. So the previewed code
3013 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3014 } else {
3015 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3016 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3017 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3018 );
3019 }
3020
3021 // Group JS is only enabled if site JS is enabled.
3022 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3023 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3024 );
3025
3026 return self::getHtmlFromLoaderLinks( $links );
3027 }
3028
3029 /**
3030 * JS stuff to put at the bottom of the "<body>"
3031 * @return string
3032 */
3033 function getBottomScripts() {
3034 // Optimise jQuery ready event cross-browser.
3035 // This also enforces $.isReady to be true at </body> which fixes the
3036 // mw.loader bug in Firefox with using document.write between </body>
3037 // and the DOMContentReady event (bug 47457).
3038 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
3039
3040 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3041 $html .= $this->getScriptsForBottomQueue( false );
3042 }
3043
3044 return $html;
3045 }
3046
3047 /**
3048 * Get the javascript config vars to include on this page
3049 *
3050 * @return array Array of javascript config vars
3051 * @since 1.23
3052 */
3053 public function getJsConfigVars() {
3054 return $this->mJsConfigVars;
3055 }
3056
3057 /**
3058 * Add one or more variables to be set in mw.config in JavaScript
3059 *
3060 * @param string|array $keys Key or array of key/value pairs
3061 * @param mixed $value [optional] Value of the configuration variable
3062 */
3063 public function addJsConfigVars( $keys, $value = null ) {
3064 if ( is_array( $keys ) ) {
3065 foreach ( $keys as $key => $value ) {
3066 $this->mJsConfigVars[$key] = $value;
3067 }
3068 return;
3069 }
3070
3071 $this->mJsConfigVars[$keys] = $value;
3072 }
3073
3074 /**
3075 * Get an array containing the variables to be set in mw.config in JavaScript.
3076 *
3077 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3078 * - in other words, page-independent/site-wide variables (without state).
3079 * You will only be adding bloat to the html page and causing page caches to
3080 * have to be purged on configuration changes.
3081 * @return array
3082 */
3083 private function getJSVars() {
3084 global $wgContLang;
3085
3086 $curRevisionId = 0;
3087 $articleId = 0;
3088 $canonicalSpecialPageName = false; # bug 21115
3089
3090 $title = $this->getTitle();
3091 $ns = $title->getNamespace();
3092 $canonicalNamespace = MWNamespace::exists( $ns )
3093 ? MWNamespace::getCanonicalName( $ns )
3094 : $title->getNsText();
3095
3096 $sk = $this->getSkin();
3097 // Get the relevant title so that AJAX features can use the correct page name
3098 // when making API requests from certain special pages (bug 34972).
3099 $relevantTitle = $sk->getRelevantTitle();
3100 $relevantUser = $sk->getRelevantUser();
3101
3102 if ( $ns == NS_SPECIAL ) {
3103 list( $canonicalSpecialPageName, /*...*/ ) =
3104 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3105 } elseif ( $this->canUseWikiPage() ) {
3106 $wikiPage = $this->getWikiPage();
3107 $curRevisionId = $wikiPage->getLatest();
3108 $articleId = $wikiPage->getId();
3109 }
3110
3111 $lang = $title->getPageLanguage();
3112
3113 // Pre-process information
3114 $separatorTransTable = $lang->separatorTransformTable();
3115 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3116 $compactSeparatorTransTable = array(
3117 implode( "\t", array_keys( $separatorTransTable ) ),
3118 implode( "\t", $separatorTransTable ),
3119 );
3120 $digitTransTable = $lang->digitTransformTable();
3121 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3122 $compactDigitTransTable = array(
3123 implode( "\t", array_keys( $digitTransTable ) ),
3124 implode( "\t", $digitTransTable ),
3125 );
3126
3127 $user = $this->getUser();
3128
3129 $vars = array(
3130 'wgCanonicalNamespace' => $canonicalNamespace,
3131 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3132 'wgNamespaceNumber' => $title->getNamespace(),
3133 'wgPageName' => $title->getPrefixedDBkey(),
3134 'wgTitle' => $title->getText(),
3135 'wgCurRevisionId' => $curRevisionId,
3136 'wgRevisionId' => (int)$this->getRevisionId(),
3137 'wgArticleId' => $articleId,
3138 'wgIsArticle' => $this->isArticle(),
3139 'wgIsRedirect' => $title->isRedirect(),
3140 'wgAction' => Action::getActionName( $this->getContext() ),
3141 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3142 'wgUserGroups' => $user->getEffectiveGroups(),
3143 'wgCategories' => $this->getCategories(),
3144 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3145 'wgPageContentLanguage' => $lang->getCode(),
3146 'wgPageContentModel' => $title->getContentModel(),
3147 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3148 'wgDigitTransformTable' => $compactDigitTransTable,
3149 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3150 'wgMonthNames' => $lang->getMonthNamesArray(),
3151 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3152 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3153 );
3154
3155 if ( $user->isLoggedIn() ) {
3156 $vars['wgUserId'] = $user->getId();
3157 $vars['wgUserEditCount'] = $user->getEditCount();
3158 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3159 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3160 // Get the revision ID of the oldest new message on the user's talk
3161 // page. This can be used for constructing new message alerts on
3162 // the client side.
3163 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3164 }
3165
3166 if ( $wgContLang->hasVariants() ) {
3167 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3168 }
3169 // Same test as SkinTemplate
3170 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3171 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3172
3173 foreach ( $title->getRestrictionTypes() as $type ) {
3174 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3175 }
3176
3177 if ( $title->isMainPage() ) {
3178 $vars['wgIsMainPage'] = true;
3179 }
3180
3181 if ( $this->mRedirectedFrom ) {
3182 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3183 }
3184
3185 if ( $relevantUser ) {
3186 $vars['wgRelevantUserName'] = $relevantUser->getName();
3187 }
3188
3189 // Allow extensions to add their custom variables to the mw.config map.
3190 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3191 // page-dependant but site-wide (without state).
3192 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3193 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3194
3195 // Merge in variables from addJsConfigVars last
3196 return array_merge( $vars, $this->getJsConfigVars() );
3197 }
3198
3199 /**
3200 * To make it harder for someone to slip a user a fake
3201 * user-JavaScript or user-CSS preview, a random token
3202 * is associated with the login session. If it's not
3203 * passed back with the preview request, we won't render
3204 * the code.
3205 *
3206 * @return bool
3207 */
3208 public function userCanPreview() {
3209 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3210 || !$this->getRequest()->wasPosted()
3211 || !$this->getUser()->matchEditToken(
3212 $this->getRequest()->getVal( 'wpEditToken' ) )
3213 ) {
3214 return false;
3215 }
3216 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3217 return false;
3218 }
3219
3220 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3221 }
3222
3223 /**
3224 * @return array Array in format "link name or number => 'link html'".
3225 */
3226 public function getHeadLinksArray() {
3227 global $wgVersion;
3228
3229 $tags = array();
3230 $config = $this->getConfig();
3231
3232 $canonicalUrl = $this->mCanonicalUrl;
3233
3234 $tags['meta-generator'] = Html::element( 'meta', array(
3235 'name' => 'generator',
3236 'content' => "MediaWiki $wgVersion",
3237 ) );
3238
3239 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3240 if ( $p !== 'index,follow' ) {
3241 // http://www.robotstxt.org/wc/meta-user.html
3242 // Only show if it's different from the default robots policy
3243 $tags['meta-robots'] = Html::element( 'meta', array(
3244 'name' => 'robots',
3245 'content' => $p,
3246 ) );
3247 }
3248
3249 foreach ( $this->mMetatags as $tag ) {
3250 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3251 $a = 'http-equiv';
3252 $tag[0] = substr( $tag[0], 5 );
3253 } else {
3254 $a = 'name';
3255 }
3256 $tagName = "meta-{$tag[0]}";
3257 if ( isset( $tags[$tagName] ) ) {
3258 $tagName .= $tag[1];
3259 }
3260 $tags[$tagName] = Html::element( 'meta',
3261 array(
3262 $a => $tag[0],
3263 'content' => $tag[1]
3264 )
3265 );
3266 }
3267
3268 foreach ( $this->mLinktags as $tag ) {
3269 $tags[] = Html::element( 'link', $tag );
3270 }
3271
3272 # Universal edit button
3273 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3274 $user = $this->getUser();
3275 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3276 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3277 // Original UniversalEditButton
3278 $msg = $this->msg( 'edit' )->text();
3279 $tags['universal-edit-button'] = Html::element( 'link', array(
3280 'rel' => 'alternate',
3281 'type' => 'application/x-wiki',
3282 'title' => $msg,
3283 'href' => $this->getTitle()->getEditURL(),
3284 ) );
3285 // Alternate edit link
3286 $tags['alternative-edit'] = Html::element( 'link', array(
3287 'rel' => 'edit',
3288 'title' => $msg,
3289 'href' => $this->getTitle()->getEditURL(),
3290 ) );
3291 }
3292 }
3293
3294 # Generally the order of the favicon and apple-touch-icon links
3295 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3296 # uses whichever one appears later in the HTML source. Make sure
3297 # apple-touch-icon is specified first to avoid this.
3298 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3299 $tags['apple-touch-icon'] = Html::element( 'link', array(
3300 'rel' => 'apple-touch-icon',
3301 'href' => $config->get( 'AppleTouchIcon' )
3302 ) );
3303 }
3304
3305 if ( $config->get( 'Favicon' ) !== false ) {
3306 $tags['favicon'] = Html::element( 'link', array(
3307 'rel' => 'shortcut icon',
3308 'href' => $config->get( 'Favicon' )
3309 ) );
3310 }
3311
3312 # OpenSearch description link
3313 $tags['opensearch'] = Html::element( 'link', array(
3314 'rel' => 'search',
3315 'type' => 'application/opensearchdescription+xml',
3316 'href' => wfScript( 'opensearch_desc' ),
3317 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3318 ) );
3319
3320 if ( $config->get( 'EnableAPI' ) ) {
3321 # Real Simple Discovery link, provides auto-discovery information
3322 # for the MediaWiki API (and potentially additional custom API
3323 # support such as WordPress or Twitter-compatible APIs for a
3324 # blogging extension, etc)
3325 $tags['rsd'] = Html::element( 'link', array(
3326 'rel' => 'EditURI',
3327 'type' => 'application/rsd+xml',
3328 // Output a protocol-relative URL here if $wgServer is protocol-relative
3329 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3330 'href' => wfExpandUrl( wfAppendQuery(
3331 wfScript( 'api' ),
3332 array( 'action' => 'rsd' ) ),
3333 PROTO_RELATIVE
3334 ),
3335 ) );
3336 }
3337
3338 # Language variants
3339 if ( !$config->get( 'DisableLangConversion' ) ) {
3340 $lang = $this->getTitle()->getPageLanguage();
3341 if ( $lang->hasVariants() ) {
3342 $variants = $lang->getVariants();
3343 foreach ( $variants as $_v ) {
3344 $tags["variant-$_v"] = Html::element( 'link', array(
3345 'rel' => 'alternate',
3346 'hreflang' => wfBCP47( $_v ),
3347 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3348 );
3349 }
3350 }
3351 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3352 $tags["variant-x-default"] = Html::element( 'link', array(
3353 'rel' => 'alternate',
3354 'hreflang' => 'x-default',
3355 'href' => $this->getTitle()->getLocalURL() ) );
3356 }
3357
3358 # Copyright
3359 $copyright = '';
3360 if ( $config->get( 'RightsPage' ) ) {
3361 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3362
3363 if ( $copy ) {
3364 $copyright = $copy->getLocalURL();
3365 }
3366 }
3367
3368 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3369 $copyright = $config->get( 'RightsUrl' );
3370 }
3371
3372 if ( $copyright ) {
3373 $tags['copyright'] = Html::element( 'link', array(
3374 'rel' => 'copyright',
3375 'href' => $copyright )
3376 );
3377 }
3378
3379 # Feeds
3380 if ( $config->get( 'Feed' ) ) {
3381 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3382 # Use the page name for the title. In principle, this could
3383 # lead to issues with having the same name for different feeds
3384 # corresponding to the same page, but we can't avoid that at
3385 # this low a level.
3386
3387 $tags[] = $this->feedLink(
3388 $format,
3389 $link,
3390 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3391 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3392 );
3393 }
3394
3395 # Recent changes feed should appear on every page (except recentchanges,
3396 # that would be redundant). Put it after the per-page feed to avoid
3397 # changing existing behavior. It's still available, probably via a
3398 # menu in your browser. Some sites might have a different feed they'd
3399 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3400 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3401 # If so, use it instead.
3402 $sitename = $config->get( 'Sitename' );
3403 if ( $config->get( 'OverrideSiteFeed' ) ) {
3404 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3405 // Note, this->feedLink escapes the url.
3406 $tags[] = $this->feedLink(
3407 $type,
3408 $feedUrl,
3409 $this->msg( "site-{$type}-feed", $sitename )->text()
3410 );
3411 }
3412 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3413 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3414 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3415 $tags[] = $this->feedLink(
3416 $format,
3417 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3418 # For grep: 'site-rss-feed', 'site-atom-feed'
3419 $this->msg( "site-{$format}-feed", $sitename )->text()
3420 );
3421 }
3422 }
3423 }
3424
3425 # Canonical URL
3426 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3427 if ( $canonicalUrl !== false ) {
3428 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3429 } else {
3430 $reqUrl = $this->getRequest()->getRequestURL();
3431 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3432 }
3433 }
3434 if ( $canonicalUrl !== false ) {
3435 $tags[] = Html::element( 'link', array(
3436 'rel' => 'canonical',
3437 'href' => $canonicalUrl
3438 ) );
3439 }
3440
3441 return $tags;
3442 }
3443
3444 /**
3445 * @return string HTML tag links to be put in the header.
3446 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3447 * OutputPage::getHeadLinksArray directly.
3448 */
3449 public function getHeadLinks() {
3450 wfDeprecated( __METHOD__, '1.24' );
3451 return implode( "\n", $this->getHeadLinksArray() );
3452 }
3453
3454 /**
3455 * Generate a "<link rel/>" for a feed.
3456 *
3457 * @param string $type Feed type
3458 * @param string $url URL to the feed
3459 * @param string $text Value of the "title" attribute
3460 * @return string HTML fragment
3461 */
3462 private function feedLink( $type, $url, $text ) {
3463 return Html::element( 'link', array(
3464 'rel' => 'alternate',
3465 'type' => "application/$type+xml",
3466 'title' => $text,
3467 'href' => $url )
3468 );
3469 }
3470
3471 /**
3472 * Add a local or specified stylesheet, with the given media options.
3473 * Meant primarily for internal use...
3474 *
3475 * @param string $style URL to the file
3476 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3477 * @param string $condition For IE conditional comments, specifying an IE version
3478 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3479 */
3480 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3481 $options = array();
3482 // Even though we expect the media type to be lowercase, but here we
3483 // force it to lowercase to be safe.
3484 if ( $media ) {
3485 $options['media'] = $media;
3486 }
3487 if ( $condition ) {
3488 $options['condition'] = $condition;
3489 }
3490 if ( $dir ) {
3491 $options['dir'] = $dir;
3492 }
3493 $this->styles[$style] = $options;
3494 }
3495
3496 /**
3497 * Adds inline CSS styles
3498 * @param mixed $style_css Inline CSS
3499 * @param string $flip Set to 'flip' to flip the CSS if needed
3500 */
3501 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3502 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3503 # If wanted, and the interface is right-to-left, flip the CSS
3504 $style_css = CSSJanus::transform( $style_css, true, false );
3505 } else {
3506 $style_css = CSSJanus::nullTransform( $style_css );
3507 }
3508 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3509 }
3510
3511 /**
3512 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3513 * These will be applied to various media & IE conditionals.
3514 *
3515 * @return string
3516 */
3517 public function buildCssLinks() {
3518 global $wgContLang;
3519
3520 $this->getSkin()->setupSkinUserCss( $this );
3521
3522 // Add ResourceLoader styles
3523 // Split the styles into these groups
3524 $styles = array(
3525 'other' => array(),
3526 'user' => array(),
3527 'site' => array(),
3528 'private' => array(),
3529 'noscript' => array()
3530 );
3531 $links = array();
3532 $otherTags = ''; // Tags to append after the normal <link> tags
3533 $resourceLoader = $this->getResourceLoader();
3534
3535 $moduleStyles = $this->getModuleStyles();
3536
3537 // Per-site custom styles
3538 $moduleStyles[] = 'site';
3539 $moduleStyles[] = 'noscript';
3540 $moduleStyles[] = 'user.groups';
3541
3542 // Per-user custom styles
3543 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3544 // We're on a preview of a CSS subpage
3545 // Exclude this page from the user module in case it's in there (bug 26283)
3546 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3547 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3548 );
3549 $otherTags .= $link['html'];
3550
3551 // Load the previewed CSS
3552 // If needed, Janus it first. This is user-supplied CSS, so it's
3553 // assumed to be right for the content language directionality.
3554 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3555 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3556 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3557 } else {
3558 $previewedCSS = CSSJanus::nullTransform( $previewedCSS );
3559 }
3560 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3561 } else {
3562 // Load the user styles normally
3563 $moduleStyles[] = 'user';
3564 }
3565
3566 // Per-user preference styles
3567 $moduleStyles[] = 'user.cssprefs';
3568
3569 foreach ( $moduleStyles as $name ) {
3570 $module = $resourceLoader->getModule( $name );
3571 if ( !$module ) {
3572 continue;
3573 }
3574 $group = $module->getGroup();
3575 // Modules in groups different than the ones listed on top (see $styles assignment)
3576 // will be placed in the "other" group
3577 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3578 }
3579
3580 // We want site, private and user styles to override dynamically added
3581 // styles from modules, but we want dynamically added styles to override
3582 // statically added styles from other modules. So the order has to be
3583 // other, dynamic, site, private, user. Add statically added styles for
3584 // other modules
3585 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3586 // Add normal styles added through addStyle()/addInlineStyle() here
3587 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3588 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3589 // We use a <meta> tag with a made-up name for this because that's valid HTML
3590 $links[] = Html::element(
3591 'meta',
3592 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3593 ) . "\n";
3594
3595 // Add site, private and user styles
3596 // 'private' at present only contains user.options, so put that before 'user'
3597 // Any future private modules will likely have a similar user-specific character
3598 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3599 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3600 ResourceLoaderModule::TYPE_STYLES
3601 );
3602 }
3603
3604 // Add stuff in $otherTags (previewed user CSS if applicable)
3605 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3606 }
3607
3608 /**
3609 * @return array
3610 */
3611 public function buildCssLinksArray() {
3612 $links = array();
3613
3614 // Add any extension CSS
3615 foreach ( $this->mExtStyles as $url ) {
3616 $this->addStyle( $url );
3617 }
3618 $this->mExtStyles = array();
3619
3620 foreach ( $this->styles as $file => $options ) {
3621 $link = $this->styleLink( $file, $options );
3622 if ( $link ) {
3623 $links[$file] = $link;
3624 }
3625 }
3626 return $links;
3627 }
3628
3629 /**
3630 * Generate \<link\> tags for stylesheets
3631 *
3632 * @param string $style URL to the file
3633 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3634 * @return string HTML fragment
3635 */
3636 protected function styleLink( $style, array $options ) {
3637 if ( isset( $options['dir'] ) ) {
3638 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3639 return '';
3640 }
3641 }
3642
3643 if ( isset( $options['media'] ) ) {
3644 $media = self::transformCssMedia( $options['media'] );
3645 if ( is_null( $media ) ) {
3646 return '';
3647 }
3648 } else {
3649 $media = 'all';
3650 }
3651
3652 if ( substr( $style, 0, 1 ) == '/' ||
3653 substr( $style, 0, 5 ) == 'http:' ||
3654 substr( $style, 0, 6 ) == 'https:' ) {
3655 $url = $style;
3656 } else {
3657 $config = $this->getConfig();
3658 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3659 }
3660
3661 $link = Html::linkedStyle( $url, $media );
3662
3663 if ( isset( $options['condition'] ) ) {
3664 $condition = htmlspecialchars( $options['condition'] );
3665 $link = "<!--[if $condition]>$link<![endif]-->";
3666 }
3667 return $link;
3668 }
3669
3670 /**
3671 * Transform "media" attribute based on request parameters
3672 *
3673 * @param string $media Current value of the "media" attribute
3674 * @return string Modified value of the "media" attribute, or null to skip
3675 * this stylesheet
3676 */
3677 public static function transformCssMedia( $media ) {
3678 global $wgRequest;
3679
3680 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3681 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3682
3683 // Switch in on-screen display for media testing
3684 $switches = array(
3685 'printable' => 'print',
3686 'handheld' => 'handheld',
3687 );
3688 foreach ( $switches as $switch => $targetMedia ) {
3689 if ( $wgRequest->getBool( $switch ) ) {
3690 if ( $media == $targetMedia ) {
3691 $media = '';
3692 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3693 // This regex will not attempt to understand a comma-separated media_query_list
3694 //
3695 // Example supported values for $media:
3696 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3697 // Example NOT supported value for $media:
3698 // '3d-glasses, screen, print and resolution > 90dpi'
3699 //
3700 // If it's a print request, we never want any kind of screen stylesheets
3701 // If it's a handheld request (currently the only other choice with a switch),
3702 // we don't want simple 'screen' but we might want screen queries that
3703 // have a max-width or something, so we'll pass all others on and let the
3704 // client do the query.
3705 if ( $targetMedia == 'print' || $media == 'screen' ) {
3706 return null;
3707 }
3708 }
3709 }
3710 }
3711
3712 return $media;
3713 }
3714
3715 /**
3716 * Add a wikitext-formatted message to the output.
3717 * This is equivalent to:
3718 *
3719 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3720 */
3721 public function addWikiMsg( /*...*/ ) {
3722 $args = func_get_args();
3723 $name = array_shift( $args );
3724 $this->addWikiMsgArray( $name, $args );
3725 }
3726
3727 /**
3728 * Add a wikitext-formatted message to the output.
3729 * Like addWikiMsg() except the parameters are taken as an array
3730 * instead of a variable argument list.
3731 *
3732 * @param string $name
3733 * @param array $args
3734 */
3735 public function addWikiMsgArray( $name, $args ) {
3736 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3737 }
3738
3739 /**
3740 * This function takes a number of message/argument specifications, wraps them in
3741 * some overall structure, and then parses the result and adds it to the output.
3742 *
3743 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3744 * on. The subsequent arguments may either be strings, in which case they are the
3745 * message names, or arrays, in which case the first element is the message name,
3746 * and subsequent elements are the parameters to that message.
3747 *
3748 * Don't use this for messages that are not in users interface language.
3749 *
3750 * For example:
3751 *
3752 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3753 *
3754 * Is equivalent to:
3755 *
3756 * $wgOut->addWikiText( "<div class='error'>\n"
3757 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3758 *
3759 * The newline after opening div is needed in some wikitext. See bug 19226.
3760 *
3761 * @param string $wrap
3762 */
3763 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3764 $msgSpecs = func_get_args();
3765 array_shift( $msgSpecs );
3766 $msgSpecs = array_values( $msgSpecs );
3767 $s = $wrap;
3768 foreach ( $msgSpecs as $n => $spec ) {
3769 if ( is_array( $spec ) ) {
3770 $args = $spec;
3771 $name = array_shift( $args );
3772 if ( isset( $args['options'] ) ) {
3773 unset( $args['options'] );
3774 wfDeprecated(
3775 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3776 '1.20'
3777 );
3778 }
3779 } else {
3780 $args = array();
3781 $name = $spec;
3782 }
3783 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3784 }
3785 $this->addWikiText( $s );
3786 }
3787
3788 /**
3789 * Include jQuery core. Use this to avoid loading it multiple times
3790 * before we get a usable script loader.
3791 *
3792 * @param array $modules List of jQuery modules which should be loaded
3793 * @return array The list of modules which were not loaded.
3794 * @since 1.16
3795 * @deprecated since 1.17
3796 */
3797 public function includeJQuery( array $modules = array() ) {
3798 return array();
3799 }
3800
3801 /**
3802 * Enables/disables TOC, doesn't override __NOTOC__
3803 * @param bool $flag
3804 * @since 1.22
3805 */
3806 public function enableTOC( $flag = true ) {
3807 $this->mEnableTOC = $flag;
3808 }
3809
3810 /**
3811 * @return bool
3812 * @since 1.22
3813 */
3814 public function isTOCEnabled() {
3815 return $this->mEnableTOC;
3816 }
3817
3818 /**
3819 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3820 * @param bool $flag
3821 * @since 1.23
3822 */
3823 public function enableSectionEditLinks( $flag = true ) {
3824 $this->mEnableSectionEditLinks = $flag;
3825 }
3826
3827 /**
3828 * @return bool
3829 * @since 1.23
3830 */
3831 public function sectionEditLinksEnabled() {
3832 return $this->mEnableSectionEditLinks;
3833 }
3834 }