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