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