Note that jquery.json will be removed in 1.25
[lhc/web/wiklou.git] / includes / Skin.php
1 <?php
2 /**
3 * Base class for all skins.
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 * @defgroup Skins Skins
25 */
26
27 /**
28 * The main skin class which provides methods and properties for all other skins.
29 *
30 * See docs/skin.txt for more information.
31 *
32 * @ingroup Skins
33 */
34 abstract class Skin extends ContextSource {
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
38
39 /**
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
42 */
43 public $stylename = null;
44
45 /**
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
48 */
49 static function getSkinNames() {
50 global $wgValidSkinNames;
51 static $skinsInitialised = false;
52
53 if ( !$skinsInitialised || !count( $wgValidSkinNames ) ) {
54 # Get a list of available skins
55 # Build using the regular expression '^(.*).php$'
56 # Array keys are all lower case, array value keep the case used by filename
57 #
58 wfProfileIn( __METHOD__ . '-init' );
59
60 global $wgStyleDirectory;
61
62 $skinDir = dir( $wgStyleDirectory );
63
64 if ( $skinDir !== false && $skinDir !== null ) {
65 # while code from www.php.net
66 while ( false !== ( $file = $skinDir->read() ) ) {
67 // Skip non-PHP files, hidden files, and '.dep' includes
68 $matches = array();
69
70 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
71 $aSkin = $matches[1];
72
73 // Explicitly disallow loading core skins via the autodiscovery mechanism.
74 //
75 // They should be loaded already (in a non-autodicovery way), but old files might still
76 // exist on the server because our MW version upgrade process is widely documented as
77 // requiring just copying over all files, without removing old ones.
78 //
79 // This is one of the reasons we should have never used autodiscovery in the first
80 // place. This hack can be safely removed when autodiscovery is gone.
81 if ( in_array( $aSkin, array( 'CologneBlue', 'Modern', 'MonoBook', 'Vector' ) ) ) {
82 wfLogWarning(
83 "An old copy of the $aSkin skin was found in your skins/ directory. " .
84 "You should remove it to avoid problems in the future." .
85 "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for details."
86 );
87 continue;
88 }
89
90 wfLogWarning(
91 "A skin using autodiscovery mechanism, $aSkin, was found in your skins/ directory. " .
92 "The mechanism will be removed in MediaWiki 1.25 and the skin will no longer be recognized. " .
93 "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for information how to fix this."
94 );
95 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
96 }
97 }
98 $skinDir->close();
99 }
100 $skinsInitialised = true;
101 wfProfileOut( __METHOD__ . '-init' );
102 }
103 return $wgValidSkinNames;
104 }
105
106 /**
107 * Fetch the skinname messages for available skins.
108 * @return string[]
109 */
110 static function getSkinNameMessages() {
111 $messages = array();
112 foreach ( self::getSkinNames() as $skinKey => $skinName ) {
113 $messages[] = "skinname-$skinKey";
114 }
115 return $messages;
116 }
117
118 /**
119 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
120 * Useful for Special:Preferences and other places where you
121 * only want to show skins users _can_ use.
122 * @return string[]
123 * @since 1.23
124 */
125 public static function getAllowedSkins() {
126 global $wgSkipSkins;
127
128 $allowedSkins = self::getSkinNames();
129
130 foreach ( $wgSkipSkins as $skip ) {
131 unset( $allowedSkins[$skip] );
132 }
133
134 return $allowedSkins;
135 }
136
137 /**
138 * @deprecated since 1.23, use getAllowedSkins
139 * @return string[]
140 */
141 public static function getUsableSkins() {
142 wfDeprecated( __METHOD__, '1.23' );
143 return self::getAllowedSkins();
144 }
145
146 /**
147 * Normalize a skin preference value to a form that can be loaded.
148 * If a skin can't be found, it will fall back to the configured
149 * default, or the hardcoded default if that's broken.
150 * @param string $key 'monobook', 'vector', etc.
151 * @return string
152 */
153 static function normalizeKey( $key ) {
154 global $wgDefaultSkin;
155
156 $skinNames = Skin::getSkinNames();
157
158 if ( $key == '' || $key == 'default' ) {
159 // Don't return the default immediately;
160 // in a misconfiguration we need to fall back.
161 $key = $wgDefaultSkin;
162 }
163
164 if ( isset( $skinNames[$key] ) ) {
165 return $key;
166 }
167
168 // Older versions of the software used a numeric setting
169 // in the user preferences.
170 $fallback = array(
171 0 => $wgDefaultSkin,
172 2 => 'cologneblue'
173 );
174
175 if ( isset( $fallback[$key] ) ) {
176 $key = $fallback[$key];
177 }
178
179 if ( isset( $skinNames[$key] ) ) {
180 return $key;
181 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
182 return $wgDefaultSkin;
183 } else {
184 return 'vector';
185 }
186 }
187
188 /**
189 * Factory method for loading a skin of a given type
190 * @param string $key 'monobook', 'vector', etc.
191 * @return Skin
192 */
193 static function &newFromKey( $key ) {
194 global $wgStyleDirectory;
195
196 $key = Skin::normalizeKey( $key );
197
198 $skinNames = Skin::getSkinNames();
199 $skinName = $skinNames[$key];
200 $className = "Skin{$skinName}";
201
202 # Grab the skin class and initialise it.
203 if ( !class_exists( $className ) ) {
204
205 require_once "{$wgStyleDirectory}/{$skinName}.php";
206
207 # Check if we got if not fallback to default skin
208 if ( !class_exists( $className ) ) {
209 # DO NOT die if the class isn't found. This breaks maintenance
210 # scripts and can cause a user account to be unrecoverable
211 # except by SQL manipulation if a previously valid skin name
212 # is no longer valid.
213 wfDebug( "Skin class does not exist: $className\n" );
214 $className = 'SkinVector';
215 }
216 }
217 $skin = new $className( $key );
218 return $skin;
219 }
220
221 /**
222 * @return string Skin name
223 */
224 public function getSkinName() {
225 return $this->skinname;
226 }
227
228 /**
229 * @param OutputPage $out
230 */
231 function initPage( OutputPage $out ) {
232 wfProfileIn( __METHOD__ );
233
234 $this->preloadExistence();
235
236 wfProfileOut( __METHOD__ );
237 }
238
239 /**
240 * Defines the ResourceLoader modules that should be added to the skin
241 * It is recommended that skins wishing to override call parent::getDefaultModules()
242 * and substitute out any modules they wish to change by using a key to look them up
243 * @return array Array of modules with helper keys for easy overriding
244 */
245 public function getDefaultModules() {
246 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
247 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
248
249 $out = $this->getOutput();
250 $user = $out->getUser();
251 $modules = array(
252 // modules that enhance the page content in some way
253 'content' => array(
254 'mediawiki.page.ready',
255 ),
256 // modules that exist for legacy reasons
257 'legacy' => array(),
258 // modules relating to search functionality
259 'search' => array(),
260 // modules relating to functionality relating to watching an article
261 'watch' => array(),
262 // modules which relate to the current users preferences
263 'user' => array(),
264 );
265 if ( $wgIncludeLegacyJavaScript ) {
266 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
267 }
268
269 if ( $wgPreloadJavaScriptMwUtil ) {
270 $modules['legacy'][] = 'mediawiki.util';
271 }
272
273 // Add various resources if required
274 if ( $wgUseAjax ) {
275 $modules['legacy'][] = 'mediawiki.legacy.ajax';
276
277 if ( $wgEnableAPI ) {
278 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
279 && $user->isAllowed( 'writeapi' )
280 ) {
281 $modules['watch'][] = 'mediawiki.page.watch.ajax';
282 }
283
284 $modules['search'][] = 'mediawiki.searchSuggest';
285 }
286 }
287
288 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
289 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
290 }
291
292 // Crazy edit-on-double-click stuff
293 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
294 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
295 }
296 return $modules;
297 }
298
299 /**
300 * Preload the existence of three commonly-requested pages in a single query
301 */
302 function preloadExistence() {
303 $user = $this->getUser();
304
305 // User/talk link
306 $titles = array( $user->getUserPage(), $user->getTalkPage() );
307
308 // Other tab link
309 if ( $this->getTitle()->isSpecialPage() ) {
310 // nothing
311 } elseif ( $this->getTitle()->isTalkPage() ) {
312 $titles[] = $this->getTitle()->getSubjectPage();
313 } else {
314 $titles[] = $this->getTitle()->getTalkPage();
315 }
316
317 $lb = new LinkBatch( $titles );
318 $lb->setCaller( __METHOD__ );
319 $lb->execute();
320 }
321
322 /**
323 * Get the current revision ID
324 *
325 * @return int
326 */
327 public function getRevisionId() {
328 return $this->getOutput()->getRevisionId();
329 }
330
331 /**
332 * Whether the revision displayed is the latest revision of the page
333 *
334 * @return bool
335 */
336 public function isRevisionCurrent() {
337 $revID = $this->getRevisionId();
338 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
339 }
340
341 /**
342 * Set the "relevant" title
343 * @see self::getRelevantTitle()
344 * @param Title $t
345 */
346 public function setRelevantTitle( $t ) {
347 $this->mRelevantTitle = $t;
348 }
349
350 /**
351 * Return the "relevant" title.
352 * A "relevant" title is not necessarily the actual title of the page.
353 * Special pages like Special:MovePage use set the page they are acting on
354 * as their "relevant" title, this allows the skin system to display things
355 * such as content tabs which belong to to that page instead of displaying
356 * a basic special page tab which has almost no meaning.
357 *
358 * @return Title
359 */
360 public function getRelevantTitle() {
361 if ( isset( $this->mRelevantTitle ) ) {
362 return $this->mRelevantTitle;
363 }
364 return $this->getTitle();
365 }
366
367 /**
368 * Set the "relevant" user
369 * @see self::getRelevantUser()
370 * @param User $u
371 */
372 public function setRelevantUser( $u ) {
373 $this->mRelevantUser = $u;
374 }
375
376 /**
377 * Return the "relevant" user.
378 * A "relevant" user is similar to a relevant title. Special pages like
379 * Special:Contributions mark the user which they are relevant to so that
380 * things like the toolbox can display the information they usually are only
381 * able to display on a user's userpage and talkpage.
382 * @return User
383 */
384 public function getRelevantUser() {
385 if ( isset( $this->mRelevantUser ) ) {
386 return $this->mRelevantUser;
387 }
388 $title = $this->getRelevantTitle();
389 if ( $title->hasSubjectNamespace( NS_USER ) ) {
390 $rootUser = $title->getRootText();
391 if ( User::isIP( $rootUser ) ) {
392 $this->mRelevantUser = User::newFromName( $rootUser, false );
393 } else {
394 $user = User::newFromName( $rootUser, false );
395 if ( $user && $user->isLoggedIn() ) {
396 $this->mRelevantUser = $user;
397 }
398 }
399 return $this->mRelevantUser;
400 }
401 return null;
402 }
403
404 /**
405 * Outputs the HTML generated by other functions.
406 * @param OutputPage $out
407 */
408 abstract function outputPage( OutputPage $out = null );
409
410 /**
411 * @param array $data
412 * @return string
413 */
414 static function makeVariablesScript( $data ) {
415 if ( $data ) {
416 return Html::inlineScript(
417 ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) )
418 );
419 } else {
420 return '';
421 }
422 }
423
424 /**
425 * Get the query to generate a dynamic stylesheet
426 *
427 * @return array
428 */
429 public static function getDynamicStylesheetQuery() {
430 global $wgSquidMaxage;
431
432 return array(
433 'action' => 'raw',
434 'maxage' => $wgSquidMaxage,
435 'usemsgcache' => 'yes',
436 'ctype' => 'text/css',
437 'smaxage' => $wgSquidMaxage,
438 );
439 }
440
441 /**
442 * Add skin specific stylesheets
443 * Calling this method with an $out of anything but the same OutputPage
444 * inside ->getOutput() is deprecated. The $out arg is kept
445 * for compatibility purposes with skins.
446 * @param OutputPage $out
447 * @todo delete
448 */
449 abstract function setupSkinUserCss( OutputPage $out );
450
451 /**
452 * TODO: document
453 * @param Title $title
454 * @return string
455 */
456 function getPageClasses( $title ) {
457 $numeric = 'ns-' . $title->getNamespace();
458
459 if ( $title->isSpecialPage() ) {
460 $type = 'ns-special';
461 // bug 23315: provide a class based on the canonical special page name without subpages
462 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
463 if ( $canonicalName ) {
464 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
465 } else {
466 $type .= ' mw-invalidspecialpage';
467 }
468 } elseif ( $title->isTalkPage() ) {
469 $type = 'ns-talk';
470 } else {
471 $type = 'ns-subject';
472 }
473
474 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
475
476 return "$numeric $type $name";
477 }
478
479 /*
480 * Return values for <html> element
481 * @return array of associative name-to-value elements for <html> element
482 */
483 public function getHtmlElementAttributes() {
484 $lang = $this->getLanguage();
485 return array(
486 'lang' => $lang->getHtmlCode(),
487 'dir' => $lang->getDir(),
488 'class' => 'client-nojs',
489 );
490 }
491
492 /**
493 * This will be called by OutputPage::headElement when it is creating the
494 * "<body>" tag, skins can override it if they have a need to add in any
495 * body attributes or classes of their own.
496 * @param OutputPage $out
497 * @param array $bodyAttrs
498 */
499 function addToBodyAttributes( $out, &$bodyAttrs ) {
500 // does nothing by default
501 }
502
503 /**
504 * URL to the logo
505 * @return string
506 */
507 function getLogo() {
508 global $wgLogo;
509 return $wgLogo;
510 }
511
512 /**
513 * @return string
514 */
515 function getCategoryLinks() {
516 global $wgUseCategoryBrowser;
517
518 $out = $this->getOutput();
519 $allCats = $out->getCategoryLinks();
520
521 if ( !count( $allCats ) ) {
522 return '';
523 }
524
525 $embed = "<li>";
526 $pop = "</li>";
527
528 $s = '';
529 $colon = $this->msg( 'colon-separator' )->escaped();
530
531 if ( !empty( $allCats['normal'] ) ) {
532 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
533
534 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
535 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
536 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
537 Linker::link( Title::newFromText( $linkPage ), $msg )
538 . $colon . '<ul>' . $t . '</ul>' . '</div>';
539 }
540
541 # Hidden categories
542 if ( isset( $allCats['hidden'] ) ) {
543 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
544 $class = ' mw-hidden-cats-user-shown';
545 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
546 $class = ' mw-hidden-cats-ns-shown';
547 } else {
548 $class = ' mw-hidden-cats-hidden';
549 }
550
551 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
552 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
553 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
554 '</div>';
555 }
556
557 # optional 'dmoz-like' category browser. Will be shown under the list
558 # of categories an article belong to
559 if ( $wgUseCategoryBrowser ) {
560 $s .= '<br /><hr />';
561
562 # get a big array of the parents tree
563 $parenttree = $this->getTitle()->getParentCategoryTree();
564 # Skin object passed by reference cause it can not be
565 # accessed under the method subfunction drawCategoryBrowser
566 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
567 # Clean out bogus first entry and sort them
568 unset( $tempout[0] );
569 asort( $tempout );
570 # Output one per line
571 $s .= implode( "<br />\n", $tempout );
572 }
573
574 return $s;
575 }
576
577 /**
578 * Render the array as a series of links.
579 * @param array $tree Categories tree returned by Title::getParentCategoryTree
580 * @return string Separated by &gt;, terminate with "\n"
581 */
582 function drawCategoryBrowser( $tree ) {
583 $return = '';
584
585 foreach ( $tree as $element => $parent ) {
586 if ( empty( $parent ) ) {
587 # element start a new list
588 $return .= "\n";
589 } else {
590 # grab the others elements
591 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
592 }
593
594 # add our current element to the list
595 $eltitle = Title::newFromText( $element );
596 $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
597 }
598
599 return $return;
600 }
601
602 /**
603 * @return string
604 */
605 function getCategories() {
606 $out = $this->getOutput();
607
608 $catlinks = $this->getCategoryLinks();
609
610 $classes = 'catlinks';
611
612 // Check what we're showing
613 $allCats = $out->getCategoryLinks();
614 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
615 $this->getTitle()->getNamespace() == NS_CATEGORY;
616
617 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
618 $classes .= ' catlinks-allhidden';
619 }
620
621 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
622 }
623
624 /**
625 * This runs a hook to allow extensions placing their stuff after content
626 * and article metadata (e.g. categories).
627 * Note: This function has nothing to do with afterContent().
628 *
629 * This hook is placed here in order to allow using the same hook for all
630 * skins, both the SkinTemplate based ones and the older ones, which directly
631 * use this class to get their data.
632 *
633 * The output of this function gets processed in SkinTemplate::outputPage() for
634 * the SkinTemplate based skins, all other skins should directly echo it.
635 *
636 * @return string Empty by default, if not changed by any hook function.
637 */
638 protected function afterContentHook() {
639 $data = '';
640
641 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
642 // adding just some spaces shouldn't toggle the output
643 // of the whole <div/>, so we use trim() here
644 if ( trim( $data ) != '' ) {
645 // Doing this here instead of in the skins to
646 // ensure that the div has the same ID in all
647 // skins
648 $data = "<div id='mw-data-after-content'>\n" .
649 "\t$data\n" .
650 "</div>\n";
651 }
652 } else {
653 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
654 }
655
656 return $data;
657 }
658
659 /**
660 * Generate debug data HTML for displaying at the bottom of the main content
661 * area.
662 * @return string HTML containing debug data, if enabled (otherwise empty).
663 */
664 protected function generateDebugHTML() {
665 return MWDebug::getHTMLDebugLog();
666 }
667
668 /**
669 * This gets called shortly before the "</body>" tag.
670 *
671 * @return string HTML-wrapped JS code to be put before "</body>"
672 */
673 function bottomScripts() {
674 // TODO and the suckage continues. This function is really just a wrapper around
675 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
676 // up at some point
677 $bottomScriptText = $this->getOutput()->getBottomScripts();
678 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
679
680 return $bottomScriptText;
681 }
682
683 /**
684 * Text with the permalink to the source page,
685 * usually shown on the footer of a printed page
686 *
687 * @return string HTML text with an URL
688 */
689 function printSource() {
690 $oldid = $this->getRevisionId();
691 if ( $oldid ) {
692 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
693 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
694 } else {
695 // oldid not available for non existing pages
696 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
697 }
698
699 return $this->msg( 'retrievedfrom', '<a dir="ltr" href="' . $url
700 . '">' . $url . '</a>' )->text();
701 }
702
703 /**
704 * @return string
705 */
706 function getUndeleteLink() {
707 $action = $this->getRequest()->getVal( 'action', 'view' );
708
709 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
710 ( $this->getTitle()->getArticleID() == 0 || $action == 'history' ) ) {
711 $n = $this->getTitle()->isDeleted();
712
713 if ( $n ) {
714 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
715 $msg = 'thisisdeleted';
716 } else {
717 $msg = 'viewdeleted';
718 }
719
720 return $this->msg( $msg )->rawParams(
721 Linker::linkKnown(
722 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
723 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
724 )->text();
725 }
726 }
727
728 return '';
729 }
730
731 /**
732 * @return string
733 */
734 function subPageSubtitle() {
735 $out = $this->getOutput();
736 $subpages = '';
737
738 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
739 return $subpages;
740 }
741
742 if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) {
743 $ptext = $this->getTitle()->getPrefixedText();
744 if ( preg_match( '/\//', $ptext ) ) {
745 $links = explode( '/', $ptext );
746 array_pop( $links );
747 $c = 0;
748 $growinglink = '';
749 $display = '';
750 $lang = $this->getLanguage();
751
752 foreach ( $links as $link ) {
753 $growinglink .= $link;
754 $display .= $link;
755 $linkObj = Title::newFromText( $growinglink );
756
757 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
758 $getlink = Linker::linkKnown(
759 $linkObj,
760 htmlspecialchars( $display )
761 );
762
763 $c++;
764
765 if ( $c > 1 ) {
766 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
767 } else {
768 $subpages .= '&lt; ';
769 }
770
771 $subpages .= $getlink;
772 $display = '';
773 } else {
774 $display .= '/';
775 }
776 $growinglink .= '/';
777 }
778 }
779 }
780
781 return $subpages;
782 }
783
784 /**
785 * Returns true if the IP should be shown in the header
786 * @return bool
787 */
788 function showIPinHeader() {
789 global $wgShowIPinHeader;
790 return $wgShowIPinHeader && session_id() != '';
791 }
792
793 /**
794 * @return string
795 */
796 function getSearchLink() {
797 $searchPage = SpecialPage::getTitleFor( 'Search' );
798 return $searchPage->getLocalURL();
799 }
800
801 /**
802 * @return string
803 */
804 function escapeSearchLink() {
805 return htmlspecialchars( $this->getSearchLink() );
806 }
807
808 /**
809 * @param string $type
810 * @return string
811 */
812 function getCopyright( $type = 'detect' ) {
813 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
814
815 if ( $type == 'detect' ) {
816 if ( !$this->isRevisionCurrent()
817 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
818 ) {
819 $type = 'history';
820 } else {
821 $type = 'normal';
822 }
823 }
824
825 if ( $type == 'history' ) {
826 $msg = 'history_copyright';
827 } else {
828 $msg = 'copyright';
829 }
830
831 if ( $wgRightsPage ) {
832 $title = Title::newFromText( $wgRightsPage );
833 $link = Linker::linkKnown( $title, $wgRightsText );
834 } elseif ( $wgRightsUrl ) {
835 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
836 } elseif ( $wgRightsText ) {
837 $link = $wgRightsText;
838 } else {
839 # Give up now
840 return '';
841 }
842
843 // Allow for site and per-namespace customization of copyright notice.
844 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
845 $forContent = true;
846
847 wfRunHooks(
848 'SkinCopyrightFooter',
849 array( $this->getTitle(), $type, &$msg, &$link, &$forContent )
850 );
851
852 return $this->msg( $msg )->rawParams( $link )->text();
853 }
854
855 /**
856 * @return null|string
857 */
858 function getCopyrightIcon() {
859 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
860
861 $out = '';
862
863 if ( $wgCopyrightIcon ) {
864 $out = $wgCopyrightIcon;
865 } elseif ( $wgRightsIcon ) {
866 $icon = htmlspecialchars( $wgRightsIcon );
867
868 if ( $wgRightsUrl ) {
869 $url = htmlspecialchars( $wgRightsUrl );
870 $out .= '<a href="' . $url . '">';
871 }
872
873 $text = htmlspecialchars( $wgRightsText );
874 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
875
876 if ( $wgRightsUrl ) {
877 $out .= '</a>';
878 }
879 }
880
881 return $out;
882 }
883
884 /**
885 * Gets the powered by MediaWiki icon.
886 * @return string
887 */
888 function getPoweredBy() {
889 global $wgStylePath;
890
891 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
892 $text = '<a href="//www.mediawiki.org/"><img src="' . $url
893 . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
894 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
895 return $text;
896 }
897
898 /**
899 * Get the timestamp of the latest revision, formatted in user language
900 *
901 * @return string
902 */
903 protected function lastModified() {
904 $timestamp = $this->getOutput()->getRevisionTimestamp();
905
906 # No cached timestamp, load it from the database
907 if ( $timestamp === null ) {
908 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
909 }
910
911 if ( $timestamp ) {
912 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
913 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
914 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
915 } else {
916 $s = '';
917 }
918
919 if ( wfGetLB()->getLaggedSlaveMode() ) {
920 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
921 }
922
923 return $s;
924 }
925
926 /**
927 * @param string $align
928 * @return string
929 */
930 function logoText( $align = '' ) {
931 if ( $align != '' ) {
932 $a = " style='float: {$align};'";
933 } else {
934 $a = '';
935 }
936
937 $mp = $this->msg( 'mainpage' )->escaped();
938 $mptitle = Title::newMainPage();
939 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
940
941 $logourl = $this->getLogo();
942 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
943
944 return $s;
945 }
946
947 /**
948 * Renders a $wgFooterIcons icon according to the method's arguments
949 * @param array $icon The icon to build the html for, see $wgFooterIcons
950 * for the format of this array.
951 * @param bool|string $withImage Whether to use the icon's image or output
952 * a text-only footericon.
953 * @return string HTML
954 */
955 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
956 if ( is_string( $icon ) ) {
957 $html = $icon;
958 } else { // Assuming array
959 $url = isset( $icon["url"] ) ? $icon["url"] : null;
960 unset( $icon["url"] );
961 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
962 // do this the lazy way, just pass icon data as an attribute array
963 $html = Html::element( 'img', $icon );
964 } else {
965 $html = htmlspecialchars( $icon["alt"] );
966 }
967 if ( $url ) {
968 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
969 }
970 }
971 return $html;
972 }
973
974 /**
975 * Gets the link to the wiki's main page.
976 * @return string
977 */
978 function mainPageLink() {
979 $s = Linker::linkKnown(
980 Title::newMainPage(),
981 $this->msg( 'mainpage' )->escaped()
982 );
983
984 return $s;
985 }
986
987 /**
988 * Returns an HTML link for use in the footer
989 * @param string $desc i18n message key for the link text
990 * @param string $page i18n message key for the page to link to
991 * @return string HTML anchor
992 */
993 public function footerLink( $desc, $page ) {
994 // if the link description has been set to "-" in the default language,
995 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
996 // then it is disabled, for all languages.
997 return '';
998 } else {
999 // Otherwise, we display the link for the user, described in their
1000 // language (which may or may not be the same as the default language),
1001 // but we make the link target be the one site-wide page.
1002 $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1003
1004 return Linker::linkKnown(
1005 $title,
1006 $this->msg( $desc )->escaped()
1007 );
1008 }
1009 }
1010
1011 /**
1012 * Gets the link to the wiki's privacy policy page.
1013 * @return string HTML
1014 */
1015 function privacyLink() {
1016 return $this->footerLink( 'privacy', 'privacypage' );
1017 }
1018
1019 /**
1020 * Gets the link to the wiki's about page.
1021 * @return string HTML
1022 */
1023 function aboutLink() {
1024 return $this->footerLink( 'aboutsite', 'aboutpage' );
1025 }
1026
1027 /**
1028 * Gets the link to the wiki's general disclaimers page.
1029 * @return string HTML
1030 */
1031 function disclaimerLink() {
1032 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1033 }
1034
1035 /**
1036 * Return URL options for the 'edit page' link.
1037 * This may include an 'oldid' specifier, if the current page view is such.
1038 *
1039 * @return array
1040 * @private
1041 */
1042 function editUrlOptions() {
1043 $options = array( 'action' => 'edit' );
1044
1045 if ( !$this->isRevisionCurrent() ) {
1046 $options['oldid'] = intval( $this->getRevisionId() );
1047 }
1048
1049 return $options;
1050 }
1051
1052 /**
1053 * @param User|int $id
1054 * @return bool
1055 */
1056 function showEmailUser( $id ) {
1057 if ( $id instanceof User ) {
1058 $targetUser = $id;
1059 } else {
1060 $targetUser = User::newFromId( $id );
1061 }
1062
1063 # The sending user must have a confirmed email address and the target
1064 # user must have a confirmed email address and allow emails from users.
1065 return $this->getUser()->canSendEmail() &&
1066 $targetUser->canReceiveEmail();
1067 }
1068
1069 /**
1070 * Return a fully resolved style path url to images or styles stored in the common folder.
1071 * This method returns a url resolved using the configured skin style path
1072 * and includes the style version inside of the url.
1073 * @param string $name The name or path of a skin resource file
1074 * @return string The fully resolved style path url including styleversion
1075 */
1076 function getCommonStylePath( $name ) {
1077 global $wgStylePath, $wgStyleVersion;
1078 return "$wgStylePath/common/$name?$wgStyleVersion";
1079 }
1080
1081 /**
1082 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1083 * This method returns a url resolved using the configured skin style path
1084 * and includes the style version inside of the url.
1085 *
1086 * Requires $stylename to be set, otherwise throws MWException.
1087 *
1088 * @param string $name The name or path of a skin resource file
1089 * @return string The fully resolved style path url including styleversion
1090 */
1091 function getSkinStylePath( $name ) {
1092 global $wgStylePath, $wgStyleVersion;
1093
1094 if ( $this->stylename === null ) {
1095 $class = get_class( $this );
1096 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1097 }
1098
1099 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1100 }
1101
1102 /* these are used extensively in SkinTemplate, but also some other places */
1103
1104 /**
1105 * @param string $urlaction
1106 * @return string
1107 */
1108 static function makeMainPageUrl( $urlaction = '' ) {
1109 $title = Title::newMainPage();
1110 self::checkTitle( $title, '' );
1111
1112 return $title->getLocalURL( $urlaction );
1113 }
1114
1115 /**
1116 * Make a URL for a Special Page using the given query and protocol.
1117 *
1118 * If $proto is set to null, make a local URL. Otherwise, make a full
1119 * URL with the protocol specified.
1120 *
1121 * @param string $name Name of the Special page
1122 * @param string $urlaction Query to append
1123 * @param string|null $proto Protocol to use or null for a local URL
1124 * @return string
1125 */
1126 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1127 $title = SpecialPage::getSafeTitleFor( $name );
1128 if ( is_null( $proto ) ) {
1129 return $title->getLocalURL( $urlaction );
1130 } else {
1131 return $title->getFullURL( $urlaction, false, $proto );
1132 }
1133 }
1134
1135 /**
1136 * @param string $name
1137 * @param string $subpage
1138 * @param string $urlaction
1139 * @return string
1140 */
1141 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1142 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1143 return $title->getLocalURL( $urlaction );
1144 }
1145
1146 /**
1147 * @param string $name
1148 * @param string $urlaction
1149 * @return string
1150 */
1151 static function makeI18nUrl( $name, $urlaction = '' ) {
1152 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1153 self::checkTitle( $title, $name );
1154 return $title->getLocalURL( $urlaction );
1155 }
1156
1157 /**
1158 * @param string $name
1159 * @param string $urlaction
1160 * @return string
1161 */
1162 static function makeUrl( $name, $urlaction = '' ) {
1163 $title = Title::newFromText( $name );
1164 self::checkTitle( $title, $name );
1165
1166 return $title->getLocalURL( $urlaction );
1167 }
1168
1169 /**
1170 * If url string starts with http, consider as external URL, else
1171 * internal
1172 * @param string $name
1173 * @return string URL
1174 */
1175 static function makeInternalOrExternalUrl( $name ) {
1176 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1177 return $name;
1178 } else {
1179 return self::makeUrl( $name );
1180 }
1181 }
1182
1183 /**
1184 * this can be passed the NS number as defined in Language.php
1185 * @param string $name
1186 * @param string $urlaction
1187 * @param int $namespace
1188 * @return string
1189 */
1190 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1191 $title = Title::makeTitleSafe( $namespace, $name );
1192 self::checkTitle( $title, $name );
1193
1194 return $title->getLocalURL( $urlaction );
1195 }
1196
1197 /**
1198 * these return an array with the 'href' and boolean 'exists'
1199 * @param string $name
1200 * @param string $urlaction
1201 * @return array
1202 */
1203 static function makeUrlDetails( $name, $urlaction = '' ) {
1204 $title = Title::newFromText( $name );
1205 self::checkTitle( $title, $name );
1206
1207 return array(
1208 'href' => $title->getLocalURL( $urlaction ),
1209 'exists' => $title->getArticleID() != 0,
1210 );
1211 }
1212
1213 /**
1214 * Make URL details where the article exists (or at least it's convenient to think so)
1215 * @param string $name Article name
1216 * @param string $urlaction
1217 * @return array
1218 */
1219 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1220 $title = Title::newFromText( $name );
1221 self::checkTitle( $title, $name );
1222
1223 return array(
1224 'href' => $title->getLocalURL( $urlaction ),
1225 'exists' => true
1226 );
1227 }
1228
1229 /**
1230 * make sure we have some title to operate on
1231 *
1232 * @param Title $title
1233 * @param string $name
1234 */
1235 static function checkTitle( &$title, $name ) {
1236 if ( !is_object( $title ) ) {
1237 $title = Title::newFromText( $name );
1238 if ( !is_object( $title ) ) {
1239 $title = Title::newFromText( '--error: link target missing--' );
1240 }
1241 }
1242 }
1243
1244 /**
1245 * Build an array that represents the sidebar(s), the navigation bar among them.
1246 *
1247 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1248 *
1249 * The format of the returned array is array( heading => content, ... ), where:
1250 * - heading is the heading of a navigation portlet. It is either:
1251 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1252 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1253 * - plain text, which should be HTML-escaped by the skin
1254 * - content is the contents of the portlet. It is either:
1255 * - HTML text (<ul><li>...</li>...</ul>)
1256 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1257 * - (for a magic string as a key, any value)
1258 *
1259 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1260 * and can technically insert anything in here; skin creators are expected to handle
1261 * values described above.
1262 *
1263 * @return array
1264 */
1265 function buildSidebar() {
1266 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1267 wfProfileIn( __METHOD__ );
1268
1269 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1270
1271 if ( $wgEnableSidebarCache ) {
1272 $cachedsidebar = $wgMemc->get( $key );
1273 if ( $cachedsidebar ) {
1274 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$cachedsidebar ) );
1275
1276 wfProfileOut( __METHOD__ );
1277 return $cachedsidebar;
1278 }
1279 }
1280
1281 $bar = array();
1282 $this->addToSidebar( $bar, 'sidebar' );
1283
1284 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1285 if ( $wgEnableSidebarCache ) {
1286 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1287 }
1288
1289 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$bar ) );
1290
1291 wfProfileOut( __METHOD__ );
1292 return $bar;
1293 }
1294
1295 /**
1296 * Add content from a sidebar system message
1297 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1298 *
1299 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1300 *
1301 * @param array $bar
1302 * @param string $message
1303 */
1304 function addToSidebar( &$bar, $message ) {
1305 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1306 }
1307
1308 /**
1309 * Add content from plain text
1310 * @since 1.17
1311 * @param array $bar
1312 * @param string $text
1313 * @return array
1314 */
1315 function addToSidebarPlain( &$bar, $text ) {
1316 $lines = explode( "\n", $text );
1317
1318 $heading = '';
1319
1320 foreach ( $lines as $line ) {
1321 if ( strpos( $line, '*' ) !== 0 ) {
1322 continue;
1323 }
1324 $line = rtrim( $line, "\r" ); // for Windows compat
1325
1326 if ( strpos( $line, '**' ) !== 0 ) {
1327 $heading = trim( $line, '* ' );
1328 if ( !array_key_exists( $heading, $bar ) ) {
1329 $bar[$heading] = array();
1330 }
1331 } else {
1332 $line = trim( $line, '* ' );
1333
1334 if ( strpos( $line, '|' ) !== false ) { // sanity check
1335 $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() );
1336 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1337 if ( count( $line ) !== 2 ) {
1338 // Second sanity check, could be hit by people doing
1339 // funky stuff with parserfuncs... (bug 33321)
1340 continue;
1341 }
1342
1343 $extraAttribs = array();
1344
1345 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1346 if ( $msgLink->exists() ) {
1347 $link = $msgLink->text();
1348 if ( $link == '-' ) {
1349 continue;
1350 }
1351 } else {
1352 $link = $line[0];
1353 }
1354 $msgText = $this->msg( $line[1] );
1355 if ( $msgText->exists() ) {
1356 $text = $msgText->text();
1357 } else {
1358 $text = $line[1];
1359 }
1360
1361 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1362 $href = $link;
1363
1364 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1365 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1366 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1367 $extraAttribs['rel'] = 'nofollow';
1368 }
1369
1370 global $wgExternalLinkTarget;
1371 if ( $wgExternalLinkTarget ) {
1372 $extraAttribs['target'] = $wgExternalLinkTarget;
1373 }
1374 } else {
1375 $title = Title::newFromText( $link );
1376
1377 if ( $title ) {
1378 $title = $title->fixSpecialName();
1379 $href = $title->getLinkURL();
1380 } else {
1381 $href = 'INVALID-TITLE';
1382 }
1383 }
1384
1385 $bar[$heading][] = array_merge( array(
1386 'text' => $text,
1387 'href' => $href,
1388 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1389 'active' => false
1390 ), $extraAttribs );
1391 } else {
1392 continue;
1393 }
1394 }
1395 }
1396
1397 return $bar;
1398 }
1399
1400 /**
1401 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1402 * should be loaded by OutputPage. That module no longer exists and the return value of this
1403 * method is ignored.
1404 *
1405 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1406 * can be used instead (SkinTemplate-based skins do it automatically).
1407 *
1408 * @deprecated since 1.22
1409 * @return bool
1410 */
1411 public function commonPrintStylesheet() {
1412 wfDeprecated( __METHOD__, '1.22' );
1413 return false;
1414 }
1415
1416 /**
1417 * Gets new talk page messages for the current user and returns an
1418 * appropriate alert message (or an empty string if there are no messages)
1419 * @return string
1420 */
1421 function getNewtalks() {
1422
1423 $newMessagesAlert = '';
1424 $user = $this->getUser();
1425 $newtalks = $user->getNewMessageLinks();
1426 $out = $this->getOutput();
1427
1428 // Allow extensions to disable or modify the new messages alert
1429 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1430 return '';
1431 }
1432 if ( $newMessagesAlert ) {
1433 return $newMessagesAlert;
1434 }
1435
1436 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1437 $uTalkTitle = $user->getTalkPage();
1438 $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null;
1439 $nofAuthors = 0;
1440 if ( $lastSeenRev !== null ) {
1441 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1442 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1443 if ( $latestRev !== null ) {
1444 // Singular if only 1 unseen revision, plural if several unseen revisions.
1445 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1446 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1447 $lastSeenRev, $latestRev, 10, 'include_new' );
1448 }
1449 } else {
1450 // Singular if no revision -> diff link will show latest change only in any case
1451 $plural = false;
1452 }
1453 $plural = $plural ? 999 : 1;
1454 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1455 // the number of revisions or authors is not necessarily the same as the number of
1456 // "messages".
1457 $newMessagesLink = Linker::linkKnown(
1458 $uTalkTitle,
1459 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1460 array(),
1461 array( 'redirect' => 'no' )
1462 );
1463
1464 $newMessagesDiffLink = Linker::linkKnown(
1465 $uTalkTitle,
1466 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1467 array(),
1468 $lastSeenRev !== null
1469 ? array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1470 : array( 'diff' => 'cur' )
1471 );
1472
1473 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1474 $newMessagesAlert = $this->msg(
1475 'youhavenewmessagesfromusers',
1476 $newMessagesLink,
1477 $newMessagesDiffLink
1478 )->numParams( $nofAuthors, $plural );
1479 } else {
1480 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1481 $newMessagesAlert = $this->msg(
1482 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1483 $newMessagesLink,
1484 $newMessagesDiffLink
1485 )->numParams( $plural );
1486 }
1487 $newMessagesAlert = $newMessagesAlert->text();
1488 # Disable Squid cache
1489 $out->setSquidMaxage( 0 );
1490 } elseif ( count( $newtalks ) ) {
1491 $sep = $this->msg( 'newtalkseparator' )->escaped();
1492 $msgs = array();
1493
1494 foreach ( $newtalks as $newtalk ) {
1495 $msgs[] = Xml::element(
1496 'a',
1497 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1498 );
1499 }
1500 $parts = implode( $sep, $msgs );
1501 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1502 $out->setSquidMaxage( 0 );
1503 }
1504
1505 return $newMessagesAlert;
1506 }
1507
1508 /**
1509 * Get a cached notice
1510 *
1511 * @param string $name Message name, or 'default' for $wgSiteNotice
1512 * @return string HTML fragment
1513 */
1514 private function getCachedNotice( $name ) {
1515 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1516
1517 wfProfileIn( __METHOD__ );
1518
1519 $needParse = false;
1520
1521 if ( $name === 'default' ) {
1522 // special case
1523 global $wgSiteNotice;
1524 $notice = $wgSiteNotice;
1525 if ( empty( $notice ) ) {
1526 wfProfileOut( __METHOD__ );
1527 return false;
1528 }
1529 } else {
1530 $msg = $this->msg( $name )->inContentLanguage();
1531 if ( $msg->isDisabled() ) {
1532 wfProfileOut( __METHOD__ );
1533 return false;
1534 }
1535 $notice = $msg->plain();
1536 }
1537
1538 // Use the extra hash appender to let eg SSL variants separately cache.
1539 $key = wfMemcKey( $name . $wgRenderHashAppend );
1540 $cachedNotice = $parserMemc->get( $key );
1541 if ( is_array( $cachedNotice ) ) {
1542 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1543 $notice = $cachedNotice['html'];
1544 } else {
1545 $needParse = true;
1546 }
1547 } else {
1548 $needParse = true;
1549 }
1550
1551 if ( $needParse ) {
1552 $parsed = $this->getOutput()->parse( $notice );
1553 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1554 $notice = $parsed;
1555 }
1556
1557 $notice = Html::rawElement( 'div', array( 'id' => 'localNotice',
1558 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1559 wfProfileOut( __METHOD__ );
1560 return $notice;
1561 }
1562
1563 /**
1564 * Get a notice based on page's namespace
1565 *
1566 * @return string HTML fragment
1567 */
1568 function getNamespaceNotice() {
1569 wfProfileIn( __METHOD__ );
1570
1571 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1572 $namespaceNotice = $this->getCachedNotice( $key );
1573 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
1574 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1575 } else {
1576 $namespaceNotice = '';
1577 }
1578
1579 wfProfileOut( __METHOD__ );
1580 return $namespaceNotice;
1581 }
1582
1583 /**
1584 * Get the site notice
1585 *
1586 * @return string HTML fragment
1587 */
1588 function getSiteNotice() {
1589 wfProfileIn( __METHOD__ );
1590 $siteNotice = '';
1591
1592 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1593 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1594 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1595 } else {
1596 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1597 if ( !$anonNotice ) {
1598 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1599 } else {
1600 $siteNotice = $anonNotice;
1601 }
1602 }
1603 if ( !$siteNotice ) {
1604 $siteNotice = $this->getCachedNotice( 'default' );
1605 }
1606 }
1607
1608 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1609 wfProfileOut( __METHOD__ );
1610 return $siteNotice;
1611 }
1612
1613 /**
1614 * Create a section edit link. This supersedes editSectionLink() and
1615 * editSectionLinkForOther().
1616 *
1617 * @param Title $nt The title being linked to (may not be the same as
1618 * the current page, if the section is included from a template)
1619 * @param string $section The designation of the section being pointed to,
1620 * to be included in the link, like "&section=$section"
1621 * @param string $tooltip The tooltip to use for the link: will be escaped
1622 * and wrapped in the 'editsectionhint' message
1623 * @param string $lang Language code
1624 * @return string HTML to use for edit link
1625 */
1626 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1627 // HTML generated here should probably have userlangattributes
1628 // added to it for LTR text on RTL pages
1629
1630 $lang = wfGetLangObj( $lang );
1631
1632 $attribs = array();
1633 if ( !is_null( $tooltip ) ) {
1634 # Bug 25462: undo double-escaping.
1635 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1636 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1637 ->inLanguage( $lang )->text();
1638 }
1639 $link = Linker::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1640 $attribs,
1641 array( 'action' => 'edit', 'section' => $section ),
1642 array( 'noclasses', 'known' )
1643 );
1644
1645 # Add the brackets and the span and run the hook.
1646 $result = '<span class="mw-editsection">'
1647 . '<span class="mw-editsection-bracket">[</span>'
1648 . $link
1649 . '<span class="mw-editsection-bracket">]</span>'
1650 . '</span>';
1651
1652 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1653 return $result;
1654 }
1655
1656 /**
1657 * Use PHP's magic __call handler to intercept legacy calls to the linker
1658 * for backwards compatibility.
1659 *
1660 * @param string $fname Name of called method
1661 * @param array $args Arguments to the method
1662 * @throws MWException
1663 * @return mixed
1664 */
1665 function __call( $fname, $args ) {
1666 $realFunction = array( 'Linker', $fname );
1667 if ( is_callable( $realFunction ) ) {
1668 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1669 return call_user_func_array( $realFunction, $args );
1670 } else {
1671 $className = get_class( $this );
1672 throw new MWException( "Call to undefined method $className::$fname" );
1673 }
1674 }
1675
1676 }