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