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