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