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