Merge "misc style issues"
[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 if ( !$title ) {
1439 throw new MWException( 'Title is null' );
1440 }
1441 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1442 }
1443
1444 /**
1445 * Add wikitext with a custom Title object
1446 *
1447 * @param $text String: wikitext
1448 * @param $title Title object
1449 * @param $linestart Boolean: is this the start of a line?
1450 */
1451 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1452 $this->addWikiTextTitle( $text, $title, $linestart );
1453 }
1454
1455 /**
1456 * Add wikitext with a custom Title object and tidy enabled.
1457 *
1458 * @param $text String: wikitext
1459 * @param $title Title object
1460 * @param $linestart Boolean: is this the start of a line?
1461 */
1462 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1463 $this->addWikiTextTitle( $text, $title, $linestart, true );
1464 }
1465
1466 /**
1467 * Add wikitext with tidy enabled
1468 *
1469 * @param $text String: wikitext
1470 * @param $linestart Boolean: is this the start of a line?
1471 */
1472 public function addWikiTextTidy( $text, $linestart = true ) {
1473 $title = $this->getTitle();
1474 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1475 }
1476
1477 /**
1478 * Add wikitext with a custom Title object
1479 *
1480 * @param $text String: wikitext
1481 * @param $title Title object
1482 * @param $linestart Boolean: is this the start of a line?
1483 * @param $tidy Boolean: whether to use tidy
1484 * @param $interface Boolean: whether it is an interface message
1485 * (for example disables conversion)
1486 */
1487 public function addWikiTextTitle( $text, Title $title, $linestart, $tidy = false, $interface = false ) {
1488 global $wgParser;
1489
1490 wfProfileIn( __METHOD__ );
1491
1492 $popts = $this->parserOptions();
1493 $oldTidy = $popts->setTidy( $tidy );
1494 $popts->setInterfaceMessage( (bool) $interface );
1495
1496 $parserOutput = $wgParser->parse(
1497 $text, $title, $popts,
1498 $linestart, true, $this->mRevisionId
1499 );
1500
1501 $popts->setTidy( $oldTidy );
1502
1503 $this->addParserOutput( $parserOutput );
1504
1505 wfProfileOut( __METHOD__ );
1506 }
1507
1508 /**
1509 * Add a ParserOutput object, but without Html
1510 *
1511 * @param $parserOutput ParserOutput object
1512 */
1513 public function addParserOutputNoText( &$parserOutput ) {
1514 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1515 $this->addCategoryLinks( $parserOutput->getCategories() );
1516 $this->mNewSectionLink = $parserOutput->getNewSection();
1517 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1518
1519 $this->mParseWarnings = $parserOutput->getWarnings();
1520 if ( !$parserOutput->isCacheable() ) {
1521 $this->enableClientCache( false );
1522 }
1523 $this->mNoGallery = $parserOutput->getNoGallery();
1524 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1525 $this->addModules( $parserOutput->getModules() );
1526 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1527 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1528 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1529
1530 // Template versioning...
1531 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1532 if ( isset( $this->mTemplateIds[$ns] ) ) {
1533 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1534 } else {
1535 $this->mTemplateIds[$ns] = $dbks;
1536 }
1537 }
1538 // File versioning...
1539 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1540 $this->mImageTimeKeys[$dbk] = $data;
1541 }
1542
1543 // Hooks registered in the object
1544 global $wgParserOutputHooks;
1545 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1546 list( $hookName, $data ) = $hookInfo;
1547 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1548 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1549 }
1550 }
1551
1552 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1553 }
1554
1555 /**
1556 * Add a ParserOutput object
1557 *
1558 * @param $parserOutput ParserOutput
1559 */
1560 function addParserOutput( &$parserOutput ) {
1561 $this->addParserOutputNoText( $parserOutput );
1562 $text = $parserOutput->getText();
1563 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1564 $this->addHTML( $text );
1565 }
1566
1567
1568 /**
1569 * Add the output of a QuickTemplate to the output buffer
1570 *
1571 * @param $template QuickTemplate
1572 */
1573 public function addTemplate( &$template ) {
1574 ob_start();
1575 $template->execute();
1576 $this->addHTML( ob_get_contents() );
1577 ob_end_clean();
1578 }
1579
1580 /**
1581 * Parse wikitext and return the HTML.
1582 *
1583 * @param $text String
1584 * @param $linestart Boolean: is this the start of a line?
1585 * @param $interface Boolean: use interface language ($wgLang instead of
1586 * $wgContLang) while parsing language sensitive magic
1587 * words like GRAMMAR and PLURAL. This also disables
1588 * LanguageConverter.
1589 * @param $language Language object: target language object, will override
1590 * $interface
1591 * @throws MWException
1592 * @return String: HTML
1593 */
1594 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1595 global $wgParser;
1596
1597 if( is_null( $this->getTitle() ) ) {
1598 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1599 }
1600
1601 $popts = $this->parserOptions();
1602 if ( $interface ) {
1603 $popts->setInterfaceMessage( true );
1604 }
1605 if ( $language !== null ) {
1606 $oldLang = $popts->setTargetLanguage( $language );
1607 }
1608
1609 $parserOutput = $wgParser->parse(
1610 $text, $this->getTitle(), $popts,
1611 $linestart, true, $this->mRevisionId
1612 );
1613
1614 if ( $interface ) {
1615 $popts->setInterfaceMessage( false );
1616 }
1617 if ( $language !== null ) {
1618 $popts->setTargetLanguage( $oldLang );
1619 }
1620
1621 return $parserOutput->getText();
1622 }
1623
1624 /**
1625 * Parse wikitext, strip paragraphs, and return the HTML.
1626 *
1627 * @param $text String
1628 * @param $linestart Boolean: is this the start of a line?
1629 * @param $interface Boolean: use interface language ($wgLang instead of
1630 * $wgContLang) while parsing language sensitive magic
1631 * words like GRAMMAR and PLURAL
1632 * @return String: HTML
1633 */
1634 public function parseInline( $text, $linestart = true, $interface = false ) {
1635 $parsed = $this->parse( $text, $linestart, $interface );
1636
1637 $m = array();
1638 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1639 $parsed = $m[1];
1640 }
1641
1642 return $parsed;
1643 }
1644
1645 /**
1646 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1647 *
1648 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1649 */
1650 public function setSquidMaxage( $maxage ) {
1651 $this->mSquidMaxage = $maxage;
1652 }
1653
1654 /**
1655 * Use enableClientCache(false) to force it to send nocache headers
1656 *
1657 * @param $state bool
1658 *
1659 * @return bool
1660 */
1661 public function enableClientCache( $state ) {
1662 return wfSetVar( $this->mEnableClientCache, $state );
1663 }
1664
1665 /**
1666 * Get the list of cookies that will influence on the cache
1667 *
1668 * @return Array
1669 */
1670 function getCacheVaryCookies() {
1671 global $wgCookiePrefix, $wgCacheVaryCookies;
1672 static $cookies;
1673 if ( $cookies === null ) {
1674 $cookies = array_merge(
1675 array(
1676 "{$wgCookiePrefix}Token",
1677 "{$wgCookiePrefix}LoggedOut",
1678 session_name()
1679 ),
1680 $wgCacheVaryCookies
1681 );
1682 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1683 }
1684 return $cookies;
1685 }
1686
1687 /**
1688 * Check if the request has a cache-varying cookie header
1689 * If it does, it's very important that we don't allow public caching
1690 *
1691 * @return Boolean
1692 */
1693 function haveCacheVaryCookies() {
1694 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1695 if ( $cookieHeader === false ) {
1696 return false;
1697 }
1698 $cvCookies = $this->getCacheVaryCookies();
1699 foreach ( $cvCookies as $cookieName ) {
1700 # Check for a simple string match, like the way squid does it
1701 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1702 wfDebug( __METHOD__ . ": found $cookieName\n" );
1703 return true;
1704 }
1705 }
1706 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1707 return false;
1708 }
1709
1710 /**
1711 * Add an HTTP header that will influence on the cache
1712 *
1713 * @param $header String: header name
1714 * @param $option Array|null
1715 * @todo FIXME: Document the $option parameter; it appears to be for
1716 * X-Vary-Options but what format is acceptable?
1717 */
1718 public function addVaryHeader( $header, $option = null ) {
1719 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1720 $this->mVaryHeader[$header] = (array)$option;
1721 } elseif( is_array( $option ) ) {
1722 if( is_array( $this->mVaryHeader[$header] ) ) {
1723 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1724 } else {
1725 $this->mVaryHeader[$header] = $option;
1726 }
1727 }
1728 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1729 }
1730
1731 /**
1732 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1733 * such as Accept-Encoding or Cookie
1734 *
1735 * @return String
1736 */
1737 public function getVaryHeader() {
1738 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1739 }
1740
1741 /**
1742 * Get a complete X-Vary-Options header
1743 *
1744 * @return String
1745 */
1746 public function getXVO() {
1747 $cvCookies = $this->getCacheVaryCookies();
1748
1749 $cookiesOption = array();
1750 foreach ( $cvCookies as $cookieName ) {
1751 $cookiesOption[] = 'string-contains=' . $cookieName;
1752 }
1753 $this->addVaryHeader( 'Cookie', $cookiesOption );
1754
1755 $headers = array();
1756 foreach( $this->mVaryHeader as $header => $option ) {
1757 $newheader = $header;
1758 if ( is_array( $option ) && count( $option ) > 0 ) {
1759 $newheader .= ';' . implode( ';', $option );
1760 }
1761 $headers[] = $newheader;
1762 }
1763 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1764
1765 return $xvo;
1766 }
1767
1768 /**
1769 * bug 21672: Add Accept-Language to Vary and XVO headers
1770 * if there's no 'variant' parameter existed in GET.
1771 *
1772 * For example:
1773 * /w/index.php?title=Main_page should always be served; but
1774 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1775 */
1776 function addAcceptLanguage() {
1777 $lang = $this->getTitle()->getPageLanguage();
1778 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1779 $variants = $lang->getVariants();
1780 $aloption = array();
1781 foreach ( $variants as $variant ) {
1782 if( $variant === $lang->getCode() ) {
1783 continue;
1784 } else {
1785 $aloption[] = 'string-contains=' . $variant;
1786
1787 // IE and some other browsers use BCP 47 standards in
1788 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1789 // We should handle these too.
1790 $variantBCP47 = wfBCP47( $variant );
1791 if ( $variantBCP47 !== $variant ) {
1792 $aloption[] = 'string-contains=' . $variantBCP47;
1793 }
1794 }
1795 }
1796 $this->addVaryHeader( 'Accept-Language', $aloption );
1797 }
1798 }
1799
1800 /**
1801 * Set a flag which will cause an X-Frame-Options header appropriate for
1802 * edit pages to be sent. The header value is controlled by
1803 * $wgEditPageFrameOptions.
1804 *
1805 * This is the default for special pages. If you display a CSRF-protected
1806 * form on an ordinary view page, then you need to call this function.
1807 *
1808 * @param $enable bool
1809 */
1810 public function preventClickjacking( $enable = true ) {
1811 $this->mPreventClickjacking = $enable;
1812 }
1813
1814 /**
1815 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1816 * This can be called from pages which do not contain any CSRF-protected
1817 * HTML form.
1818 */
1819 public function allowClickjacking() {
1820 $this->mPreventClickjacking = false;
1821 }
1822
1823 /**
1824 * Get the X-Frame-Options header value (without the name part), or false
1825 * if there isn't one. This is used by Skin to determine whether to enable
1826 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1827 *
1828 * @return string
1829 */
1830 public function getFrameOptions() {
1831 global $wgBreakFrames, $wgEditPageFrameOptions;
1832 if ( $wgBreakFrames ) {
1833 return 'DENY';
1834 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1835 return $wgEditPageFrameOptions;
1836 }
1837 return false;
1838 }
1839
1840 /**
1841 * Send cache control HTTP headers
1842 */
1843 public function sendCacheControl() {
1844 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1845
1846 $response = $this->getRequest()->response();
1847 if ( $wgUseETag && $this->mETag ) {
1848 $response->header( "ETag: $this->mETag" );
1849 }
1850
1851 $this->addVaryHeader( 'Cookie' );
1852 $this->addAcceptLanguage();
1853
1854 # don't serve compressed data to clients who can't handle it
1855 # maintain different caches for logged-in users and non-logged in ones
1856 $response->header( $this->getVaryHeader() );
1857
1858 if ( $wgUseXVO ) {
1859 # Add an X-Vary-Options header for Squid with Wikimedia patches
1860 $response->header( $this->getXVO() );
1861 }
1862
1863 if( $this->mEnableClientCache ) {
1864 if(
1865 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1866 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1867 )
1868 {
1869 if ( $wgUseESI ) {
1870 # We'll purge the proxy cache explicitly, but require end user agents
1871 # to revalidate against the proxy on each visit.
1872 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1873 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1874 # start with a shorter timeout for initial testing
1875 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1876 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
1877 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1878 } else {
1879 # We'll purge the proxy cache for anons explicitly, but require end user agents
1880 # to revalidate against the proxy on each visit.
1881 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1882 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1883 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1884 # start with a shorter timeout for initial testing
1885 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1886 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0' );
1887 }
1888 } else {
1889 # We do want clients to cache if they can, but they *must* check for updates
1890 # on revisiting the page.
1891 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1892 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1893 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1894 }
1895 if( $this->mLastModified ) {
1896 $response->header( "Last-Modified: {$this->mLastModified}" );
1897 }
1898 } else {
1899 wfDebug( __METHOD__ . ": no caching **\n", false );
1900
1901 # In general, the absence of a last modified header should be enough to prevent
1902 # the client from using its cache. We send a few other things just to make sure.
1903 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1904 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1905 $response->header( 'Pragma: no-cache' );
1906 }
1907 }
1908
1909 /**
1910 * Get the message associed with the HTTP response code $code
1911 *
1912 * @param $code Integer: status code
1913 * @return String or null: message or null if $code is not in the list of
1914 * messages
1915 *
1916 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1917 */
1918 public static function getStatusMessage( $code ) {
1919 wfDeprecated( __METHOD__, '1.18' );
1920 return HttpStatus::getMessage( $code );
1921 }
1922
1923 /**
1924 * Finally, all the text has been munged and accumulated into
1925 * the object, let's actually output it:
1926 */
1927 public function output() {
1928 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1929
1930 if( $this->mDoNothing ) {
1931 return;
1932 }
1933
1934 wfProfileIn( __METHOD__ );
1935
1936 $response = $this->getRequest()->response();
1937
1938 if ( $this->mRedirect != '' ) {
1939 # Standards require redirect URLs to be absolute
1940 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
1941
1942 $redirect = $this->mRedirect;
1943 $code = $this->mRedirectCode;
1944
1945 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1946 if( $code == '301' || $code == '303' ) {
1947 if( !$wgDebugRedirects ) {
1948 $message = HttpStatus::getMessage( $code );
1949 $response->header( "HTTP/1.1 $code $message" );
1950 }
1951 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1952 }
1953 if ( $wgVaryOnXFP ) {
1954 $this->addVaryHeader( 'X-Forwarded-Proto' );
1955 }
1956 $this->sendCacheControl();
1957
1958 $response->header( "Content-Type: text/html; charset=utf-8" );
1959 if( $wgDebugRedirects ) {
1960 $url = htmlspecialchars( $redirect );
1961 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1962 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1963 print "</body>\n</html>\n";
1964 } else {
1965 $response->header( 'Location: ' . $redirect );
1966 }
1967 }
1968
1969 wfProfileOut( __METHOD__ );
1970 return;
1971 } elseif ( $this->mStatusCode ) {
1972 $message = HttpStatus::getMessage( $this->mStatusCode );
1973 if ( $message ) {
1974 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1975 }
1976 }
1977
1978 # Buffer output; final headers may depend on later processing
1979 ob_start();
1980
1981 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1982 $response->header( 'Content-language: ' . $wgLanguageCode );
1983
1984 // Prevent framing, if requested
1985 $frameOptions = $this->getFrameOptions();
1986 if ( $frameOptions ) {
1987 $response->header( "X-Frame-Options: $frameOptions" );
1988 }
1989
1990 if ( $this->mArticleBodyOnly ) {
1991 $this->out( $this->mBodytext );
1992 } else {
1993 $this->addDefaultModules();
1994
1995 $sk = $this->getSkin();
1996
1997 // Hook that allows last minute changes to the output page, e.g.
1998 // adding of CSS or Javascript by extensions.
1999 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2000
2001 wfProfileIn( 'Output-skin' );
2002 $sk->outputPage();
2003 wfProfileOut( 'Output-skin' );
2004 }
2005
2006 // This hook allows last minute changes to final overall output by modifying output buffer
2007 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2008
2009 $this->sendCacheControl();
2010
2011 ob_end_flush();
2012
2013 wfProfileOut( __METHOD__ );
2014 }
2015
2016 /**
2017 * Actually output something with print().
2018 *
2019 * @param $ins String: the string to output
2020 */
2021 public function out( $ins ) {
2022 print $ins;
2023 }
2024
2025 /**
2026 * Produce a "user is blocked" page.
2027 * @deprecated since 1.18
2028 */
2029 function blockedPage() {
2030 throw new UserBlockedError( $this->getUser()->mBlock );
2031 }
2032
2033 /**
2034 * Prepare this object to display an error page; disable caching and
2035 * indexing, clear the current text and redirect, set the page's title
2036 * and optionally an custom HTML title (content of the "<title>" tag).
2037 *
2038 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2039 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2040 * optional, if not passed the "<title>" attribute will be
2041 * based on $pageTitle
2042 */
2043 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2044 $this->setPageTitle( $pageTitle );
2045 if ( $htmlTitle !== false ) {
2046 $this->setHTMLTitle( $htmlTitle );
2047 }
2048 $this->setRobotPolicy( 'noindex,nofollow' );
2049 $this->setArticleRelated( false );
2050 $this->enableClientCache( false );
2051 $this->mRedirect = '';
2052 $this->clearSubtitle();
2053 $this->clearHTML();
2054 }
2055
2056 /**
2057 * Output a standard error page
2058 *
2059 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2060 * showErrorPage( 'titlemsg', $messageObject );
2061 * showErrorPage( $titleMessageObj, $messageObject );
2062 *
2063 * @param $title Mixed: message key (string) for page title, or a Message object
2064 * @param $msg Mixed: message key (string) for page text, or a Message object
2065 * @param $params Array: message parameters; ignored if $msg is a Message object
2066 */
2067 public function showErrorPage( $title, $msg, $params = array() ) {
2068 if( !$title instanceof Message ) {
2069 $title = $this->msg( $title );
2070 }
2071
2072 $this->prepareErrorPage( $title );
2073
2074 if ( $msg instanceof Message ) {
2075 $this->addHTML( $msg->parseAsBlock() );
2076 } else {
2077 $this->addWikiMsgArray( $msg, $params );
2078 }
2079
2080 $this->returnToMain();
2081 }
2082
2083 /**
2084 * Output a standard permission error page
2085 *
2086 * @param $errors Array: error message keys
2087 * @param $action String: action that was denied or null if unknown
2088 */
2089 public function showPermissionsErrorPage( $errors, $action = null ) {
2090 // For some action (read, edit, create and upload), display a "login to do this action"
2091 // error if all of the following conditions are met:
2092 // 1. the user is not logged in
2093 // 2. the only error is insufficient permissions (i.e. no block or something else)
2094 // 3. the error can be avoided simply by logging in
2095 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2096 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2097 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2098 && ( User::groupHasPermission( 'user', $action )
2099 || User::groupHasPermission( 'autoconfirmed', $action ) )
2100 ) {
2101 $displayReturnto = null;
2102
2103 # Due to bug 32276, if a user does not have read permissions,
2104 # $this->getTitle() will just give Special:Badtitle, which is
2105 # not especially useful as a returnto parameter. Use the title
2106 # from the request instead, if there was one.
2107 $request = $this->getRequest();
2108 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2109 if ( $action == 'edit' ) {
2110 $msg = 'whitelistedittext';
2111 $displayReturnto = $returnto;
2112 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2113 $msg = 'nocreatetext';
2114 } elseif ( $action == 'upload' ) {
2115 $msg = 'uploadnologintext';
2116 } else { # Read
2117 $msg = 'loginreqpagetext';
2118 $displayReturnto = Title::newMainPage();
2119 }
2120
2121 $query = array();
2122
2123 if ( $returnto ) {
2124 $query['returnto'] = $returnto->getPrefixedText();
2125
2126 if ( !$request->wasPosted() ) {
2127 $returntoquery = $request->getValues();
2128 unset( $returntoquery['title'] );
2129 unset( $returntoquery['returnto'] );
2130 unset( $returntoquery['returntoquery'] );
2131 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2132 }
2133 }
2134 $loginLink = Linker::linkKnown(
2135 SpecialPage::getTitleFor( 'Userlogin' ),
2136 $this->msg( 'loginreqlink' )->escaped(),
2137 array(),
2138 $query
2139 );
2140
2141 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2142 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2143
2144 # Don't return to a page the user can't read otherwise
2145 # we'll end up in a pointless loop
2146 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2147 $this->returnToMain( null, $displayReturnto );
2148 }
2149 } else {
2150 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2151 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2152 }
2153 }
2154
2155 /**
2156 * Display an error page indicating that a given version of MediaWiki is
2157 * required to use it
2158 *
2159 * @param $version Mixed: the version of MediaWiki needed to use the page
2160 */
2161 public function versionRequired( $version ) {
2162 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2163
2164 $this->addWikiMsg( 'versionrequiredtext', $version );
2165 $this->returnToMain();
2166 }
2167
2168 /**
2169 * Display an error page noting that a given permission bit is required.
2170 * @deprecated since 1.18, just throw the exception directly
2171 * @param $permission String: key required
2172 * @throws PermissionsError
2173 */
2174 public function permissionRequired( $permission ) {
2175 throw new PermissionsError( $permission );
2176 }
2177
2178 /**
2179 * Produce the stock "please login to use the wiki" page
2180 *
2181 * @deprecated in 1.19; throw the exception directly
2182 */
2183 public function loginToUse() {
2184 throw new PermissionsError( 'read' );
2185 }
2186
2187 /**
2188 * Format a list of error messages
2189 *
2190 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2191 * @param $action String: action that was denied or null if unknown
2192 * @return String: the wikitext error-messages, formatted into a list.
2193 */
2194 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2195 if ( $action == null ) {
2196 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2197 } else {
2198 $action_desc = $this->msg( "action-$action" )->plain();
2199 $text = $this->msg(
2200 'permissionserrorstext-withaction',
2201 count( $errors ),
2202 $action_desc
2203 )->plain() . "\n\n";
2204 }
2205
2206 if ( count( $errors ) > 1 ) {
2207 $text .= '<ul class="permissions-errors">' . "\n";
2208
2209 foreach( $errors as $error ) {
2210 $text .= '<li>';
2211 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2212 $text .= "</li>\n";
2213 }
2214 $text .= '</ul>';
2215 } else {
2216 $text .= "<div class=\"permissions-errors\">\n" .
2217 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2218 "\n</div>";
2219 }
2220
2221 return $text;
2222 }
2223
2224 /**
2225 * Display a page stating that the Wiki is in read-only mode,
2226 * and optionally show the source of the page that the user
2227 * was trying to edit. Should only be called (for this
2228 * purpose) after wfReadOnly() has returned true.
2229 *
2230 * For historical reasons, this function is _also_ used to
2231 * show the error message when a user tries to edit a page
2232 * they are not allowed to edit. (Unless it's because they're
2233 * blocked, then we show blockedPage() instead.) In this
2234 * case, the second parameter should be set to true and a list
2235 * of reasons supplied as the third parameter.
2236 *
2237 * @todo Needs to be split into multiple functions.
2238 *
2239 * @param $source String: source code to show (or null).
2240 * @param $protected Boolean: is this a permissions error?
2241 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2242 * @param $action String: action that was denied or null if unknown
2243 * @throws ReadOnlyError
2244 */
2245 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2246 $this->setRobotPolicy( 'noindex,nofollow' );
2247 $this->setArticleRelated( false );
2248
2249 // If no reason is given, just supply a default "I can't let you do
2250 // that, Dave" message. Should only occur if called by legacy code.
2251 if ( $protected && empty( $reasons ) ) {
2252 $reasons[] = array( 'badaccess-group0' );
2253 }
2254
2255 if ( !empty( $reasons ) ) {
2256 // Permissions error
2257 if( $source ) {
2258 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2259 $this->addBacklinkSubtitle( $this->getTitle() );
2260 } else {
2261 $this->setPageTitle( $this->msg( 'badaccess' ) );
2262 }
2263 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2264 } else {
2265 // Wiki is read only
2266 throw new ReadOnlyError;
2267 }
2268
2269 // Show source, if supplied
2270 if( is_string( $source ) ) {
2271 $this->addWikiMsg( 'viewsourcetext' );
2272
2273 $pageLang = $this->getTitle()->getPageLanguage();
2274 $params = array(
2275 'id' => 'wpTextbox1',
2276 'name' => 'wpTextbox1',
2277 'cols' => $this->getUser()->getOption( 'cols' ),
2278 'rows' => $this->getUser()->getOption( 'rows' ),
2279 'readonly' => 'readonly',
2280 'lang' => $pageLang->getHtmlCode(),
2281 'dir' => $pageLang->getDir(),
2282 );
2283 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2284
2285 // Show templates used by this article
2286 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2287 $this->addHTML( "<div class='templatesUsed'>
2288 $templates
2289 </div>
2290 " );
2291 }
2292
2293 # If the title doesn't exist, it's fairly pointless to print a return
2294 # link to it. After all, you just tried editing it and couldn't, so
2295 # what's there to do there?
2296 if( $this->getTitle()->exists() ) {
2297 $this->returnToMain( null, $this->getTitle() );
2298 }
2299 }
2300
2301 /**
2302 * Turn off regular page output and return an error reponse
2303 * for when rate limiting has triggered.
2304 */
2305 public function rateLimited() {
2306 throw new ThrottledError;
2307 }
2308
2309 /**
2310 * Show a warning about slave lag
2311 *
2312 * If the lag is higher than $wgSlaveLagCritical seconds,
2313 * then the warning is a bit more obvious. If the lag is
2314 * lower than $wgSlaveLagWarning, then no warning is shown.
2315 *
2316 * @param $lag Integer: slave lag
2317 */
2318 public function showLagWarning( $lag ) {
2319 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2320 if( $lag >= $wgSlaveLagWarning ) {
2321 $message = $lag < $wgSlaveLagCritical
2322 ? 'lag-warn-normal'
2323 : 'lag-warn-high';
2324 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2325 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2326 }
2327 }
2328
2329 public function showFatalError( $message ) {
2330 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2331
2332 $this->addHTML( $message );
2333 }
2334
2335 public function showUnexpectedValueError( $name, $val ) {
2336 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2337 }
2338
2339 public function showFileCopyError( $old, $new ) {
2340 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2341 }
2342
2343 public function showFileRenameError( $old, $new ) {
2344 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2345 }
2346
2347 public function showFileDeleteError( $name ) {
2348 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2349 }
2350
2351 public function showFileNotFoundError( $name ) {
2352 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2353 }
2354
2355 /**
2356 * Add a "return to" link pointing to a specified title
2357 *
2358 * @param $title Title to link
2359 * @param $query Array query string parameters
2360 * @param $text String text of the link (input is not escaped)
2361 * @param $options Options array to pass to Linker
2362 */
2363 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2364 if( in_array( 'http', $options ) ) {
2365 $proto = PROTO_HTTP;
2366 } elseif( in_array( 'https', $options ) ) {
2367 $proto = PROTO_HTTPS;
2368 } else {
2369 $proto = PROTO_RELATIVE;
2370 }
2371
2372 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL( '', false, $proto ) ) );
2373 $link = $this->msg( 'returnto' )->rawParams(
2374 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2375 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2376 }
2377
2378 /**
2379 * Add a "return to" link pointing to a specified title,
2380 * or the title indicated in the request, or else the main page
2381 *
2382 * @param $unused
2383 * @param $returnto Title or String to return to
2384 * @param $returntoquery String: query string for the return to link
2385 */
2386 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2387 if ( $returnto == null ) {
2388 $returnto = $this->getRequest()->getText( 'returnto' );
2389 }
2390
2391 if ( $returntoquery == null ) {
2392 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2393 }
2394
2395 if ( $returnto === '' ) {
2396 $returnto = Title::newMainPage();
2397 }
2398
2399 if ( is_object( $returnto ) ) {
2400 $titleObj = $returnto;
2401 } else {
2402 $titleObj = Title::newFromText( $returnto );
2403 }
2404 if ( !is_object( $titleObj ) ) {
2405 $titleObj = Title::newMainPage();
2406 }
2407
2408 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2409 }
2410
2411 /**
2412 * @param $sk Skin The given Skin
2413 * @param $includeStyle Boolean: unused
2414 * @return String: The doctype, opening "<html>", and head element.
2415 */
2416 public function headElement( Skin $sk, $includeStyle = true ) {
2417 global $wgContLang;
2418
2419 $userdir = $this->getLanguage()->getDir();
2420 $sitedir = $wgContLang->getDir();
2421
2422 if ( $sk->commonPrintStylesheet() ) {
2423 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2424 }
2425
2426 $ret = Html::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2427
2428 if ( $this->getHTMLTitle() == '' ) {
2429 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2430 }
2431
2432 $openHead = Html::openElement( 'head' );
2433 if ( $openHead ) {
2434 # Don't bother with the newline if $head == ''
2435 $ret .= "$openHead\n";
2436 }
2437
2438 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2439
2440 $ret .= implode( "\n", array(
2441 $this->getHeadLinks( null, true ),
2442 $this->buildCssLinks(),
2443 $this->getHeadScripts(),
2444 $this->getHeadItems()
2445 ) );
2446
2447 $closeHead = Html::closeElement( 'head' );
2448 if ( $closeHead ) {
2449 $ret .= "$closeHead\n";
2450 }
2451
2452 $bodyAttrs = array();
2453
2454 # Classes for LTR/RTL directionality support
2455 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2456
2457 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2458 # A <body> class is probably not the best way to do this . . .
2459 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2460 }
2461 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2462 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2463 $bodyAttrs['class'] .= ' action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2464
2465 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2466 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2467
2468 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2469
2470 return $ret;
2471 }
2472
2473 /**
2474 * Add the default ResourceLoader modules to this object
2475 */
2476 private function addDefaultModules() {
2477 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2478 $wgAjaxWatch, $wgResponsiveImages;
2479
2480 // Add base resources
2481 $this->addModules( array(
2482 'mediawiki.user',
2483 'mediawiki.page.startup',
2484 'mediawiki.page.ready',
2485 ) );
2486 if ( $wgIncludeLegacyJavaScript ) {
2487 $this->addModules( 'mediawiki.legacy.wikibits' );
2488 }
2489
2490 if ( $wgPreloadJavaScriptMwUtil ) {
2491 $this->addModules( 'mediawiki.util' );
2492 }
2493
2494 MWDebug::addModules( $this );
2495
2496 // Add various resources if required
2497 if ( $wgUseAjax ) {
2498 $this->addModules( 'mediawiki.legacy.ajax' );
2499
2500 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2501
2502 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2503 $this->addModules( 'mediawiki.page.watch.ajax' );
2504 }
2505
2506 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2507 $this->addModules( 'mediawiki.searchSuggest' );
2508 }
2509 }
2510
2511 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2512 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2513 }
2514
2515 # Crazy edit-on-double-click stuff
2516 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2517 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2518 }
2519
2520 // Support for high-density display images
2521 if ( $wgResponsiveImages ) {
2522 $this->addModules( 'mediawiki.hidpi' );
2523 }
2524 }
2525
2526 /**
2527 * Get a ResourceLoader object associated with this OutputPage
2528 *
2529 * @return ResourceLoader
2530 */
2531 public function getResourceLoader() {
2532 if ( is_null( $this->mResourceLoader ) ) {
2533 $this->mResourceLoader = new ResourceLoader();
2534 }
2535 return $this->mResourceLoader;
2536 }
2537
2538 /**
2539 * TODO: Document
2540 * @param $modules Array/string with the module name(s)
2541 * @param $only String ResourceLoaderModule TYPE_ class constant
2542 * @param $useESI boolean
2543 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2544 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2545 * @return string html "<script>" and "<style>" tags
2546 */
2547 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2548 global $wgResourceLoaderUseESI;
2549
2550 $modules = (array) $modules;
2551
2552 if ( !count( $modules ) ) {
2553 return '';
2554 }
2555
2556 if ( count( $modules ) > 1 ) {
2557 // Remove duplicate module requests
2558 $modules = array_unique( $modules );
2559 // Sort module names so requests are more uniform
2560 sort( $modules );
2561
2562 if ( ResourceLoader::inDebugMode() ) {
2563 // Recursively call us for every item
2564 $links = '';
2565 foreach ( $modules as $name ) {
2566 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2567 }
2568 return $links;
2569 }
2570 }
2571
2572 // Create keyed-by-group list of module objects from modules list
2573 $groups = array();
2574 $resourceLoader = $this->getResourceLoader();
2575 foreach ( $modules as $name ) {
2576 $module = $resourceLoader->getModule( $name );
2577 # Check that we're allowed to include this module on this page
2578 if ( !$module
2579 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2580 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2581 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2582 && $only == ResourceLoaderModule::TYPE_STYLES )
2583 )
2584 {
2585 continue;
2586 }
2587
2588 $group = $module->getGroup();
2589 if ( !isset( $groups[$group] ) ) {
2590 $groups[$group] = array();
2591 }
2592 $groups[$group][$name] = $module;
2593 }
2594
2595 $links = '';
2596 foreach ( $groups as $group => $grpModules ) {
2597 // Special handling for user-specific groups
2598 $user = null;
2599 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2600 $user = $this->getUser()->getName();
2601 }
2602
2603 // Create a fake request based on the one we are about to make so modules return
2604 // correct timestamp and emptiness data
2605 $query = ResourceLoader::makeLoaderQuery(
2606 array(), // modules; not determined yet
2607 $this->getLanguage()->getCode(),
2608 $this->getSkin()->getSkinName(),
2609 $user,
2610 null, // version; not determined yet
2611 ResourceLoader::inDebugMode(),
2612 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2613 $this->isPrintable(),
2614 $this->getRequest()->getBool( 'handheld' ),
2615 $extraQuery
2616 );
2617 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2618 // Extract modules that know they're empty
2619 $emptyModules = array ();
2620 foreach ( $grpModules as $key => $module ) {
2621 if ( $module->isKnownEmpty( $context ) ) {
2622 $emptyModules[$key] = 'ready';
2623 unset( $grpModules[$key] );
2624 }
2625 }
2626 // Inline empty modules: since they're empty, just mark them as 'ready'
2627 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule::TYPE_STYLES ) {
2628 // If we're only getting the styles, we don't need to do anything for empty modules.
2629 $links .= Html::inlineScript(
2630
2631 ResourceLoader::makeLoaderConditionalScript(
2632
2633 ResourceLoader::makeLoaderStateScript( $emptyModules )
2634
2635 )
2636
2637 ) . "\n";
2638 }
2639
2640 // If there are no modules left, skip this group
2641 if ( count( $grpModules ) === 0 ) {
2642 continue;
2643 }
2644
2645 // Inline private modules. These can't be loaded through load.php for security
2646 // reasons, see bug 34907. Note that these modules should be loaded from
2647 // getHeadScripts() before the first loader call. Otherwise other modules can't
2648 // properly use them as dependencies (bug 30914)
2649 if ( $group === 'private' ) {
2650 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2651 $links .= Html::inlineStyle(
2652 $resourceLoader->makeModuleResponse( $context, $grpModules )
2653 );
2654 } else {
2655 $links .= Html::inlineScript(
2656 ResourceLoader::makeLoaderConditionalScript(
2657 $resourceLoader->makeModuleResponse( $context, $grpModules )
2658 )
2659 );
2660 }
2661 $links .= "\n";
2662 continue;
2663 }
2664 // Special handling for the user group; because users might change their stuff
2665 // on-wiki like user pages, or user preferences; we need to find the highest
2666 // timestamp of these user-changable modules so we can ensure cache misses on change
2667 // This should NOT be done for the site group (bug 27564) because anons get that too
2668 // and we shouldn't be putting timestamps in Squid-cached HTML
2669 $version = null;
2670 if ( $group === 'user' ) {
2671 // Get the maximum timestamp
2672 $timestamp = 1;
2673 foreach ( $grpModules as $module ) {
2674 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2675 }
2676 // Add a version parameter so cache will break when things change
2677 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2678 }
2679
2680 $url = ResourceLoader::makeLoaderURL(
2681 array_keys( $grpModules ),
2682 $this->getLanguage()->getCode(),
2683 $this->getSkin()->getSkinName(),
2684 $user,
2685 $version,
2686 ResourceLoader::inDebugMode(),
2687 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2688 $this->isPrintable(),
2689 $this->getRequest()->getBool( 'handheld' ),
2690 $extraQuery
2691 );
2692 if ( $useESI && $wgResourceLoaderUseESI ) {
2693 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2694 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2695 $link = Html::inlineStyle( $esi );
2696 } else {
2697 $link = Html::inlineScript( $esi );
2698 }
2699 } else {
2700 // Automatically select style/script elements
2701 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2702 $link = Html::linkedStyle( $url );
2703 } else if ( $loadCall ) {
2704 $link = Html::inlineScript(
2705 ResourceLoader::makeLoaderConditionalScript(
2706 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2707 )
2708 );
2709 } else {
2710 $link = Html::linkedScript( $url );
2711 }
2712 }
2713
2714 if( $group == 'noscript' ) {
2715 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2716 } else {
2717 $links .= $link . "\n";
2718 }
2719 }
2720 return $links;
2721 }
2722
2723 /**
2724 * JS stuff to put in the "<head>". This is the startup module, config
2725 * vars and modules marked with position 'top'
2726 *
2727 * @return String: HTML fragment
2728 */
2729 function getHeadScripts() {
2730 global $wgResourceLoaderExperimentalAsyncLoading;
2731
2732 // Startup - this will immediately load jquery and mediawiki modules
2733 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2734
2735 // Load config before anything else
2736 $scripts .= Html::inlineScript(
2737 ResourceLoader::makeLoaderConditionalScript(
2738 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2739 )
2740 );
2741
2742 // Load embeddable private modules before any loader links
2743 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2744 // in mw.loader.implement() calls and deferred until mw.user is available
2745 $embedScripts = array( 'user.options', 'user.tokens' );
2746 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2747
2748 // Script and Messages "only" requests marked for top inclusion
2749 // Messages should go first
2750 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2751 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2752
2753 // Modules requests - let the client calculate dependencies and batch requests as it likes
2754 // Only load modules that have marked themselves for loading at the top
2755 $modules = $this->getModules( true, 'top' );
2756 if ( $modules ) {
2757 $scripts .= Html::inlineScript(
2758 ResourceLoader::makeLoaderConditionalScript(
2759 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2760 )
2761 );
2762 }
2763
2764 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2765 $scripts .= $this->getScriptsForBottomQueue( true );
2766 }
2767
2768 return $scripts;
2769 }
2770
2771 /**
2772 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2773 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2774 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2775 * user preferences, site JS and user JS
2776 *
2777 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2778 * @return string
2779 */
2780 function getScriptsForBottomQueue( $inHead ) {
2781 global $wgUseSiteJs, $wgAllowUserJs;
2782
2783 // Script and Messages "only" requests marked for bottom inclusion
2784 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2785 // Messages should go first
2786 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2787 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2788 /* $loadCall = */ $inHead
2789 );
2790 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2791 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2792 /* $loadCall = */ $inHead
2793 );
2794
2795 // Modules requests - let the client calculate dependencies and batch requests as it likes
2796 // Only load modules that have marked themselves for loading at the bottom
2797 $modules = $this->getModules( true, 'bottom' );
2798 if ( $modules ) {
2799 $scripts .= Html::inlineScript(
2800 ResourceLoader::makeLoaderConditionalScript(
2801 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2802 )
2803 );
2804 }
2805
2806 // Legacy Scripts
2807 $scripts .= "\n" . $this->mScripts;
2808
2809 $defaultModules = array();
2810
2811 // Add site JS if enabled
2812 if ( $wgUseSiteJs ) {
2813 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2814 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2815 );
2816 $defaultModules['site'] = 'loading';
2817 } else {
2818 // The wiki is configured to not allow a site module.
2819 $defaultModules['site'] = 'missing';
2820 }
2821
2822 // Add user JS if enabled
2823 if ( $wgAllowUserJs ) {
2824 if ( $this->getUser()->isLoggedIn() ) {
2825 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2826 # XXX: additional security check/prompt?
2827 // We're on a preview of a JS subpage
2828 // Exclude this page from the user module in case it's in there (bug 26283)
2829 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2830 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2831 );
2832 // Load the previewed JS
2833 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2834 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2835 // asynchronously and may arrive *after* the inline script here. So the previewed code
2836 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2837 } else {
2838 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2839 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
2840 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2841 );
2842 }
2843 $defaultModules['user'] = 'loading';
2844 } else {
2845 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2846 // blocking default gadgets that might depend on it. Although arguably default-enabled
2847 // gadgets should not depend on the user module, it's harmless and less error-prone to
2848 // handle this case.
2849 $defaultModules['user'] = 'ready';
2850 }
2851 } else {
2852 // User JS disabled
2853 $defaultModules['user'] = 'missing';
2854 }
2855
2856 // Group JS is only enabled if site JS is enabled.
2857 if ( $wgUseSiteJs ) {
2858 if ( $this->getUser()->isLoggedIn() ) {
2859 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
2860 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2861 );
2862 $defaultModules['user.groups'] = 'loading';
2863 } else {
2864 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2865 // avoid blocking gadgets that might depend upon the module.
2866 $defaultModules['user.groups'] = 'ready';
2867 }
2868 } else {
2869 // Site (and group JS) disabled
2870 $defaultModules['user.groups'] = 'missing';
2871 }
2872
2873 $loaderInit = '';
2874 if ( $inHead ) {
2875 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2876 foreach ( $defaultModules as $m => $state ) {
2877 if ( $state == 'loading' ) {
2878 unset( $defaultModules[$m] );
2879 }
2880 }
2881 }
2882 if ( count( $defaultModules ) > 0 ) {
2883 $loaderInit = Html::inlineScript(
2884 ResourceLoader::makeLoaderConditionalScript(
2885 ResourceLoader::makeLoaderStateScript( $defaultModules )
2886 )
2887 ) . "\n";
2888 }
2889 return $loaderInit . $scripts;
2890 }
2891
2892 /**
2893 * JS stuff to put at the bottom of the "<body>"
2894 * @return string
2895 */
2896 function getBottomScripts() {
2897 global $wgResourceLoaderExperimentalAsyncLoading;
2898 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2899 return $this->getScriptsForBottomQueue( false );
2900 } else {
2901 return '';
2902 }
2903 }
2904
2905 /**
2906 * Add one or more variables to be set in mw.config in JavaScript.
2907 *
2908 * @param $keys {String|Array} Key or array of key/value pairs.
2909 * @param $value {Mixed} [optional] Value of the configuration variable.
2910 */
2911 public function addJsConfigVars( $keys, $value = null ) {
2912 if ( is_array( $keys ) ) {
2913 foreach ( $keys as $key => $value ) {
2914 $this->mJsConfigVars[$key] = $value;
2915 }
2916 return;
2917 }
2918
2919 $this->mJsConfigVars[$keys] = $value;
2920 }
2921
2922
2923 /**
2924 * Get an array containing the variables to be set in mw.config in JavaScript.
2925 *
2926 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2927 * This is only public until that function is removed. You have been warned.
2928 *
2929 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2930 * - in other words, page-independent/site-wide variables (without state).
2931 * You will only be adding bloat to the html page and causing page caches to
2932 * have to be purged on configuration changes.
2933 * @return array
2934 */
2935 public function getJSVars() {
2936 global $wgContLang;
2937
2938 $latestRevID = 0;
2939 $pageID = 0;
2940 $canonicalName = false; # bug 21115
2941
2942 $title = $this->getTitle();
2943 $ns = $title->getNamespace();
2944 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2945
2946 // Get the relevant title so that AJAX features can use the correct page name
2947 // when making API requests from certain special pages (bug 34972).
2948 $relevantTitle = $this->getSkin()->getRelevantTitle();
2949
2950 if ( $ns == NS_SPECIAL ) {
2951 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2952 } elseif ( $this->canUseWikiPage() ) {
2953 $wikiPage = $this->getWikiPage();
2954 $latestRevID = $wikiPage->getLatest();
2955 $pageID = $wikiPage->getId();
2956 }
2957
2958 $lang = $title->getPageLanguage();
2959
2960 // Pre-process information
2961 $separatorTransTable = $lang->separatorTransformTable();
2962 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
2963 $compactSeparatorTransTable = array(
2964 implode( "\t", array_keys( $separatorTransTable ) ),
2965 implode( "\t", $separatorTransTable ),
2966 );
2967 $digitTransTable = $lang->digitTransformTable();
2968 $digitTransTable = $digitTransTable ? $digitTransTable : array();
2969 $compactDigitTransTable = array(
2970 implode( "\t", array_keys( $digitTransTable ) ),
2971 implode( "\t", $digitTransTable ),
2972 );
2973
2974 $vars = array(
2975 'wgCanonicalNamespace' => $nsname,
2976 'wgCanonicalSpecialPageName' => $canonicalName,
2977 'wgNamespaceNumber' => $title->getNamespace(),
2978 'wgPageName' => $title->getPrefixedDBKey(),
2979 'wgTitle' => $title->getText(),
2980 'wgCurRevisionId' => $latestRevID,
2981 'wgArticleId' => $pageID,
2982 'wgIsArticle' => $this->isArticle(),
2983 'wgAction' => Action::getActionName( $this->getContext() ),
2984 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
2985 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2986 'wgCategories' => $this->getCategories(),
2987 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2988 'wgPageContentLanguage' => $lang->getCode(),
2989 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2990 'wgDigitTransformTable' => $compactDigitTransTable,
2991 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
2992 'wgMonthNames' => $lang->getMonthNamesArray(),
2993 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
2994 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2995 );
2996 if ( $wgContLang->hasVariants() ) {
2997 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2998 }
2999 foreach ( $title->getRestrictionTypes() as $type ) {
3000 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3001 }
3002 if ( $title->isMainPage() ) {
3003 $vars['wgIsMainPage'] = true;
3004 }
3005 if ( $this->mRedirectedFrom ) {
3006 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBKey();
3007 }
3008
3009 // Allow extensions to add their custom variables to the mw.config map.
3010 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3011 // page-dependant but site-wide (without state).
3012 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3013 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3014
3015 // Merge in variables from addJsConfigVars last
3016 return array_merge( $vars, $this->mJsConfigVars );
3017 }
3018
3019 /**
3020 * To make it harder for someone to slip a user a fake
3021 * user-JavaScript or user-CSS preview, a random token
3022 * is associated with the login session. If it's not
3023 * passed back with the preview request, we won't render
3024 * the code.
3025 *
3026 * @return bool
3027 */
3028 public function userCanPreview() {
3029 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3030 || !$this->getRequest()->wasPosted()
3031 || !$this->getUser()->matchEditToken(
3032 $this->getRequest()->getVal( 'wpEditToken' ) )
3033 ) {
3034 return false;
3035 }
3036 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3037 return false;
3038 }
3039
3040 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3041 }
3042
3043 /**
3044 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3045 *
3046 * @return array in format "link name or number => 'link html'".
3047 */
3048 public function getHeadLinksArray( $addContentType = false ) {
3049 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3050 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3051 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3052 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3053 $wgRightsPage, $wgRightsUrl;
3054
3055 $tags = array();
3056
3057 $canonicalUrl = $this->mCanonicalUrl;
3058
3059 if ( $addContentType ) {
3060 if ( $wgHtml5 ) {
3061 # More succinct than <meta http-equiv=Content-Type>, has the
3062 # same effect
3063 $tags['meta-charset'] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
3064 } else {
3065 $tags['meta-content-type'] = Html::element( 'meta', array(
3066 'http-equiv' => 'Content-Type',
3067 'content' => "$wgMimeType; charset=UTF-8"
3068 ) );
3069 $tags['meta-content-style-type'] = Html::element( 'meta', array( // bug 15835
3070 'http-equiv' => 'Content-Style-Type',
3071 'content' => 'text/css'
3072 ) );
3073 }
3074 }
3075
3076 $tags['meta-generator'] = Html::element( 'meta', array(
3077 'name' => 'generator',
3078 'content' => "MediaWiki $wgVersion",
3079 ) );
3080
3081 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3082 if( $p !== 'index,follow' ) {
3083 // http://www.robotstxt.org/wc/meta-user.html
3084 // Only show if it's different from the default robots policy
3085 $tags['meta-robots'] = Html::element( 'meta', array(
3086 'name' => 'robots',
3087 'content' => $p,
3088 ) );
3089 }
3090
3091 if ( count( $this->mKeywords ) > 0 ) {
3092 $strip = array(
3093 "/<.*?" . ">/" => '',
3094 "/_/" => ' '
3095 );
3096 $tags['meta-keywords'] = Html::element( 'meta', array(
3097 'name' => 'keywords',
3098 'content' => preg_replace(
3099 array_keys( $strip ),
3100 array_values( $strip ),
3101 implode( ',', $this->mKeywords )
3102 )
3103 ) );
3104 }
3105
3106 foreach ( $this->mMetatags as $tag ) {
3107 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3108 $a = 'http-equiv';
3109 $tag[0] = substr( $tag[0], 5 );
3110 } else {
3111 $a = 'name';
3112 }
3113 $tagName = "meta-{$tag[0]}";
3114 if ( isset( $tags[$tagName] ) ) {
3115 $tagName .= $tag[1];
3116 }
3117 $tags[$tagName] = Html::element( 'meta',
3118 array(
3119 $a => $tag[0],
3120 'content' => $tag[1]
3121 )
3122 );
3123 }
3124
3125 foreach ( $this->mLinktags as $tag ) {
3126 $tags[] = Html::element( 'link', $tag );
3127 }
3128
3129 # Universal edit button
3130 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3131 $user = $this->getUser();
3132 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3133 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3134 // Original UniversalEditButton
3135 $msg = $this->msg( 'edit' )->text();
3136 $tags['universal-edit-button'] = Html::element( 'link', array(
3137 'rel' => 'alternate',
3138 'type' => 'application/x-wiki',
3139 'title' => $msg,
3140 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3141 ) );
3142 // Alternate edit link
3143 $tags['alternative-edit'] = Html::element( 'link', array(
3144 'rel' => 'edit',
3145 'title' => $msg,
3146 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3147 ) );
3148 }
3149 }
3150
3151 # Generally the order of the favicon and apple-touch-icon links
3152 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3153 # uses whichever one appears later in the HTML source. Make sure
3154 # apple-touch-icon is specified first to avoid this.
3155 if ( $wgAppleTouchIcon !== false ) {
3156 $tags['apple-touch-icon'] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3157 }
3158
3159 if ( $wgFavicon !== false ) {
3160 $tags['favicon'] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3161 }
3162
3163 # OpenSearch description link
3164 $tags['opensearch'] = Html::element( 'link', array(
3165 'rel' => 'search',
3166 'type' => 'application/opensearchdescription+xml',
3167 'href' => wfScript( 'opensearch_desc' ),
3168 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3169 ) );
3170
3171 if ( $wgEnableAPI ) {
3172 # Real Simple Discovery link, provides auto-discovery information
3173 # for the MediaWiki API (and potentially additional custom API
3174 # support such as WordPress or Twitter-compatible APIs for a
3175 # blogging extension, etc)
3176 $tags['rsd'] = Html::element( 'link', array(
3177 'rel' => 'EditURI',
3178 'type' => 'application/rsd+xml',
3179 // Output a protocol-relative URL here if $wgServer is protocol-relative
3180 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3181 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
3182 ) );
3183 }
3184
3185
3186 # Language variants
3187 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3188 $lang = $this->getTitle()->getPageLanguage();
3189 if ( $lang->hasVariants() ) {
3190
3191 $urlvar = $lang->getURLVariant();
3192
3193 if ( !$urlvar ) {
3194 $variants = $lang->getVariants();
3195 foreach ( $variants as $_v ) {
3196 $tags["variant-$_v"] = Html::element( 'link', array(
3197 'rel' => 'alternate',
3198 'hreflang' => $_v,
3199 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3200 );
3201 }
3202 } else {
3203 $canonicalUrl = $this->getTitle()->getLocalURL();
3204 }
3205 }
3206 }
3207
3208 # Copyright
3209 $copyright = '';
3210 if ( $wgRightsPage ) {
3211 $copy = Title::newFromText( $wgRightsPage );
3212
3213 if ( $copy ) {
3214 $copyright = $copy->getLocalURL();
3215 }
3216 }
3217
3218 if ( !$copyright && $wgRightsUrl ) {
3219 $copyright = $wgRightsUrl;
3220 }
3221
3222 if ( $copyright ) {
3223 $tags['copyright'] = Html::element( 'link', array(
3224 'rel' => 'copyright',
3225 'href' => $copyright )
3226 );
3227 }
3228
3229 # Feeds
3230 if ( $wgFeed ) {
3231 foreach( $this->getSyndicationLinks() as $format => $link ) {
3232 # Use the page name for the title. In principle, this could
3233 # lead to issues with having the same name for different feeds
3234 # corresponding to the same page, but we can't avoid that at
3235 # this low a level.
3236
3237 $tags[] = $this->feedLink(
3238 $format,
3239 $link,
3240 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3241 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3242 );
3243 }
3244
3245 # Recent changes feed should appear on every page (except recentchanges,
3246 # that would be redundant). Put it after the per-page feed to avoid
3247 # changing existing behavior. It's still available, probably via a
3248 # menu in your browser. Some sites might have a different feed they'd
3249 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3250 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3251 # If so, use it instead.
3252 if ( $wgOverrideSiteFeed ) {
3253 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3254 // Note, this->feedLink escapes the url.
3255 $tags[] = $this->feedLink(
3256 $type,
3257 $feedUrl,
3258 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3259 );
3260 }
3261 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3262 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3263 foreach ( $wgAdvertisedFeedTypes as $format ) {
3264 $tags[] = $this->feedLink(
3265 $format,
3266 $rctitle->getLocalURL( "feed={$format}" ),
3267 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3268 );
3269 }
3270 }
3271 }
3272
3273 # Canonical URL
3274 global $wgEnableCanonicalServerLink;
3275 if ( $wgEnableCanonicalServerLink ) {
3276 if ( $canonicalUrl !== false ) {
3277 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3278 } else {
3279 $reqUrl = $this->getRequest()->getRequestURL();
3280 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3281 }
3282 }
3283 if ( $canonicalUrl !== false ) {
3284 $tags[] = Html::element( 'link', array(
3285 'rel' => 'canonical',
3286 'href' => $canonicalUrl
3287 ) );
3288 }
3289
3290 return $tags;
3291 }
3292
3293 /**
3294 * @param $unused
3295 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3296 *
3297 * @return string HTML tag links to be put in the header.
3298 */
3299 public function getHeadLinks( $unused = null, $addContentType = false ) {
3300 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3301 }
3302
3303 /**
3304 * Generate a "<link rel/>" for a feed.
3305 *
3306 * @param $type String: feed type
3307 * @param $url String: URL to the feed
3308 * @param $text String: value of the "title" attribute
3309 * @return String: HTML fragment
3310 */
3311 private function feedLink( $type, $url, $text ) {
3312 return Html::element( 'link', array(
3313 'rel' => 'alternate',
3314 'type' => "application/$type+xml",
3315 'title' => $text,
3316 'href' => $url )
3317 );
3318 }
3319
3320 /**
3321 * Add a local or specified stylesheet, with the given media options.
3322 * Meant primarily for internal use...
3323 *
3324 * @param $style String: URL to the file
3325 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3326 * @param $condition String: for IE conditional comments, specifying an IE version
3327 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3328 */
3329 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3330 $options = array();
3331 // Even though we expect the media type to be lowercase, but here we
3332 // force it to lowercase to be safe.
3333 if( $media ) {
3334 $options['media'] = $media;
3335 }
3336 if( $condition ) {
3337 $options['condition'] = $condition;
3338 }
3339 if( $dir ) {
3340 $options['dir'] = $dir;
3341 }
3342 $this->styles[$style] = $options;
3343 }
3344
3345 /**
3346 * Adds inline CSS styles
3347 * @param $style_css Mixed: inline CSS
3348 * @param $flip String: Set to 'flip' to flip the CSS if needed
3349 */
3350 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3351 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3352 # If wanted, and the interface is right-to-left, flip the CSS
3353 $style_css = CSSJanus::transform( $style_css, true, false );
3354 }
3355 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3356 }
3357
3358 /**
3359 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3360 * These will be applied to various media & IE conditionals.
3361 *
3362 * @return string
3363 */
3364 public function buildCssLinks() {
3365 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3366 $wgLang, $wgContLang;
3367
3368 $this->getSkin()->setupSkinUserCss( $this );
3369
3370 // Add ResourceLoader styles
3371 // Split the styles into four groups
3372 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3373 $otherTags = ''; // Tags to append after the normal <link> tags
3374 $resourceLoader = $this->getResourceLoader();
3375
3376 $moduleStyles = $this->getModuleStyles();
3377
3378 // Per-site custom styles
3379 if ( $wgUseSiteCss ) {
3380 $moduleStyles[] = 'site';
3381 $moduleStyles[] = 'noscript';
3382 if( $this->getUser()->isLoggedIn() ) {
3383 $moduleStyles[] = 'user.groups';
3384 }
3385 }
3386
3387 // Per-user custom styles
3388 if ( $wgAllowUserCss ) {
3389 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3390 // We're on a preview of a CSS subpage
3391 // Exclude this page from the user module in case it's in there (bug 26283)
3392 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3393 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3394 );
3395
3396 // Load the previewed CSS
3397 // If needed, Janus it first. This is user-supplied CSS, so it's
3398 // assumed to be right for the content language directionality.
3399 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3400 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3401 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3402 }
3403 $otherTags .= Html::inlineStyle( $previewedCSS );
3404 } else {
3405 // Load the user styles normally
3406 $moduleStyles[] = 'user';
3407 }
3408 }
3409
3410 // Per-user preference styles
3411 if ( $wgAllowUserCssPrefs ) {
3412 $moduleStyles[] = 'user.cssprefs';
3413 }
3414
3415 foreach ( $moduleStyles as $name ) {
3416 $module = $resourceLoader->getModule( $name );
3417 if ( !$module ) {
3418 continue;
3419 }
3420 $group = $module->getGroup();
3421 // Modules in groups named "other" or anything different than "user", "site" or "private"
3422 // will be placed in the "other" group
3423 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3424 }
3425
3426 // We want site, private and user styles to override dynamically added styles from modules, but we want
3427 // dynamically added styles to override statically added styles from other modules. So the order
3428 // has to be other, dynamic, site, private, user
3429 // Add statically added styles for other modules
3430 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3431 // Add normal styles added through addStyle()/addInlineStyle() here
3432 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3433 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3434 // We use a <meta> tag with a made-up name for this because that's valid HTML
3435 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3436
3437 // Add site, private and user styles
3438 // 'private' at present only contains user.options, so put that before 'user'
3439 // Any future private modules will likely have a similar user-specific character
3440 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3441 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3442 ResourceLoaderModule::TYPE_STYLES
3443 );
3444 }
3445
3446 // Add stuff in $otherTags (previewed user CSS if applicable)
3447 $ret .= $otherTags;
3448 return $ret;
3449 }
3450
3451 /**
3452 * @return Array
3453 */
3454 public function buildCssLinksArray() {
3455 $links = array();
3456
3457 // Add any extension CSS
3458 foreach ( $this->mExtStyles as $url ) {
3459 $this->addStyle( $url );
3460 }
3461 $this->mExtStyles = array();
3462
3463 foreach( $this->styles as $file => $options ) {
3464 $link = $this->styleLink( $file, $options );
3465 if( $link ) {
3466 $links[$file] = $link;
3467 }
3468 }
3469 return $links;
3470 }
3471
3472 /**
3473 * Generate \<link\> tags for stylesheets
3474 *
3475 * @param $style String: URL to the file
3476 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3477 * keys
3478 * @return String: HTML fragment
3479 */
3480 protected function styleLink( $style, $options ) {
3481 if( isset( $options['dir'] ) ) {
3482 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3483 return '';
3484 }
3485 }
3486
3487 if( isset( $options['media'] ) ) {
3488 $media = self::transformCssMedia( $options['media'] );
3489 if( is_null( $media ) ) {
3490 return '';
3491 }
3492 } else {
3493 $media = 'all';
3494 }
3495
3496 if( substr( $style, 0, 1 ) == '/' ||
3497 substr( $style, 0, 5 ) == 'http:' ||
3498 substr( $style, 0, 6 ) == 'https:' ) {
3499 $url = $style;
3500 } else {
3501 global $wgStylePath, $wgStyleVersion;
3502 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3503 }
3504
3505 $link = Html::linkedStyle( $url, $media );
3506
3507 if( isset( $options['condition'] ) ) {
3508 $condition = htmlspecialchars( $options['condition'] );
3509 $link = "<!--[if $condition]>$link<![endif]-->";
3510 }
3511 return $link;
3512 }
3513
3514 /**
3515 * Transform "media" attribute based on request parameters
3516 *
3517 * @param $media String: current value of the "media" attribute
3518 * @return String: modified value of the "media" attribute, or null to skip
3519 * this stylesheet
3520 */
3521 public static function transformCssMedia( $media ) {
3522 global $wgRequest, $wgHandheldForIPhone;
3523
3524 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3525 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3526
3527 // Switch in on-screen display for media testing
3528 $switches = array(
3529 'printable' => 'print',
3530 'handheld' => 'handheld',
3531 );
3532 foreach( $switches as $switch => $targetMedia ) {
3533 if( $wgRequest->getBool( $switch ) ) {
3534 if( $media == $targetMedia ) {
3535 $media = '';
3536 } elseif( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3537 // This regex will not attempt to understand a comma-separated media_query_list
3538 //
3539 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3540 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3541 //
3542 // If it's a print request, we never want any kind of screen styesheets
3543 // If it's a handheld request (currently the only other choice with a switch),
3544 // we don't want simple 'screen' but we might want screen queries that
3545 // have a max-width or something, so we'll pass all others on and let the
3546 // client do the query.
3547 if( $targetMedia == 'print' || $media == 'screen' ) {
3548 return null;
3549 }
3550 }
3551 }
3552 }
3553
3554 // Expand longer media queries as iPhone doesn't grok 'handheld'
3555 if( $wgHandheldForIPhone ) {
3556 $mediaAliases = array(
3557 'screen' => 'screen and (min-device-width: 481px)',
3558 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3559 );
3560
3561 if( isset( $mediaAliases[$media] ) ) {
3562 $media = $mediaAliases[$media];
3563 }
3564 }
3565
3566 return $media;
3567 }
3568
3569 /**
3570 * Add a wikitext-formatted message to the output.
3571 * This is equivalent to:
3572 *
3573 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3574 */
3575 public function addWikiMsg( /*...*/ ) {
3576 $args = func_get_args();
3577 $name = array_shift( $args );
3578 $this->addWikiMsgArray( $name, $args );
3579 }
3580
3581 /**
3582 * Add a wikitext-formatted message to the output.
3583 * Like addWikiMsg() except the parameters are taken as an array
3584 * instead of a variable argument list.
3585 *
3586 * @param $name string
3587 * @param $args array
3588 */
3589 public function addWikiMsgArray( $name, $args ) {
3590 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3591 }
3592
3593 /**
3594 * This function takes a number of message/argument specifications, wraps them in
3595 * some overall structure, and then parses the result and adds it to the output.
3596 *
3597 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3598 * on. The subsequent arguments may either be strings, in which case they are the
3599 * message names, or arrays, in which case the first element is the message name,
3600 * and subsequent elements are the parameters to that message.
3601 *
3602 * Don't use this for messages that are not in users interface language.
3603 *
3604 * For example:
3605 *
3606 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3607 *
3608 * Is equivalent to:
3609 *
3610 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3611 *
3612 * The newline after opening div is needed in some wikitext. See bug 19226.
3613 *
3614 * @param $wrap string
3615 */
3616 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3617 $msgSpecs = func_get_args();
3618 array_shift( $msgSpecs );
3619 $msgSpecs = array_values( $msgSpecs );
3620 $s = $wrap;
3621 foreach ( $msgSpecs as $n => $spec ) {
3622 if ( is_array( $spec ) ) {
3623 $args = $spec;
3624 $name = array_shift( $args );
3625 if ( isset( $args['options'] ) ) {
3626 unset( $args['options'] );
3627 wfDeprecated(
3628 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3629 '1.20'
3630 );
3631 }
3632 } else {
3633 $args = array();
3634 $name = $spec;
3635 }
3636 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3637 }
3638 $this->addWikiText( $s );
3639 }
3640
3641 /**
3642 * Include jQuery core. Use this to avoid loading it multiple times
3643 * before we get a usable script loader.
3644 *
3645 * @param $modules Array: list of jQuery modules which should be loaded
3646 * @return Array: the list of modules which were not loaded.
3647 * @since 1.16
3648 * @deprecated since 1.17
3649 */
3650 public function includeJQuery( $modules = array() ) {
3651 return array();
3652 }
3653
3654 }