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