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