Merge "PPAccum_Hash -> PPDAccum_Hash"
[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
1752 $m = array();
1753 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1754 $parsed = $m[1];
1755 }
1756
1757 return $parsed;
1758 }
1759
1760 /**
1761 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1762 *
1763 * @param int $maxage Maximum cache time on the Squid, in seconds.
1764 */
1765 public function setSquidMaxage( $maxage ) {
1766 $this->mSquidMaxage = $maxage;
1767 }
1768
1769 /**
1770 * Use enableClientCache(false) to force it to send nocache headers
1771 *
1772 * @param bool $state
1773 *
1774 * @return bool
1775 */
1776 public function enableClientCache( $state ) {
1777 return wfSetVar( $this->mEnableClientCache, $state );
1778 }
1779
1780 /**
1781 * Get the list of cookies that will influence on the cache
1782 *
1783 * @return array
1784 */
1785 function getCacheVaryCookies() {
1786 global $wgCookiePrefix, $wgCacheVaryCookies;
1787 static $cookies;
1788 if ( $cookies === null ) {
1789 $cookies = array_merge(
1790 array(
1791 "{$wgCookiePrefix}Token",
1792 "{$wgCookiePrefix}LoggedOut",
1793 "forceHTTPS",
1794 session_name()
1795 ),
1796 $wgCacheVaryCookies
1797 );
1798 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1799 }
1800 return $cookies;
1801 }
1802
1803 /**
1804 * Check if the request has a cache-varying cookie header
1805 * If it does, it's very important that we don't allow public caching
1806 *
1807 * @return bool
1808 */
1809 function haveCacheVaryCookies() {
1810 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1811 if ( $cookieHeader === false ) {
1812 return false;
1813 }
1814 $cvCookies = $this->getCacheVaryCookies();
1815 foreach ( $cvCookies as $cookieName ) {
1816 # Check for a simple string match, like the way squid does it
1817 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1818 wfDebug( __METHOD__ . ": found $cookieName\n" );
1819 return true;
1820 }
1821 }
1822 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1823 return false;
1824 }
1825
1826 /**
1827 * Add an HTTP header that will influence on the cache
1828 *
1829 * @param string $header header name
1830 * @param array|null $option
1831 * @todo FIXME: Document the $option parameter; it appears to be for
1832 * X-Vary-Options but what format is acceptable?
1833 */
1834 public function addVaryHeader( $header, $option = null ) {
1835 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1836 $this->mVaryHeader[$header] = (array)$option;
1837 } elseif ( is_array( $option ) ) {
1838 if ( is_array( $this->mVaryHeader[$header] ) ) {
1839 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1840 } else {
1841 $this->mVaryHeader[$header] = $option;
1842 }
1843 }
1844 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1845 }
1846
1847 /**
1848 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1849 * such as Accept-Encoding or Cookie
1850 *
1851 * @return string
1852 */
1853 public function getVaryHeader() {
1854 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1855 }
1856
1857 /**
1858 * Get a complete X-Vary-Options header
1859 *
1860 * @return string
1861 */
1862 public function getXVO() {
1863 $cvCookies = $this->getCacheVaryCookies();
1864
1865 $cookiesOption = array();
1866 foreach ( $cvCookies as $cookieName ) {
1867 $cookiesOption[] = 'string-contains=' . $cookieName;
1868 }
1869 $this->addVaryHeader( 'Cookie', $cookiesOption );
1870
1871 $headers = array();
1872 foreach ( $this->mVaryHeader as $header => $option ) {
1873 $newheader = $header;
1874 if ( is_array( $option ) && count( $option ) > 0 ) {
1875 $newheader .= ';' . implode( ';', $option );
1876 }
1877 $headers[] = $newheader;
1878 }
1879 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1880
1881 return $xvo;
1882 }
1883
1884 /**
1885 * bug 21672: Add Accept-Language to Vary and XVO headers
1886 * if there's no 'variant' parameter existed in GET.
1887 *
1888 * For example:
1889 * /w/index.php?title=Main_page should always be served; but
1890 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1891 */
1892 function addAcceptLanguage() {
1893 $lang = $this->getTitle()->getPageLanguage();
1894 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1895 $variants = $lang->getVariants();
1896 $aloption = array();
1897 foreach ( $variants as $variant ) {
1898 if ( $variant === $lang->getCode() ) {
1899 continue;
1900 } else {
1901 $aloption[] = 'string-contains=' . $variant;
1902
1903 // IE and some other browsers use BCP 47 standards in
1904 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1905 // We should handle these too.
1906 $variantBCP47 = wfBCP47( $variant );
1907 if ( $variantBCP47 !== $variant ) {
1908 $aloption[] = 'string-contains=' . $variantBCP47;
1909 }
1910 }
1911 }
1912 $this->addVaryHeader( 'Accept-Language', $aloption );
1913 }
1914 }
1915
1916 /**
1917 * Set a flag which will cause an X-Frame-Options header appropriate for
1918 * edit pages to be sent. The header value is controlled by
1919 * $wgEditPageFrameOptions.
1920 *
1921 * This is the default for special pages. If you display a CSRF-protected
1922 * form on an ordinary view page, then you need to call this function.
1923 *
1924 * @param bool $enable
1925 */
1926 public function preventClickjacking( $enable = true ) {
1927 $this->mPreventClickjacking = $enable;
1928 }
1929
1930 /**
1931 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1932 * This can be called from pages which do not contain any CSRF-protected
1933 * HTML form.
1934 */
1935 public function allowClickjacking() {
1936 $this->mPreventClickjacking = false;
1937 }
1938
1939 /**
1940 * Get the X-Frame-Options header value (without the name part), or false
1941 * if there isn't one. This is used by Skin to determine whether to enable
1942 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1943 *
1944 * @return string
1945 */
1946 public function getFrameOptions() {
1947 global $wgBreakFrames, $wgEditPageFrameOptions;
1948 if ( $wgBreakFrames ) {
1949 return 'DENY';
1950 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1951 return $wgEditPageFrameOptions;
1952 }
1953 return false;
1954 }
1955
1956 /**
1957 * Send cache control HTTP headers
1958 */
1959 public function sendCacheControl() {
1960 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1961
1962 $response = $this->getRequest()->response();
1963 if ( $wgUseETag && $this->mETag ) {
1964 $response->header( "ETag: $this->mETag" );
1965 }
1966
1967 $this->addVaryHeader( 'Cookie' );
1968 $this->addAcceptLanguage();
1969
1970 # don't serve compressed data to clients who can't handle it
1971 # maintain different caches for logged-in users and non-logged in ones
1972 $response->header( $this->getVaryHeader() );
1973
1974 if ( $wgUseXVO ) {
1975 # Add an X-Vary-Options header for Squid with Wikimedia patches
1976 $response->header( $this->getXVO() );
1977 }
1978
1979 if ( $this->mEnableClientCache ) {
1980 if (
1981 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1982 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1983 ) {
1984 if ( $wgUseESI ) {
1985 # We'll purge the proxy cache explicitly, but require end user agents
1986 # to revalidate against the proxy on each visit.
1987 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1988 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
1989 # start with a shorter timeout for initial testing
1990 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1991 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage
1992 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
1993 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1994 } else {
1995 # We'll purge the proxy cache for anons explicitly, but require end user agents
1996 # to revalidate against the proxy on each visit.
1997 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1998 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1999 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2000 # start with a shorter timeout for initial testing
2001 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2002 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2003 . ', must-revalidate, max-age=0' );
2004 }
2005 } else {
2006 # We do want clients to cache if they can, but they *must* check for updates
2007 # on revisiting the page.
2008 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2009 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2010 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2011 }
2012 if ( $this->mLastModified ) {
2013 $response->header( "Last-Modified: {$this->mLastModified}" );
2014 }
2015 } else {
2016 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2017
2018 # In general, the absence of a last modified header should be enough to prevent
2019 # the client from using its cache. We send a few other things just to make sure.
2020 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2021 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2022 $response->header( 'Pragma: no-cache' );
2023 }
2024 }
2025
2026 /**
2027 * Get the message associated with the HTTP response code $code
2028 *
2029 * @param int $code Status code
2030 * @return string|null Message or null if $code is not in the list of messages
2031 *
2032 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
2033 */
2034 public static function getStatusMessage( $code ) {
2035 wfDeprecated( __METHOD__, '1.18' );
2036 return HttpStatus::getMessage( $code );
2037 }
2038
2039 /**
2040 * Finally, all the text has been munged and accumulated into
2041 * the object, let's actually output it:
2042 */
2043 public function output() {
2044 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
2045 $wgUseAjax, $wgResponsiveImages;
2046
2047 if ( $this->mDoNothing ) {
2048 return;
2049 }
2050
2051 wfProfileIn( __METHOD__ );
2052
2053 $response = $this->getRequest()->response();
2054
2055 if ( $this->mRedirect != '' ) {
2056 # Standards require redirect URLs to be absolute
2057 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2058
2059 $redirect = $this->mRedirect;
2060 $code = $this->mRedirectCode;
2061
2062 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2063 if ( $code == '301' || $code == '303' ) {
2064 if ( !$wgDebugRedirects ) {
2065 $message = HttpStatus::getMessage( $code );
2066 $response->header( "HTTP/1.1 $code $message" );
2067 }
2068 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2069 }
2070 if ( $wgVaryOnXFP ) {
2071 $this->addVaryHeader( 'X-Forwarded-Proto' );
2072 }
2073 $this->sendCacheControl();
2074
2075 $response->header( "Content-Type: text/html; charset=utf-8" );
2076 if ( $wgDebugRedirects ) {
2077 $url = htmlspecialchars( $redirect );
2078 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2079 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2080 print "</body>\n</html>\n";
2081 } else {
2082 $response->header( 'Location: ' . $redirect );
2083 }
2084 }
2085
2086 wfProfileOut( __METHOD__ );
2087 return;
2088 } elseif ( $this->mStatusCode ) {
2089 $message = HttpStatus::getMessage( $this->mStatusCode );
2090 if ( $message ) {
2091 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2092 }
2093 }
2094
2095 # Buffer output; final headers may depend on later processing
2096 ob_start();
2097
2098 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2099 $response->header( 'Content-language: ' . $wgLanguageCode );
2100
2101 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2102 // jQuery etc. can work correctly.
2103 $response->header( 'X-UA-Compatible: IE=Edge' );
2104
2105 // Prevent framing, if requested
2106 $frameOptions = $this->getFrameOptions();
2107 if ( $frameOptions ) {
2108 $response->header( "X-Frame-Options: $frameOptions" );
2109 }
2110
2111 if ( $this->mArticleBodyOnly ) {
2112 echo $this->mBodytext;
2113 } else {
2114
2115 $sk = $this->getSkin();
2116 // add skin specific modules
2117 $modules = $sk->getDefaultModules();
2118
2119 // enforce various default modules for all skins
2120 $coreModules = array(
2121 // keep this list as small as possible
2122 'mediawiki.page.startup',
2123 'mediawiki.user',
2124 );
2125
2126 // Support for high-density display images if enabled
2127 if ( $wgResponsiveImages ) {
2128 $coreModules[] = 'mediawiki.hidpi';
2129 }
2130
2131 $this->addModules( $coreModules );
2132 foreach ( $modules as $group ) {
2133 $this->addModules( $group );
2134 }
2135 MWDebug::addModules( $this );
2136 if ( $wgUseAjax ) {
2137 // FIXME: deprecate? - not clear why this is useful
2138 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2139 }
2140
2141 // Hook that allows last minute changes to the output page, e.g.
2142 // adding of CSS or Javascript by extensions.
2143 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2144
2145 wfProfileIn( 'Output-skin' );
2146 $sk->outputPage();
2147 wfProfileOut( 'Output-skin' );
2148 }
2149
2150 // This hook allows last minute changes to final overall output by modifying output buffer
2151 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2152
2153 $this->sendCacheControl();
2154
2155 ob_end_flush();
2156
2157 wfProfileOut( __METHOD__ );
2158 }
2159
2160 /**
2161 * Actually output something with print.
2162 *
2163 * @param string $ins the string to output
2164 * @deprecated since 1.22 Use echo yourself.
2165 */
2166 public function out( $ins ) {
2167 wfDeprecated( __METHOD__, '1.22' );
2168 print $ins;
2169 }
2170
2171 /**
2172 * Produce a "user is blocked" page.
2173 * @deprecated since 1.18
2174 */
2175 function blockedPage() {
2176 throw new UserBlockedError( $this->getUser()->mBlock );
2177 }
2178
2179 /**
2180 * Prepare this object to display an error page; disable caching and
2181 * indexing, clear the current text and redirect, set the page's title
2182 * and optionally an custom HTML title (content of the "<title>" tag).
2183 *
2184 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2185 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2186 * optional, if not passed the "<title>" attribute will be
2187 * based on $pageTitle
2188 */
2189 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2190 $this->setPageTitle( $pageTitle );
2191 if ( $htmlTitle !== false ) {
2192 $this->setHTMLTitle( $htmlTitle );
2193 }
2194 $this->setRobotPolicy( 'noindex,nofollow' );
2195 $this->setArticleRelated( false );
2196 $this->enableClientCache( false );
2197 $this->mRedirect = '';
2198 $this->clearSubtitle();
2199 $this->clearHTML();
2200 }
2201
2202 /**
2203 * Output a standard error page
2204 *
2205 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2206 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2207 * showErrorPage( 'titlemsg', $messageObject );
2208 * showErrorPage( $titleMessageObject, $messageObject );
2209 *
2210 * @param string|Message $title Message key (string) for page title, or a Message object
2211 * @param string|Message $msg Message key (string) for page text, or a Message object
2212 * @param array $params Message parameters; ignored if $msg is a Message object
2213 */
2214 public function showErrorPage( $title, $msg, $params = array() ) {
2215 if ( !$title instanceof Message ) {
2216 $title = $this->msg( $title );
2217 }
2218
2219 $this->prepareErrorPage( $title );
2220
2221 if ( $msg instanceof Message ) {
2222 if ( $params !== array() ) {
2223 trigger_error( 'Argument ignored: $params. The message parameters argument '
2224 . 'is discarded when the $msg argument is a Message object instead of '
2225 . 'a string.', E_USER_NOTICE );
2226 }
2227 $this->addHTML( $msg->parseAsBlock() );
2228 } else {
2229 $this->addWikiMsgArray( $msg, $params );
2230 }
2231
2232 $this->returnToMain();
2233 }
2234
2235 /**
2236 * Output a standard permission error page
2237 *
2238 * @param array $errors error message keys
2239 * @param string $action action that was denied or null if unknown
2240 */
2241 public function showPermissionsErrorPage( $errors, $action = null ) {
2242 // For some action (read, edit, create and upload), display a "login to do this action"
2243 // error if all of the following conditions are met:
2244 // 1. the user is not logged in
2245 // 2. the only error is insufficient permissions (i.e. no block or something else)
2246 // 3. the error can be avoided simply by logging in
2247 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2248 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2249 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2250 && ( User::groupHasPermission( 'user', $action )
2251 || User::groupHasPermission( 'autoconfirmed', $action ) )
2252 ) {
2253 $displayReturnto = null;
2254
2255 # Due to bug 32276, if a user does not have read permissions,
2256 # $this->getTitle() will just give Special:Badtitle, which is
2257 # not especially useful as a returnto parameter. Use the title
2258 # from the request instead, if there was one.
2259 $request = $this->getRequest();
2260 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2261 if ( $action == 'edit' ) {
2262 $msg = 'whitelistedittext';
2263 $displayReturnto = $returnto;
2264 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2265 $msg = 'nocreatetext';
2266 } elseif ( $action == 'upload' ) {
2267 $msg = 'uploadnologintext';
2268 } else { # Read
2269 $msg = 'loginreqpagetext';
2270 $displayReturnto = Title::newMainPage();
2271 }
2272
2273 $query = array();
2274
2275 if ( $returnto ) {
2276 $query['returnto'] = $returnto->getPrefixedText();
2277
2278 if ( !$request->wasPosted() ) {
2279 $returntoquery = $request->getValues();
2280 unset( $returntoquery['title'] );
2281 unset( $returntoquery['returnto'] );
2282 unset( $returntoquery['returntoquery'] );
2283 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2284 }
2285 }
2286 $loginLink = Linker::linkKnown(
2287 SpecialPage::getTitleFor( 'Userlogin' ),
2288 $this->msg( 'loginreqlink' )->escaped(),
2289 array(),
2290 $query
2291 );
2292
2293 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2294 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2295
2296 # Don't return to a page the user can't read otherwise
2297 # we'll end up in a pointless loop
2298 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2299 $this->returnToMain( null, $displayReturnto );
2300 }
2301 } else {
2302 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2303 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2304 }
2305 }
2306
2307 /**
2308 * Display an error page indicating that a given version of MediaWiki is
2309 * required to use it
2310 *
2311 * @param mixed $version The version of MediaWiki needed to use the page
2312 */
2313 public function versionRequired( $version ) {
2314 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2315
2316 $this->addWikiMsg( 'versionrequiredtext', $version );
2317 $this->returnToMain();
2318 }
2319
2320 /**
2321 * Display an error page noting that a given permission bit is required.
2322 * @deprecated since 1.18, just throw the exception directly
2323 * @param string $permission key required
2324 * @throws PermissionsError
2325 */
2326 public function permissionRequired( $permission ) {
2327 throw new PermissionsError( $permission );
2328 }
2329
2330 /**
2331 * Produce the stock "please login to use the wiki" page
2332 *
2333 * @deprecated since 1.19; throw the exception directly
2334 */
2335 public function loginToUse() {
2336 throw new PermissionsError( 'read' );
2337 }
2338
2339 /**
2340 * Format a list of error messages
2341 *
2342 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2343 * @param string $action Action that was denied or null if unknown
2344 * @return string The wikitext error-messages, formatted into a list.
2345 */
2346 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2347 if ( $action == null ) {
2348 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2349 } else {
2350 $action_desc = $this->msg( "action-$action" )->plain();
2351 $text = $this->msg(
2352 'permissionserrorstext-withaction',
2353 count( $errors ),
2354 $action_desc
2355 )->plain() . "\n\n";
2356 }
2357
2358 if ( count( $errors ) > 1 ) {
2359 $text .= '<ul class="permissions-errors">' . "\n";
2360
2361 foreach ( $errors as $error ) {
2362 $text .= '<li>';
2363 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2364 $text .= "</li>\n";
2365 }
2366 $text .= '</ul>';
2367 } else {
2368 $text .= "<div class=\"permissions-errors\">\n" .
2369 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2370 "\n</div>";
2371 }
2372
2373 return $text;
2374 }
2375
2376 /**
2377 * Display a page stating that the Wiki is in read-only mode,
2378 * and optionally show the source of the page that the user
2379 * was trying to edit. Should only be called (for this
2380 * purpose) after wfReadOnly() has returned true.
2381 *
2382 * For historical reasons, this function is _also_ used to
2383 * show the error message when a user tries to edit a page
2384 * they are not allowed to edit. (Unless it's because they're
2385 * blocked, then we show blockedPage() instead.) In this
2386 * case, the second parameter should be set to true and a list
2387 * of reasons supplied as the third parameter.
2388 *
2389 * @todo Needs to be split into multiple functions.
2390 *
2391 * @param string $source Source code to show (or null).
2392 * @param bool $protected Is this a permissions error?
2393 * @param array $reasons List of reasons for this error, as returned by
2394 * Title::getUserPermissionsErrors().
2395 * @param string $action Action that was denied or null if unknown
2396 * @throws ReadOnlyError
2397 */
2398 public function readOnlyPage( $source = null, $protected = false,
2399 $reasons = array(), $action = null
2400 ) {
2401 $this->setRobotPolicy( 'noindex,nofollow' );
2402 $this->setArticleRelated( false );
2403
2404 // If no reason is given, just supply a default "I can't let you do
2405 // that, Dave" message. Should only occur if called by legacy code.
2406 if ( $protected && empty( $reasons ) ) {
2407 $reasons[] = array( 'badaccess-group0' );
2408 }
2409
2410 if ( !empty( $reasons ) ) {
2411 // Permissions error
2412 if ( $source ) {
2413 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2414 $this->addBacklinkSubtitle( $this->getTitle() );
2415 } else {
2416 $this->setPageTitle( $this->msg( 'badaccess' ) );
2417 }
2418 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2419 } else {
2420 // Wiki is read only
2421 throw new ReadOnlyError;
2422 }
2423
2424 // Show source, if supplied
2425 if ( is_string( $source ) ) {
2426 $this->addWikiMsg( 'viewsourcetext' );
2427
2428 $pageLang = $this->getTitle()->getPageLanguage();
2429 $params = array(
2430 'id' => 'wpTextbox1',
2431 'name' => 'wpTextbox1',
2432 'cols' => $this->getUser()->getOption( 'cols' ),
2433 'rows' => $this->getUser()->getOption( 'rows' ),
2434 'readonly' => 'readonly',
2435 'lang' => $pageLang->getHtmlCode(),
2436 'dir' => $pageLang->getDir(),
2437 );
2438 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2439
2440 // Show templates used by this article
2441 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2442 $this->addHTML( "<div class='templatesUsed'>
2443 $templates
2444 </div>
2445 " );
2446 }
2447
2448 # If the title doesn't exist, it's fairly pointless to print a return
2449 # link to it. After all, you just tried editing it and couldn't, so
2450 # what's there to do there?
2451 if ( $this->getTitle()->exists() ) {
2452 $this->returnToMain( null, $this->getTitle() );
2453 }
2454 }
2455
2456 /**
2457 * Turn off regular page output and return an error response
2458 * for when rate limiting has triggered.
2459 */
2460 public function rateLimited() {
2461 throw new ThrottledError;
2462 }
2463
2464 /**
2465 * Show a warning about slave lag
2466 *
2467 * If the lag is higher than $wgSlaveLagCritical seconds,
2468 * then the warning is a bit more obvious. If the lag is
2469 * lower than $wgSlaveLagWarning, then no warning is shown.
2470 *
2471 * @param int $lag Slave lag
2472 */
2473 public function showLagWarning( $lag ) {
2474 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2475 if ( $lag >= $wgSlaveLagWarning ) {
2476 $message = $lag < $wgSlaveLagCritical
2477 ? 'lag-warn-normal'
2478 : 'lag-warn-high';
2479 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2480 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2481 }
2482 }
2483
2484 public function showFatalError( $message ) {
2485 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2486
2487 $this->addHTML( $message );
2488 }
2489
2490 public function showUnexpectedValueError( $name, $val ) {
2491 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2492 }
2493
2494 public function showFileCopyError( $old, $new ) {
2495 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2496 }
2497
2498 public function showFileRenameError( $old, $new ) {
2499 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2500 }
2501
2502 public function showFileDeleteError( $name ) {
2503 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2504 }
2505
2506 public function showFileNotFoundError( $name ) {
2507 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2508 }
2509
2510 /**
2511 * Add a "return to" link pointing to a specified title
2512 *
2513 * @param Title $title Title to link
2514 * @param array $query Query string parameters
2515 * @param string $text Text of the link (input is not escaped)
2516 * @param array $options Options array to pass to Linker
2517 */
2518 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2519 $link = $this->msg( 'returnto' )->rawParams(
2520 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2521 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2522 }
2523
2524 /**
2525 * Add a "return to" link pointing to a specified title,
2526 * or the title indicated in the request, or else the main page
2527 *
2528 * @param mixed $unused
2529 * @param Title|string $returnto Title or String to return to
2530 * @param string $returntoquery Query string for the return to link
2531 */
2532 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2533 if ( $returnto == null ) {
2534 $returnto = $this->getRequest()->getText( 'returnto' );
2535 }
2536
2537 if ( $returntoquery == null ) {
2538 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2539 }
2540
2541 if ( $returnto === '' ) {
2542 $returnto = Title::newMainPage();
2543 }
2544
2545 if ( is_object( $returnto ) ) {
2546 $titleObj = $returnto;
2547 } else {
2548 $titleObj = Title::newFromText( $returnto );
2549 }
2550 if ( !is_object( $titleObj ) ) {
2551 $titleObj = Title::newMainPage();
2552 }
2553
2554 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2555 }
2556
2557 /**
2558 * @param Skin $sk The given Skin
2559 * @param bool $includeStyle Unused
2560 * @return string The doctype, opening "<html>", and head element.
2561 */
2562 public function headElement( Skin $sk, $includeStyle = true ) {
2563 global $wgContLang, $wgMimeType;
2564
2565 $userdir = $this->getLanguage()->getDir();
2566 $sitedir = $wgContLang->getDir();
2567
2568 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2569
2570 if ( $this->getHTMLTitle() == '' ) {
2571 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2572 }
2573
2574 $openHead = Html::openElement( 'head' );
2575 if ( $openHead ) {
2576 # Don't bother with the newline if $head == ''
2577 $ret .= "$openHead\n";
2578 }
2579
2580 if ( !Html::isXmlMimeType( $wgMimeType ) ) {
2581 // Add <meta charset="UTF-8">
2582 // This should be before <title> since it defines the charset used by
2583 // text including the text inside <title>.
2584 // The spec recommends defining XHTML5's charset using the XML declaration
2585 // instead of meta.
2586 // Our XML declaration is output by Html::htmlHeader.
2587 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2588 // http://www.whatwg.org/html/semantics.html#charset
2589 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2590 }
2591
2592 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2593
2594 $ret .= (
2595 $this->getHeadLinks() .
2596 "\n" .
2597 $this->buildCssLinks() .
2598 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2599 $this->getHeadScripts() .
2600 "\n" .
2601 $this->getHeadItems()
2602 );
2603
2604 $closeHead = Html::closeElement( 'head' );
2605 if ( $closeHead ) {
2606 $ret .= "$closeHead\n";
2607 }
2608
2609 $bodyClasses = array();
2610 $bodyClasses[] = 'mediawiki';
2611
2612 # Classes for LTR/RTL directionality support
2613 $bodyClasses[] = $userdir;
2614 $bodyClasses[] = "sitedir-$sitedir";
2615
2616 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2617 # A <body> class is probably not the best way to do this . . .
2618 $bodyClasses[] = 'capitalize-all-nouns';
2619 }
2620
2621 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2622 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2623 $bodyClasses[] =
2624 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2625
2626 $bodyAttrs = array();
2627 // While the implode() is not strictly needed, it's used for backwards compatibility
2628 // (this used to be built as a string and hooks likely still expect that).
2629 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2630
2631 // Allow skins and extensions to add body attributes they need
2632 $sk->addToBodyAttributes( $this, $bodyAttrs );
2633 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2634
2635 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2636
2637 return $ret;
2638 }
2639
2640 /**
2641 * Get a ResourceLoader object associated with this OutputPage
2642 *
2643 * @return ResourceLoader
2644 */
2645 public function getResourceLoader() {
2646 if ( is_null( $this->mResourceLoader ) ) {
2647 $this->mResourceLoader = new ResourceLoader();
2648 }
2649 return $this->mResourceLoader;
2650 }
2651
2652 /**
2653 * @todo Document
2654 * @param array|string $modules One or more module names
2655 * @param string $only ResourceLoaderModule TYPE_ class constant
2656 * @param bool $useESI
2657 * @param array $extraQuery Array with extra query parameters to add to each
2658 * request. array( param => value ).
2659 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2660 * call rather than a "<script src='...'>" tag.
2661 * @return string The html "<script>", "<link>" and "<style>" tags
2662 */
2663 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2664 array $extraQuery = array(), $loadCall = false
2665 ) {
2666 global $wgResourceLoaderUseESI;
2667
2668 $modules = (array)$modules;
2669
2670 $links = array(
2671 'html' => '',
2672 'states' => array(),
2673 );
2674
2675 if ( !count( $modules ) ) {
2676 return $links;
2677 }
2678
2679 if ( count( $modules ) > 1 ) {
2680 // Remove duplicate module requests
2681 $modules = array_unique( $modules );
2682 // Sort module names so requests are more uniform
2683 sort( $modules );
2684
2685 if ( ResourceLoader::inDebugMode() ) {
2686 // Recursively call us for every item
2687 foreach ( $modules as $name ) {
2688 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2689 $links['html'] .= $link['html'];
2690 $links['states'] += $link['states'];
2691 }
2692 return $links;
2693 }
2694 }
2695
2696 if ( !is_null( $this->mTarget ) ) {
2697 $extraQuery['target'] = $this->mTarget;
2698 }
2699
2700 // Create keyed-by-group list of module objects from modules list
2701 $groups = array();
2702 $resourceLoader = $this->getResourceLoader();
2703 foreach ( $modules as $name ) {
2704 $module = $resourceLoader->getModule( $name );
2705 # Check that we're allowed to include this module on this page
2706 if ( !$module
2707 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2708 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2709 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2710 && $only == ResourceLoaderModule::TYPE_STYLES )
2711 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2712 ) {
2713 continue;
2714 }
2715
2716 $group = $module->getGroup();
2717 if ( !isset( $groups[$group] ) ) {
2718 $groups[$group] = array();
2719 }
2720 $groups[$group][$name] = $module;
2721 }
2722
2723 foreach ( $groups as $group => $grpModules ) {
2724 // Special handling for user-specific groups
2725 $user = null;
2726 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2727 $user = $this->getUser()->getName();
2728 }
2729
2730 // Create a fake request based on the one we are about to make so modules return
2731 // correct timestamp and emptiness data
2732 $query = ResourceLoader::makeLoaderQuery(
2733 array(), // modules; not determined yet
2734 $this->getLanguage()->getCode(),
2735 $this->getSkin()->getSkinName(),
2736 $user,
2737 null, // version; not determined yet
2738 ResourceLoader::inDebugMode(),
2739 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2740 $this->isPrintable(),
2741 $this->getRequest()->getBool( 'handheld' ),
2742 $extraQuery
2743 );
2744 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2745
2746 // Extract modules that know they're empty
2747 foreach ( $grpModules as $key => $module ) {
2748 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2749 // If we're only getting the styles, we don't need to do anything for empty modules.
2750 if ( $module->isKnownEmpty( $context ) ) {
2751 unset( $grpModules[$key] );
2752 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2753 $links['states'][$key] = 'ready';
2754 }
2755 }
2756 }
2757
2758 // If there are no non-empty modules, skip this group
2759 if ( count( $grpModules ) === 0 ) {
2760 continue;
2761 }
2762
2763 // Inline private modules. These can't be loaded through load.php for security
2764 // reasons, see bug 34907. Note that these modules should be loaded from
2765 // getHeadScripts() before the first loader call. Otherwise other modules can't
2766 // properly use them as dependencies (bug 30914)
2767 if ( $group === 'private' ) {
2768 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2769 $links['html'] .= Html::inlineStyle(
2770 $resourceLoader->makeModuleResponse( $context, $grpModules )
2771 );
2772 } else {
2773 $links['html'] .= Html::inlineScript(
2774 ResourceLoader::makeLoaderConditionalScript(
2775 $resourceLoader->makeModuleResponse( $context, $grpModules )
2776 )
2777 );
2778 }
2779 $links['html'] .= "\n";
2780 continue;
2781 }
2782
2783 // Special handling for the user group; because users might change their stuff
2784 // on-wiki like user pages, or user preferences; we need to find the highest
2785 // timestamp of these user-changeable modules so we can ensure cache misses on change
2786 // This should NOT be done for the site group (bug 27564) because anons get that too
2787 // and we shouldn't be putting timestamps in Squid-cached HTML
2788 $version = null;
2789 if ( $group === 'user' ) {
2790 // Get the maximum timestamp
2791 $timestamp = 1;
2792 foreach ( $grpModules as $module ) {
2793 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2794 }
2795 // Add a version parameter so cache will break when things change
2796 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2797 }
2798
2799 $url = ResourceLoader::makeLoaderURL(
2800 array_keys( $grpModules ),
2801 $this->getLanguage()->getCode(),
2802 $this->getSkin()->getSkinName(),
2803 $user,
2804 $version,
2805 ResourceLoader::inDebugMode(),
2806 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2807 $this->isPrintable(),
2808 $this->getRequest()->getBool( 'handheld' ),
2809 $extraQuery
2810 );
2811 if ( $useESI && $wgResourceLoaderUseESI ) {
2812 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2813 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2814 $link = Html::inlineStyle( $esi );
2815 } else {
2816 $link = Html::inlineScript( $esi );
2817 }
2818 } else {
2819 // Automatically select style/script elements
2820 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2821 $link = Html::linkedStyle( $url );
2822 } elseif ( $loadCall ) {
2823 $link = Html::inlineScript(
2824 ResourceLoader::makeLoaderConditionalScript(
2825 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2826 )
2827 );
2828 } else {
2829 $link = Html::linkedScript( $url );
2830
2831 // For modules requested directly in the html via <link> or <script>,
2832 // tell mw.loader they are being loading to prevent duplicate requests.
2833 foreach ( $grpModules as $key => $module ) {
2834 // Don't output state=loading for the startup module..
2835 if ( $key !== 'startup' ) {
2836 $links['states'][$key] = 'loading';
2837 }
2838 }
2839 }
2840 }
2841
2842 if ( $group == 'noscript' ) {
2843 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2844 } else {
2845 $links['html'] .= $link . "\n";
2846 }
2847 }
2848
2849 return $links;
2850 }
2851
2852 /**
2853 * Build html output from an array of links from makeResourceLoaderLink.
2854 * @param array $links
2855 * @return string HTML
2856 */
2857 protected static function getHtmlFromLoaderLinks( Array $links ) {
2858 $html = '';
2859 $states = array();
2860 foreach ( $links as $link ) {
2861 if ( !is_array( $link ) ) {
2862 $html .= $link;
2863 } else {
2864 $html .= $link['html'];
2865 $states += $link['states'];
2866 }
2867 }
2868
2869 if ( count( $states ) ) {
2870 $html = Html::inlineScript(
2871 ResourceLoader::makeLoaderConditionalScript(
2872 ResourceLoader::makeLoaderStateScript( $states )
2873 )
2874 ) . "\n" . $html;
2875 }
2876
2877 return $html;
2878 }
2879
2880 /**
2881 * JS stuff to put in the "<head>". This is the startup module, config
2882 * vars and modules marked with position 'top'
2883 *
2884 * @return string HTML fragment
2885 */
2886 function getHeadScripts() {
2887 global $wgResourceLoaderExperimentalAsyncLoading;
2888
2889 // Startup - this will immediately load jquery and mediawiki modules
2890 $links = array();
2891 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2892
2893 // Load config before anything else
2894 $links[] = Html::inlineScript(
2895 ResourceLoader::makeLoaderConditionalScript(
2896 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2897 )
2898 );
2899
2900 // Load embeddable private modules before any loader links
2901 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2902 // in mw.loader.implement() calls and deferred until mw.user is available
2903 $embedScripts = array( 'user.options', 'user.tokens' );
2904 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2905
2906 // Scripts and messages "only" requests marked for top inclusion
2907 // Messages should go first
2908 $links[] = $this->makeResourceLoaderLink(
2909 $this->getModuleMessages( true, 'top' ),
2910 ResourceLoaderModule::TYPE_MESSAGES
2911 );
2912 $links[] = $this->makeResourceLoaderLink(
2913 $this->getModuleScripts( true, 'top' ),
2914 ResourceLoaderModule::TYPE_SCRIPTS
2915 );
2916
2917 // Modules requests - let the client calculate dependencies and batch requests as it likes
2918 // Only load modules that have marked themselves for loading at the top
2919 $modules = $this->getModules( true, 'top' );
2920 if ( $modules ) {
2921 $links[] = Html::inlineScript(
2922 ResourceLoader::makeLoaderConditionalScript(
2923 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2924 )
2925 );
2926 }
2927
2928 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2929 $links[] = $this->getScriptsForBottomQueue( true );
2930 }
2931
2932 return self::getHtmlFromLoaderLinks( $links );
2933 }
2934
2935 /**
2936 * JS stuff to put at the 'bottom', which can either be the bottom of the
2937 * "<body>" or the bottom of the "<head>" depending on
2938 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2939 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2940 * and user JS.
2941 *
2942 * @param bool $inHead If true, this HTML goes into the "<head>",
2943 * if false it goes into the "<body>".
2944 * @return string
2945 */
2946 function getScriptsForBottomQueue( $inHead ) {
2947 global $wgUseSiteJs, $wgAllowUserJs;
2948
2949 // Scripts and messages "only" requests marked for bottom inclusion
2950 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2951 // Messages should go first
2952 $links = array();
2953 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2954 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2955 /* $loadCall = */ $inHead
2956 );
2957 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2958 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2959 /* $loadCall = */ $inHead
2960 );
2961
2962 // Modules requests - let the client calculate dependencies and batch requests as it likes
2963 // Only load modules that have marked themselves for loading at the bottom
2964 $modules = $this->getModules( true, 'bottom' );
2965 if ( $modules ) {
2966 $links[] = Html::inlineScript(
2967 ResourceLoader::makeLoaderConditionalScript(
2968 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2969 )
2970 );
2971 }
2972
2973 // Legacy Scripts
2974 $links[] = "\n" . $this->mScripts;
2975
2976 // Add site JS if enabled
2977 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2978 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2979 );
2980
2981 // Add user JS if enabled
2982 if ( $wgAllowUserJs
2983 && $this->getUser()->isLoggedIn()
2984 && $this->getTitle()
2985 && $this->getTitle()->isJsSubpage()
2986 && $this->userCanPreview()
2987 ) {
2988 # XXX: additional security check/prompt?
2989 // We're on a preview of a JS subpage
2990 // Exclude this page from the user module in case it's in there (bug 26283)
2991 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2992 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2993 );
2994 // Load the previewed JS
2995 $links[] = Html::inlineScript( "\n"
2996 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2997
2998 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2999 // asynchronously and may arrive *after* the inline script here. So the previewed code
3000 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3001 } else {
3002 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3003 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3004 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3005 );
3006 }
3007
3008 // Group JS is only enabled if site JS is enabled.
3009 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3010 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3011 );
3012
3013 return self::getHtmlFromLoaderLinks( $links );
3014 }
3015
3016 /**
3017 * JS stuff to put at the bottom of the "<body>"
3018 * @return string
3019 */
3020 function getBottomScripts() {
3021 global $wgResourceLoaderExperimentalAsyncLoading;
3022
3023 // Optimise jQuery ready event cross-browser.
3024 // This also enforces $.isReady to be true at </body> which fixes the
3025 // mw.loader bug in Firefox with using document.write between </body>
3026 // and the DOMContentReady event (bug 47457).
3027 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
3028
3029 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
3030 $html .= $this->getScriptsForBottomQueue( false );
3031 }
3032
3033 return $html;
3034 }
3035
3036 /**
3037 * Get the javascript config vars to include on this page
3038 *
3039 * @return array Array of javascript config vars
3040 * @since 1.23
3041 */
3042 public function getJsConfigVars() {
3043 return $this->mJsConfigVars;
3044 }
3045
3046 /**
3047 * Add one or more variables to be set in mw.config in JavaScript
3048 *
3049 * @param string|array $keys Key or array of key/value pairs
3050 * @param mixed $value [optional] Value of the configuration variable
3051 */
3052 public function addJsConfigVars( $keys, $value = null ) {
3053 if ( is_array( $keys ) ) {
3054 foreach ( $keys as $key => $value ) {
3055 $this->mJsConfigVars[$key] = $value;
3056 }
3057 return;
3058 }
3059
3060 $this->mJsConfigVars[$keys] = $value;
3061 }
3062
3063 /**
3064 * Get an array containing the variables to be set in mw.config in JavaScript.
3065 *
3066 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
3067 * This is only public until that function is removed. You have been warned.
3068 *
3069 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3070 * - in other words, page-independent/site-wide variables (without state).
3071 * You will only be adding bloat to the html page and causing page caches to
3072 * have to be purged on configuration changes.
3073 * @return array
3074 */
3075 public function getJSVars() {
3076 global $wgContLang;
3077
3078 $curRevisionId = 0;
3079 $articleId = 0;
3080 $canonicalSpecialPageName = false; # bug 21115
3081
3082 $title = $this->getTitle();
3083 $ns = $title->getNamespace();
3084 $canonicalNamespace = MWNamespace::exists( $ns )
3085 ? MWNamespace::getCanonicalName( $ns )
3086 : $title->getNsText();
3087
3088 $sk = $this->getSkin();
3089 // Get the relevant title so that AJAX features can use the correct page name
3090 // when making API requests from certain special pages (bug 34972).
3091 $relevantTitle = $sk->getRelevantTitle();
3092 $relevantUser = $sk->getRelevantUser();
3093
3094 if ( $ns == NS_SPECIAL ) {
3095 list( $canonicalSpecialPageName, /*...*/ ) =
3096 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3097 } elseif ( $this->canUseWikiPage() ) {
3098 $wikiPage = $this->getWikiPage();
3099 $curRevisionId = $wikiPage->getLatest();
3100 $articleId = $wikiPage->getId();
3101 }
3102
3103 $lang = $title->getPageLanguage();
3104
3105 // Pre-process information
3106 $separatorTransTable = $lang->separatorTransformTable();
3107 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3108 $compactSeparatorTransTable = array(
3109 implode( "\t", array_keys( $separatorTransTable ) ),
3110 implode( "\t", $separatorTransTable ),
3111 );
3112 $digitTransTable = $lang->digitTransformTable();
3113 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3114 $compactDigitTransTable = array(
3115 implode( "\t", array_keys( $digitTransTable ) ),
3116 implode( "\t", $digitTransTable ),
3117 );
3118
3119 $user = $this->getUser();
3120
3121 $vars = array(
3122 'wgCanonicalNamespace' => $canonicalNamespace,
3123 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3124 'wgNamespaceNumber' => $title->getNamespace(),
3125 'wgPageName' => $title->getPrefixedDBkey(),
3126 'wgTitle' => $title->getText(),
3127 'wgCurRevisionId' => $curRevisionId,
3128 'wgRevisionId' => (int)$this->getRevisionId(),
3129 'wgArticleId' => $articleId,
3130 'wgIsArticle' => $this->isArticle(),
3131 'wgIsRedirect' => $title->isRedirect(),
3132 'wgAction' => Action::getActionName( $this->getContext() ),
3133 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3134 'wgUserGroups' => $user->getEffectiveGroups(),
3135 'wgCategories' => $this->getCategories(),
3136 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3137 'wgPageContentLanguage' => $lang->getCode(),
3138 'wgPageContentModel' => $title->getContentModel(),
3139 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3140 'wgDigitTransformTable' => $compactDigitTransTable,
3141 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3142 'wgMonthNames' => $lang->getMonthNamesArray(),
3143 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3144 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3145 );
3146
3147 if ( $user->isLoggedIn() ) {
3148 $vars['wgUserId'] = $user->getId();
3149 $vars['wgUserEditCount'] = $user->getEditCount();
3150 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3151 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3152 // Get the revision ID of the oldest new message on the user's talk
3153 // page. This can be used for constructing new message alerts on
3154 // the client side.
3155 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3156 }
3157
3158 if ( $wgContLang->hasVariants() ) {
3159 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3160 }
3161 // Same test as SkinTemplate
3162 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3163 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3164
3165 foreach ( $title->getRestrictionTypes() as $type ) {
3166 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3167 }
3168
3169 if ( $title->isMainPage() ) {
3170 $vars['wgIsMainPage'] = true;
3171 }
3172
3173 if ( $this->mRedirectedFrom ) {
3174 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3175 }
3176
3177 if ( $relevantUser ) {
3178 $vars['wgRelevantUserName'] = $relevantUser->getName();
3179 }
3180
3181 // Allow extensions to add their custom variables to the mw.config map.
3182 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3183 // page-dependant but site-wide (without state).
3184 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3185 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3186
3187 // Merge in variables from addJsConfigVars last
3188 return array_merge( $vars, $this->getJsConfigVars() );
3189 }
3190
3191 /**
3192 * To make it harder for someone to slip a user a fake
3193 * user-JavaScript or user-CSS preview, a random token
3194 * is associated with the login session. If it's not
3195 * passed back with the preview request, we won't render
3196 * the code.
3197 *
3198 * @return bool
3199 */
3200 public function userCanPreview() {
3201 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3202 || !$this->getRequest()->wasPosted()
3203 || !$this->getUser()->matchEditToken(
3204 $this->getRequest()->getVal( 'wpEditToken' ) )
3205 ) {
3206 return false;
3207 }
3208 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3209 return false;
3210 }
3211
3212 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3213 }
3214
3215 /**
3216 * @return array in format "link name or number => 'link html'".
3217 */
3218 public function getHeadLinksArray() {
3219 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3220 $wgSitename, $wgVersion,
3221 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3222 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3223 $wgRightsPage, $wgRightsUrl;
3224
3225 $tags = array();
3226
3227 $canonicalUrl = $this->mCanonicalUrl;
3228
3229 $tags['meta-generator'] = Html::element( 'meta', array(
3230 'name' => 'generator',
3231 'content' => "MediaWiki $wgVersion",
3232 ) );
3233
3234 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3235 if ( $p !== 'index,follow' ) {
3236 // http://www.robotstxt.org/wc/meta-user.html
3237 // Only show if it's different from the default robots policy
3238 $tags['meta-robots'] = Html::element( 'meta', array(
3239 'name' => 'robots',
3240 'content' => $p,
3241 ) );
3242 }
3243
3244 foreach ( $this->mMetatags as $tag ) {
3245 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3246 $a = 'http-equiv';
3247 $tag[0] = substr( $tag[0], 5 );
3248 } else {
3249 $a = 'name';
3250 }
3251 $tagName = "meta-{$tag[0]}";
3252 if ( isset( $tags[$tagName] ) ) {
3253 $tagName .= $tag[1];
3254 }
3255 $tags[$tagName] = Html::element( 'meta',
3256 array(
3257 $a => $tag[0],
3258 'content' => $tag[1]
3259 )
3260 );
3261 }
3262
3263 foreach ( $this->mLinktags as $tag ) {
3264 $tags[] = Html::element( 'link', $tag );
3265 }
3266
3267 # Universal edit button
3268 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3269 $user = $this->getUser();
3270 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3271 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3272 // Original UniversalEditButton
3273 $msg = $this->msg( 'edit' )->text();
3274 $tags['universal-edit-button'] = Html::element( 'link', array(
3275 'rel' => 'alternate',
3276 'type' => 'application/x-wiki',
3277 'title' => $msg,
3278 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3279 ) );
3280 // Alternate edit link
3281 $tags['alternative-edit'] = Html::element( 'link', array(
3282 'rel' => 'edit',
3283 'title' => $msg,
3284 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3285 ) );
3286 }
3287 }
3288
3289 # Generally the order of the favicon and apple-touch-icon links
3290 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3291 # uses whichever one appears later in the HTML source. Make sure
3292 # apple-touch-icon is specified first to avoid this.
3293 if ( $wgAppleTouchIcon !== false ) {
3294 $tags['apple-touch-icon'] = Html::element( 'link', array(
3295 'rel' => 'apple-touch-icon',
3296 'href' => $wgAppleTouchIcon
3297 ) );
3298 }
3299
3300 if ( $wgFavicon !== false ) {
3301 $tags['favicon'] = Html::element( 'link', array(
3302 'rel' => 'shortcut icon',
3303 'href' => $wgFavicon
3304 ) );
3305 }
3306
3307 # OpenSearch description link
3308 $tags['opensearch'] = Html::element( 'link', array(
3309 'rel' => 'search',
3310 'type' => 'application/opensearchdescription+xml',
3311 'href' => wfScript( 'opensearch_desc' ),
3312 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3313 ) );
3314
3315 if ( $wgEnableAPI ) {
3316 # Real Simple Discovery link, provides auto-discovery information
3317 # for the MediaWiki API (and potentially additional custom API
3318 # support such as WordPress or Twitter-compatible APIs for a
3319 # blogging extension, etc)
3320 $tags['rsd'] = Html::element( 'link', array(
3321 'rel' => 'EditURI',
3322 'type' => 'application/rsd+xml',
3323 // Output a protocol-relative URL here if $wgServer is protocol-relative
3324 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3325 'href' => wfExpandUrl( wfAppendQuery(
3326 wfScript( 'api' ),
3327 array( 'action' => 'rsd' ) ),
3328 PROTO_RELATIVE
3329 ),
3330 ) );
3331 }
3332
3333 # Language variants
3334 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3335 $lang = $this->getTitle()->getPageLanguage();
3336 if ( $lang->hasVariants() ) {
3337
3338 $urlvar = $lang->getURLVariant();
3339
3340 if ( !$urlvar ) {
3341 $variants = $lang->getVariants();
3342 foreach ( $variants as $_v ) {
3343 $tags["variant-$_v"] = Html::element( 'link', array(
3344 'rel' => 'alternate',
3345 'hreflang' => wfBCP47( $_v ),
3346 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3347 );
3348 }
3349 } else {
3350 $canonicalUrl = $this->getTitle()->getLocalURL();
3351 }
3352 }
3353 }
3354
3355 # Copyright
3356 $copyright = '';
3357 if ( $wgRightsPage ) {
3358 $copy = Title::newFromText( $wgRightsPage );
3359
3360 if ( $copy ) {
3361 $copyright = $copy->getLocalURL();
3362 }
3363 }
3364
3365 if ( !$copyright && $wgRightsUrl ) {
3366 $copyright = $wgRightsUrl;
3367 }
3368
3369 if ( $copyright ) {
3370 $tags['copyright'] = Html::element( 'link', array(
3371 'rel' => 'copyright',
3372 'href' => $copyright )
3373 );
3374 }
3375
3376 # Feeds
3377 if ( $wgFeed ) {
3378 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3379 # Use the page name for the title. In principle, this could
3380 # lead to issues with having the same name for different feeds
3381 # corresponding to the same page, but we can't avoid that at
3382 # this low a level.
3383
3384 $tags[] = $this->feedLink(
3385 $format,
3386 $link,
3387 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3388 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3389 );
3390 }
3391
3392 # Recent changes feed should appear on every page (except recentchanges,
3393 # that would be redundant). Put it after the per-page feed to avoid
3394 # changing existing behavior. It's still available, probably via a
3395 # menu in your browser. Some sites might have a different feed they'd
3396 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3397 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3398 # If so, use it instead.
3399 if ( $wgOverrideSiteFeed ) {
3400 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3401 // Note, this->feedLink escapes the url.
3402 $tags[] = $this->feedLink(
3403 $type,
3404 $feedUrl,
3405 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3406 );
3407 }
3408 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3409 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3410 foreach ( $wgAdvertisedFeedTypes as $format ) {
3411 $tags[] = $this->feedLink(
3412 $format,
3413 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3414 # For grep: 'site-rss-feed', 'site-atom-feed'
3415 $this->msg( "site-{$format}-feed", $wgSitename )->text()
3416 );
3417 }
3418 }
3419 }
3420
3421 # Canonical URL
3422 global $wgEnableCanonicalServerLink;
3423 if ( $wgEnableCanonicalServerLink ) {
3424 if ( $canonicalUrl !== false ) {
3425 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3426 } else {
3427 $reqUrl = $this->getRequest()->getRequestURL();
3428 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3429 }
3430 }
3431 if ( $canonicalUrl !== false ) {
3432 $tags[] = Html::element( 'link', array(
3433 'rel' => 'canonical',
3434 'href' => $canonicalUrl
3435 ) );
3436 }
3437
3438 return $tags;
3439 }
3440
3441 /**
3442 * @return string HTML tag links to be put in the header.
3443 */
3444 public function getHeadLinks() {
3445 return implode( "\n", $this->getHeadLinksArray() );
3446 }
3447
3448 /**
3449 * Generate a "<link rel/>" for a feed.
3450 *
3451 * @param string $type Feed type
3452 * @param string $url URL to the feed
3453 * @param string $text Value of the "title" attribute
3454 * @return string HTML fragment
3455 */
3456 private function feedLink( $type, $url, $text ) {
3457 return Html::element( 'link', array(
3458 'rel' => 'alternate',
3459 'type' => "application/$type+xml",
3460 'title' => $text,
3461 'href' => $url )
3462 );
3463 }
3464
3465 /**
3466 * Add a local or specified stylesheet, with the given media options.
3467 * Meant primarily for internal use...
3468 *
3469 * @param string $style URL to the file
3470 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3471 * @param string $condition for IE conditional comments, specifying an IE version
3472 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3473 */
3474 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3475 $options = array();
3476 // Even though we expect the media type to be lowercase, but here we
3477 // force it to lowercase to be safe.
3478 if ( $media ) {
3479 $options['media'] = $media;
3480 }
3481 if ( $condition ) {
3482 $options['condition'] = $condition;
3483 }
3484 if ( $dir ) {
3485 $options['dir'] = $dir;
3486 }
3487 $this->styles[$style] = $options;
3488 }
3489
3490 /**
3491 * Adds inline CSS styles
3492 * @param mixed $style_css Inline CSS
3493 * @param string $flip Set to 'flip' to flip the CSS if needed
3494 */
3495 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3496 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3497 # If wanted, and the interface is right-to-left, flip the CSS
3498 $style_css = CSSJanus::transform( $style_css, true, false );
3499 }
3500 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3501 }
3502
3503 /**
3504 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3505 * These will be applied to various media & IE conditionals.
3506 *
3507 * @return string
3508 */
3509 public function buildCssLinks() {
3510 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3511
3512 $this->getSkin()->setupSkinUserCss( $this );
3513
3514 // Add ResourceLoader styles
3515 // Split the styles into these groups
3516 $styles = array(
3517 'other' => array(),
3518 'user' => array(),
3519 'site' => array(),
3520 'private' => array(),
3521 'noscript' => array()
3522 );
3523 $links = array();
3524 $otherTags = ''; // Tags to append after the normal <link> tags
3525 $resourceLoader = $this->getResourceLoader();
3526
3527 $moduleStyles = $this->getModuleStyles();
3528
3529 // Per-site custom styles
3530 $moduleStyles[] = 'site';
3531 $moduleStyles[] = 'noscript';
3532 $moduleStyles[] = 'user.groups';
3533
3534 // Per-user custom styles
3535 if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3536 // We're on a preview of a CSS subpage
3537 // Exclude this page from the user module in case it's in there (bug 26283)
3538 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3539 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3540 );
3541 $otherTags .= $link['html'];
3542
3543 // Load the previewed CSS
3544 // If needed, Janus it first. This is user-supplied CSS, so it's
3545 // assumed to be right for the content language directionality.
3546 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3547 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3548 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3549 }
3550 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3551 } else {
3552 // Load the user styles normally
3553 $moduleStyles[] = 'user';
3554 }
3555
3556 // Per-user preference styles
3557 $moduleStyles[] = 'user.cssprefs';
3558
3559 foreach ( $moduleStyles as $name ) {
3560 $module = $resourceLoader->getModule( $name );
3561 if ( !$module ) {
3562 continue;
3563 }
3564 $group = $module->getGroup();
3565 // Modules in groups different than the ones listed on top (see $styles assignment)
3566 // will be placed in the "other" group
3567 $styles[ isset( $styles[$group] ) ? $group : 'other' ][] = $name;
3568 }
3569
3570 // We want site, private and user styles to override dynamically added
3571 // styles from modules, but we want dynamically added styles to override
3572 // statically added styles from other modules. So the order has to be
3573 // other, dynamic, site, private, user. Add statically added styles for
3574 // other modules
3575 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3576 // Add normal styles added through addStyle()/addInlineStyle() here
3577 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3578 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3579 // We use a <meta> tag with a made-up name for this because that's valid HTML
3580 $links[] = Html::element(
3581 'meta',
3582 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3583 ) . "\n";
3584
3585 // Add site, private and user styles
3586 // 'private' at present only contains user.options, so put that before 'user'
3587 // Any future private modules will likely have a similar user-specific character
3588 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3589 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3590 ResourceLoaderModule::TYPE_STYLES
3591 );
3592 }
3593
3594 // Add stuff in $otherTags (previewed user CSS if applicable)
3595 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3596 }
3597
3598 /**
3599 * @return array
3600 */
3601 public function buildCssLinksArray() {
3602 $links = array();
3603
3604 // Add any extension CSS
3605 foreach ( $this->mExtStyles as $url ) {
3606 $this->addStyle( $url );
3607 }
3608 $this->mExtStyles = array();
3609
3610 foreach ( $this->styles as $file => $options ) {
3611 $link = $this->styleLink( $file, $options );
3612 if ( $link ) {
3613 $links[$file] = $link;
3614 }
3615 }
3616 return $links;
3617 }
3618
3619 /**
3620 * Generate \<link\> tags for stylesheets
3621 *
3622 * @param string $style URL to the file
3623 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3624 * @return string HTML fragment
3625 */
3626 protected function styleLink( $style, $options ) {
3627 if ( isset( $options['dir'] ) ) {
3628 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3629 return '';
3630 }
3631 }
3632
3633 if ( isset( $options['media'] ) ) {
3634 $media = self::transformCssMedia( $options['media'] );
3635 if ( is_null( $media ) ) {
3636 return '';
3637 }
3638 } else {
3639 $media = 'all';
3640 }
3641
3642 if ( substr( $style, 0, 1 ) == '/' ||
3643 substr( $style, 0, 5 ) == 'http:' ||
3644 substr( $style, 0, 6 ) == 'https:' ) {
3645 $url = $style;
3646 } else {
3647 global $wgStylePath, $wgStyleVersion;
3648 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3649 }
3650
3651 $link = Html::linkedStyle( $url, $media );
3652
3653 if ( isset( $options['condition'] ) ) {
3654 $condition = htmlspecialchars( $options['condition'] );
3655 $link = "<!--[if $condition]>$link<![endif]-->";
3656 }
3657 return $link;
3658 }
3659
3660 /**
3661 * Transform "media" attribute based on request parameters
3662 *
3663 * @param string $media Current value of the "media" attribute
3664 * @return string Modified value of the "media" attribute, or null to skip
3665 * this stylesheet
3666 */
3667 public static function transformCssMedia( $media ) {
3668 global $wgRequest;
3669
3670 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3671 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3672
3673 // Switch in on-screen display for media testing
3674 $switches = array(
3675 'printable' => 'print',
3676 'handheld' => 'handheld',
3677 );
3678 foreach ( $switches as $switch => $targetMedia ) {
3679 if ( $wgRequest->getBool( $switch ) ) {
3680 if ( $media == $targetMedia ) {
3681 $media = '';
3682 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3683 // This regex will not attempt to understand a comma-separated media_query_list
3684 //
3685 // Example supported values for $media:
3686 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3687 // Example NOT supported value for $media:
3688 // '3d-glasses, screen, print and resolution > 90dpi'
3689 //
3690 // If it's a print request, we never want any kind of screen stylesheets
3691 // If it's a handheld request (currently the only other choice with a switch),
3692 // we don't want simple 'screen' but we might want screen queries that
3693 // have a max-width or something, so we'll pass all others on and let the
3694 // client do the query.
3695 if ( $targetMedia == 'print' || $media == 'screen' ) {
3696 return null;
3697 }
3698 }
3699 }
3700 }
3701
3702 return $media;
3703 }
3704
3705 /**
3706 * Add a wikitext-formatted message to the output.
3707 * This is equivalent to:
3708 *
3709 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3710 */
3711 public function addWikiMsg( /*...*/ ) {
3712 $args = func_get_args();
3713 $name = array_shift( $args );
3714 $this->addWikiMsgArray( $name, $args );
3715 }
3716
3717 /**
3718 * Add a wikitext-formatted message to the output.
3719 * Like addWikiMsg() except the parameters are taken as an array
3720 * instead of a variable argument list.
3721 *
3722 * @param string $name
3723 * @param array $args
3724 */
3725 public function addWikiMsgArray( $name, $args ) {
3726 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3727 }
3728
3729 /**
3730 * This function takes a number of message/argument specifications, wraps them in
3731 * some overall structure, and then parses the result and adds it to the output.
3732 *
3733 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3734 * on. The subsequent arguments may either be strings, in which case they are the
3735 * message names, or arrays, in which case the first element is the message name,
3736 * and subsequent elements are the parameters to that message.
3737 *
3738 * Don't use this for messages that are not in users interface language.
3739 *
3740 * For example:
3741 *
3742 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3743 *
3744 * Is equivalent to:
3745 *
3746 * $wgOut->addWikiText( "<div class='error'>\n"
3747 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3748 *
3749 * The newline after opening div is needed in some wikitext. See bug 19226.
3750 *
3751 * @param string $wrap
3752 */
3753 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3754 $msgSpecs = func_get_args();
3755 array_shift( $msgSpecs );
3756 $msgSpecs = array_values( $msgSpecs );
3757 $s = $wrap;
3758 foreach ( $msgSpecs as $n => $spec ) {
3759 if ( is_array( $spec ) ) {
3760 $args = $spec;
3761 $name = array_shift( $args );
3762 if ( isset( $args['options'] ) ) {
3763 unset( $args['options'] );
3764 wfDeprecated(
3765 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3766 '1.20'
3767 );
3768 }
3769 } else {
3770 $args = array();
3771 $name = $spec;
3772 }
3773 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3774 }
3775 $this->addWikiText( $s );
3776 }
3777
3778 /**
3779 * Include jQuery core. Use this to avoid loading it multiple times
3780 * before we get a usable script loader.
3781 *
3782 * @param array $modules List of jQuery modules which should be loaded
3783 * @return array The list of modules which were not loaded.
3784 * @since 1.16
3785 * @deprecated since 1.17
3786 */
3787 public function includeJQuery( $modules = array() ) {
3788 return array();
3789 }
3790
3791 /**
3792 * Enables/disables TOC, doesn't override __NOTOC__
3793 * @param bool $flag
3794 * @since 1.22
3795 */
3796 public function enableTOC( $flag = true ) {
3797 $this->mEnableTOC = $flag;
3798 }
3799
3800 /**
3801 * @return bool
3802 * @since 1.22
3803 */
3804 public function isTOCEnabled() {
3805 return $this->mEnableTOC;
3806 }
3807
3808 /**
3809 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3810 * @param bool $flag
3811 * @since 1.23
3812 */
3813 public function enableSectionEditLinks( $flag = true ) {
3814 $this->mEnableSectionEditLinks = $flag;
3815 }
3816
3817 /**
3818 * @return bool
3819 * @since 1.23
3820 */
3821 public function sectionEditLinksEnabled() {
3822 return $this->mEnableSectionEditLinks;
3823 }
3824 }