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