wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / skins / Skin.php
blobdbb7c7ff02d4632b199d4754634e85ed0da9611f
1 <?php
2 /**
3 * Base class for all skins.
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.
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.
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
20 * @file
23 /**
24 * @defgroup Skins Skins
27 /**
28 * The main skin class which provides methods and properties for all other skins.
30 * See docs/skin.txt for more information.
32 * @ingroup Skins
34 abstract class Skin extends ContextSource {
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
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.
43 public $stylename = null;
45 /**
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
49 static function getSkinNames() {
50 return SkinFactory::getDefaultInstance()->getSkinNames();
53 /**
54 * Fetch the skinname messages for available skins.
55 * @return string[]
57 static function getSkinNameMessages() {
58 $messages = array();
59 foreach ( self::getSkinNames() as $skinKey => $skinName ) {
60 $messages[] = "skinname-$skinKey";
62 return $messages;
65 /**
66 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
67 * Useful for Special:Preferences and other places where you
68 * only want to show skins users _can_ use.
69 * @return string[]
70 * @since 1.23
72 public static function getAllowedSkins() {
73 global $wgSkipSkins;
75 $allowedSkins = self::getSkinNames();
77 foreach ( $wgSkipSkins as $skip ) {
78 unset( $allowedSkins[$skip] );
81 return $allowedSkins;
84 /**
85 * @deprecated since 1.23, use getAllowedSkins
86 * @return string[]
88 public static function getUsableSkins() {
89 wfDeprecated( __METHOD__, '1.23' );
90 return self::getAllowedSkins();
93 /**
94 * Normalize a skin preference value to a form that can be loaded.
96 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
97 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
99 * @param string $key 'monobook', 'vector', etc.
100 * @return string
102 static function normalizeKey( $key ) {
103 global $wgDefaultSkin, $wgFallbackSkin;
105 $skinNames = Skin::getSkinNames();
107 // Make keys lowercase for case-insensitive matching.
108 $skinNames = array_change_key_case( $skinNames, CASE_LOWER );
109 $key = strtolower( $key );
110 $defaultSkin = strtolower( $wgDefaultSkin );
111 $fallbackSkin = strtolower( $wgFallbackSkin );
113 if ( $key == '' || $key == 'default' ) {
114 // Don't return the default immediately;
115 // in a misconfiguration we need to fall back.
116 $key = $defaultSkin;
119 if ( isset( $skinNames[$key] ) ) {
120 return $key;
123 // Older versions of the software used a numeric setting
124 // in the user preferences.
125 $fallback = array(
126 0 => $defaultSkin,
127 2 => 'cologneblue'
130 if ( isset( $fallback[$key] ) ) {
131 $key = $fallback[$key];
134 if ( isset( $skinNames[$key] ) ) {
135 return $key;
136 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
137 return $defaultSkin;
138 } else {
139 return $fallbackSkin;
144 * Factory method for loading a skin of a given type
145 * @param string $key 'monobook', 'vector', etc.
146 * @return Skin
147 * @deprecated since 1.24; Use SkinFactory instead
149 static function &newFromKey( $key ) {
150 wfDeprecated( __METHOD__, '1.24' );
152 $key = Skin::normalizeKey( $key );
153 $factory = SkinFactory::getDefaultInstance();
155 // normalizeKey() guarantees that a skin with this key will exist.
156 $skin = $factory->makeSkin( $key );
157 return $skin;
161 * @return string Skin name
163 public function getSkinName() {
164 return $this->skinname;
168 * @param OutputPage $out
170 function initPage( OutputPage $out ) {
172 $this->preloadExistence();
177 * Defines the ResourceLoader modules that should be added to the skin
178 * It is recommended that skins wishing to override call parent::getDefaultModules()
179 * and substitute out any modules they wish to change by using a key to look them up
180 * @return array Array of modules with helper keys for easy overriding
182 public function getDefaultModules() {
183 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
185 $out = $this->getOutput();
186 $user = $out->getUser();
187 $modules = array(
188 // modules that enhance the page content in some way
189 'content' => array(
190 'mediawiki.page.ready',
192 // modules that exist for legacy reasons
193 'legacy' => ResourceLoaderStartUpModule::getLegacyModules(),
194 // modules relating to search functionality
195 'search' => array(),
196 // modules relating to functionality relating to watching an article
197 'watch' => array(),
198 // modules which relate to the current users preferences
199 'user' => array(),
202 // Add various resources if required
203 if ( $wgUseAjax && $wgEnableAPI ) {
204 if ( $wgEnableWriteAPI && $user->isLoggedIn()
205 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
206 && $this->getRelevantTitle()->canExist()
208 $modules['watch'][] = 'mediawiki.page.watch.ajax';
211 $modules['search'][] = 'mediawiki.searchSuggest';
214 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
215 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
218 // Crazy edit-on-double-click stuff
219 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
220 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
222 return $modules;
226 * Preload the existence of three commonly-requested pages in a single query
228 function preloadExistence() {
229 $titles = array();
231 $user = $this->getUser();
232 $title = $this->getRelevantTitle();
234 // User/talk link
235 if ( $user->isLoggedIn() ) {
236 $titles[] = $user->getUserPage();
237 $titles[] = $user->getTalkPage();
240 // Check, if the page can hold some kind of content, otherwise do nothing
241 if ( !$title->canExist() ) {
242 // nothing
243 } elseif ( $title->isTalkPage() ) {
244 $titles[] = $title->getSubjectPage();
245 } else {
246 $titles[] = $title->getTalkPage();
249 Hooks::run( 'SkinPreloadExistence', array( &$titles, $this ) );
251 if ( count( $titles ) ) {
252 $lb = new LinkBatch( $titles );
253 $lb->setCaller( __METHOD__ );
254 $lb->execute();
259 * Get the current revision ID
261 * @return int
263 public function getRevisionId() {
264 return $this->getOutput()->getRevisionId();
268 * Whether the revision displayed is the latest revision of the page
270 * @return bool
272 public function isRevisionCurrent() {
273 $revID = $this->getRevisionId();
274 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
278 * Set the "relevant" title
279 * @see self::getRelevantTitle()
280 * @param Title $t
282 public function setRelevantTitle( $t ) {
283 $this->mRelevantTitle = $t;
287 * Return the "relevant" title.
288 * A "relevant" title is not necessarily the actual title of the page.
289 * Special pages like Special:MovePage use set the page they are acting on
290 * as their "relevant" title, this allows the skin system to display things
291 * such as content tabs which belong to to that page instead of displaying
292 * a basic special page tab which has almost no meaning.
294 * @return Title
296 public function getRelevantTitle() {
297 if ( isset( $this->mRelevantTitle ) ) {
298 return $this->mRelevantTitle;
300 return $this->getTitle();
304 * Set the "relevant" user
305 * @see self::getRelevantUser()
306 * @param User $u
308 public function setRelevantUser( $u ) {
309 $this->mRelevantUser = $u;
313 * Return the "relevant" user.
314 * A "relevant" user is similar to a relevant title. Special pages like
315 * Special:Contributions mark the user which they are relevant to so that
316 * things like the toolbox can display the information they usually are only
317 * able to display on a user's userpage and talkpage.
318 * @return User
320 public function getRelevantUser() {
321 if ( isset( $this->mRelevantUser ) ) {
322 return $this->mRelevantUser;
324 $title = $this->getRelevantTitle();
325 if ( $title->hasSubjectNamespace( NS_USER ) ) {
326 $rootUser = $title->getRootText();
327 if ( User::isIP( $rootUser ) ) {
328 $this->mRelevantUser = User::newFromName( $rootUser, false );
329 } else {
330 $user = User::newFromName( $rootUser, false );
332 if ( $user ) {
333 $user->load( User::READ_NORMAL );
335 if ( $user->isLoggedIn() ) {
336 $this->mRelevantUser = $user;
340 return $this->mRelevantUser;
342 return null;
346 * Outputs the HTML generated by other functions.
347 * @param OutputPage $out
349 abstract function outputPage( OutputPage $out = null );
352 * @param array $data
353 * @return string
355 static function makeVariablesScript( $data ) {
356 if ( $data ) {
357 return ResourceLoader::makeInlineScript(
358 ResourceLoader::makeConfigSetScript( $data )
360 } else {
361 return '';
366 * Get the query to generate a dynamic stylesheet
368 * @return array
370 public static function getDynamicStylesheetQuery() {
371 global $wgSquidMaxage;
373 return array(
374 'action' => 'raw',
375 'maxage' => $wgSquidMaxage,
376 'usemsgcache' => 'yes',
377 'ctype' => 'text/css',
378 'smaxage' => $wgSquidMaxage,
383 * Add skin specific stylesheets
384 * Calling this method with an $out of anything but the same OutputPage
385 * inside ->getOutput() is deprecated. The $out arg is kept
386 * for compatibility purposes with skins.
387 * @param OutputPage $out
388 * @todo delete
390 abstract function setupSkinUserCss( OutputPage $out );
393 * TODO: document
394 * @param Title $title
395 * @return string
397 function getPageClasses( $title ) {
398 $numeric = 'ns-' . $title->getNamespace();
400 if ( $title->isSpecialPage() ) {
401 $type = 'ns-special';
402 // bug 23315: provide a class based on the canonical special page name without subpages
403 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
404 if ( $canonicalName ) {
405 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
406 } else {
407 $type .= ' mw-invalidspecialpage';
409 } elseif ( $title->isTalkPage() ) {
410 $type = 'ns-talk';
411 } else {
412 $type = 'ns-subject';
415 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
417 return "$numeric $type $name";
421 * Return values for <html> element
422 * @return array Array of associative name-to-value elements for <html> element
424 public function getHtmlElementAttributes() {
425 $lang = $this->getLanguage();
426 return array(
427 'lang' => $lang->getHtmlCode(),
428 'dir' => $lang->getDir(),
429 'class' => 'client-nojs',
434 * This will be called by OutputPage::headElement when it is creating the
435 * "<body>" tag, skins can override it if they have a need to add in any
436 * body attributes or classes of their own.
437 * @param OutputPage $out
438 * @param array $bodyAttrs
440 function addToBodyAttributes( $out, &$bodyAttrs ) {
441 // does nothing by default
445 * URL to the logo
446 * @return string
448 function getLogo() {
449 global $wgLogo;
450 return $wgLogo;
454 * @return string
456 function getCategoryLinks() {
457 global $wgUseCategoryBrowser;
459 $out = $this->getOutput();
460 $allCats = $out->getCategoryLinks();
462 if ( !count( $allCats ) ) {
463 return '';
466 $embed = "<li>";
467 $pop = "</li>";
469 $s = '';
470 $colon = $this->msg( 'colon-separator' )->escaped();
472 if ( !empty( $allCats['normal'] ) ) {
473 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
475 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
476 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
477 $title = Title::newFromText( $linkPage );
478 $link = $title ? Linker::link( $title, $msg ) : $msg;
479 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
480 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
483 # Hidden categories
484 if ( isset( $allCats['hidden'] ) ) {
485 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
486 $class = ' mw-hidden-cats-user-shown';
487 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
488 $class = ' mw-hidden-cats-ns-shown';
489 } else {
490 $class = ' mw-hidden-cats-hidden';
493 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
494 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
495 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
496 '</div>';
499 # optional 'dmoz-like' category browser. Will be shown under the list
500 # of categories an article belong to
501 if ( $wgUseCategoryBrowser ) {
502 $s .= '<br /><hr />';
504 # get a big array of the parents tree
505 $parenttree = $this->getTitle()->getParentCategoryTree();
506 # Skin object passed by reference cause it can not be
507 # accessed under the method subfunction drawCategoryBrowser
508 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
509 # Clean out bogus first entry and sort them
510 unset( $tempout[0] );
511 asort( $tempout );
512 # Output one per line
513 $s .= implode( "<br />\n", $tempout );
516 return $s;
520 * Render the array as a series of links.
521 * @param array $tree Categories tree returned by Title::getParentCategoryTree
522 * @return string Separated by &gt;, terminate with "\n"
524 function drawCategoryBrowser( $tree ) {
525 $return = '';
527 foreach ( $tree as $element => $parent ) {
528 if ( empty( $parent ) ) {
529 # element start a new list
530 $return .= "\n";
531 } else {
532 # grab the others elements
533 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
536 # add our current element to the list
537 $eltitle = Title::newFromText( $element );
538 $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
541 return $return;
545 * @return string
547 function getCategories() {
548 $out = $this->getOutput();
550 $catlinks = $this->getCategoryLinks();
552 $classes = 'catlinks';
554 // Check what we're showing
555 $allCats = $out->getCategoryLinks();
556 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
557 $this->getTitle()->getNamespace() == NS_CATEGORY;
559 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
560 $classes .= ' catlinks-allhidden';
563 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
567 * This runs a hook to allow extensions placing their stuff after content
568 * and article metadata (e.g. categories).
569 * Note: This function has nothing to do with afterContent().
571 * This hook is placed here in order to allow using the same hook for all
572 * skins, both the SkinTemplate based ones and the older ones, which directly
573 * use this class to get their data.
575 * The output of this function gets processed in SkinTemplate::outputPage() for
576 * the SkinTemplate based skins, all other skins should directly echo it.
578 * @return string Empty by default, if not changed by any hook function.
580 protected function afterContentHook() {
581 $data = '';
583 if ( Hooks::run( 'SkinAfterContent', array( &$data, $this ) ) ) {
584 // adding just some spaces shouldn't toggle the output
585 // of the whole <div/>, so we use trim() here
586 if ( trim( $data ) != '' ) {
587 // Doing this here instead of in the skins to
588 // ensure that the div has the same ID in all
589 // skins
590 $data = "<div id='mw-data-after-content'>\n" .
591 "\t$data\n" .
592 "</div>\n";
594 } else {
595 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
598 return $data;
602 * Generate debug data HTML for displaying at the bottom of the main content
603 * area.
604 * @return string HTML containing debug data, if enabled (otherwise empty).
606 protected function generateDebugHTML() {
607 return MWDebug::getHTMLDebugLog();
611 * This gets called shortly before the "</body>" tag.
613 * @return string HTML-wrapped JS code to be put before "</body>"
615 function bottomScripts() {
616 // TODO and the suckage continues. This function is really just a wrapper around
617 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
618 // up at some point
619 $bottomScriptText = $this->getOutput()->getBottomScripts();
620 Hooks::run( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
622 return $bottomScriptText;
626 * Text with the permalink to the source page,
627 * usually shown on the footer of a printed page
629 * @return string HTML text with an URL
631 function printSource() {
632 $oldid = $this->getRevisionId();
633 if ( $oldid ) {
634 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
635 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
636 } else {
637 // oldid not available for non existing pages
638 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
641 return $this->msg( 'retrievedfrom' )
642 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
643 ->parse();
647 * @return string HTML
649 function getUndeleteLink() {
650 $action = $this->getRequest()->getVal( 'action', 'view' );
652 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
653 ( !$this->getTitle()->exists() || $action == 'history' ) ) {
654 $n = $this->getTitle()->isDeleted();
656 if ( $n ) {
657 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
658 $msg = 'thisisdeleted';
659 } else {
660 $msg = 'viewdeleted';
663 return $this->msg( $msg )->rawParams(
664 Linker::linkKnown(
665 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
666 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
667 )->escaped();
671 return '';
675 * @return string
677 function subPageSubtitle() {
678 $out = $this->getOutput();
679 $subpages = '';
681 if ( !Hooks::run( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
682 return $subpages;
685 if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) {
686 $ptext = $this->getTitle()->getPrefixedText();
687 if ( preg_match( '/\//', $ptext ) ) {
688 $links = explode( '/', $ptext );
689 array_pop( $links );
690 $c = 0;
691 $growinglink = '';
692 $display = '';
693 $lang = $this->getLanguage();
695 foreach ( $links as $link ) {
696 $growinglink .= $link;
697 $display .= $link;
698 $linkObj = Title::newFromText( $growinglink );
700 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
701 $getlink = Linker::linkKnown(
702 $linkObj,
703 htmlspecialchars( $display )
706 $c++;
708 if ( $c > 1 ) {
709 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
710 } else {
711 $subpages .= '&lt; ';
714 $subpages .= $getlink;
715 $display = '';
716 } else {
717 $display .= '/';
719 $growinglink .= '/';
724 return $subpages;
728 * @deprecated since 1.27, feature removed
729 * @return bool Always false
731 function showIPinHeader() {
732 wfDeprecated( __METHOD__, '1.27' );
733 return false;
737 * @return string
739 function getSearchLink() {
740 $searchPage = SpecialPage::getTitleFor( 'Search' );
741 return $searchPage->getLocalURL();
745 * @return string
747 function escapeSearchLink() {
748 return htmlspecialchars( $this->getSearchLink() );
752 * @param string $type
753 * @return string
755 function getCopyright( $type = 'detect' ) {
756 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
758 if ( $type == 'detect' ) {
759 if ( !$this->isRevisionCurrent()
760 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
762 $type = 'history';
763 } else {
764 $type = 'normal';
768 if ( $type == 'history' ) {
769 $msg = 'history_copyright';
770 } else {
771 $msg = 'copyright';
774 if ( $wgRightsPage ) {
775 $title = Title::newFromText( $wgRightsPage );
776 $link = Linker::linkKnown( $title, $wgRightsText );
777 } elseif ( $wgRightsUrl ) {
778 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
779 } elseif ( $wgRightsText ) {
780 $link = $wgRightsText;
781 } else {
782 # Give up now
783 return '';
786 // Allow for site and per-namespace customization of copyright notice.
787 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
788 $forContent = true;
790 Hooks::run(
791 'SkinCopyrightFooter',
792 array( $this->getTitle(), $type, &$msg, &$link, &$forContent )
795 return $this->msg( $msg )->rawParams( $link )->text();
799 * @return null|string
801 function getCopyrightIcon() {
802 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
804 $out = '';
806 if ( $wgCopyrightIcon ) {
807 $out = $wgCopyrightIcon;
808 } elseif ( $wgRightsIcon ) {
809 $icon = htmlspecialchars( $wgRightsIcon );
811 if ( $wgRightsUrl ) {
812 $url = htmlspecialchars( $wgRightsUrl );
813 $out .= '<a href="' . $url . '">';
816 $text = htmlspecialchars( $wgRightsText );
817 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
819 if ( $wgRightsUrl ) {
820 $out .= '</a>';
824 return $out;
828 * Gets the powered by MediaWiki icon.
829 * @return string
831 function getPoweredBy() {
832 global $wgResourceBasePath;
834 $url1 = htmlspecialchars(
835 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
837 $url1_5 = htmlspecialchars(
838 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
840 $url2 = htmlspecialchars(
841 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
843 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
844 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
845 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
846 Hooks::run( 'SkinGetPoweredBy', array( &$text, $this ) );
847 return $text;
851 * Get the timestamp of the latest revision, formatted in user language
853 * @return string
855 protected function lastModified() {
856 $timestamp = $this->getOutput()->getRevisionTimestamp();
858 # No cached timestamp, load it from the database
859 if ( $timestamp === null ) {
860 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
863 if ( $timestamp ) {
864 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
865 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
866 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
867 } else {
868 $s = '';
871 if ( wfGetLB()->getLaggedSlaveMode() ) {
872 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
875 return $s;
879 * @param string $align
880 * @return string
882 function logoText( $align = '' ) {
883 if ( $align != '' ) {
884 $a = " style='float: {$align};'";
885 } else {
886 $a = '';
889 $mp = $this->msg( 'mainpage' )->escaped();
890 $mptitle = Title::newMainPage();
891 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
893 $logourl = $this->getLogo();
894 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
896 return $s;
900 * Renders a $wgFooterIcons icon according to the method's arguments
901 * @param array $icon The icon to build the html for, see $wgFooterIcons
902 * for the format of this array.
903 * @param bool|string $withImage Whether to use the icon's image or output
904 * a text-only footericon.
905 * @return string HTML
907 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
908 if ( is_string( $icon ) ) {
909 $html = $icon;
910 } else { // Assuming array
911 $url = isset( $icon["url"] ) ? $icon["url"] : null;
912 unset( $icon["url"] );
913 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
914 // do this the lazy way, just pass icon data as an attribute array
915 $html = Html::element( 'img', $icon );
916 } else {
917 $html = htmlspecialchars( $icon["alt"] );
919 if ( $url ) {
920 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
923 return $html;
927 * Gets the link to the wiki's main page.
928 * @return string
930 function mainPageLink() {
931 $s = Linker::linkKnown(
932 Title::newMainPage(),
933 $this->msg( 'mainpage' )->escaped()
936 return $s;
940 * Returns an HTML link for use in the footer
941 * @param string $desc The i18n message key for the link text
942 * @param string $page The i18n message key for the page to link to
943 * @return string HTML anchor
945 public function footerLink( $desc, $page ) {
946 // if the link description has been set to "-" in the default language,
947 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
948 // then it is disabled, for all languages.
949 return '';
950 } else {
951 // Otherwise, we display the link for the user, described in their
952 // language (which may or may not be the same as the default language),
953 // but we make the link target be the one site-wide page.
954 $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
956 if ( !$title ) {
957 return '';
960 return Linker::linkKnown(
961 $title,
962 $this->msg( $desc )->escaped()
968 * Gets the link to the wiki's privacy policy page.
969 * @return string HTML
971 function privacyLink() {
972 return $this->footerLink( 'privacy', 'privacypage' );
976 * Gets the link to the wiki's about page.
977 * @return string HTML
979 function aboutLink() {
980 return $this->footerLink( 'aboutsite', 'aboutpage' );
984 * Gets the link to the wiki's general disclaimers page.
985 * @return string HTML
987 function disclaimerLink() {
988 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
992 * Return URL options for the 'edit page' link.
993 * This may include an 'oldid' specifier, if the current page view is such.
995 * @return array
996 * @private
998 function editUrlOptions() {
999 $options = array( 'action' => 'edit' );
1001 if ( !$this->isRevisionCurrent() ) {
1002 $options['oldid'] = intval( $this->getRevisionId() );
1005 return $options;
1009 * @param User|int $id
1010 * @return bool
1012 function showEmailUser( $id ) {
1013 if ( $id instanceof User ) {
1014 $targetUser = $id;
1015 } else {
1016 $targetUser = User::newFromId( $id );
1019 # The sending user must have a confirmed email address and the target
1020 # user must have a confirmed email address and allow emails from users.
1021 return $this->getUser()->canSendEmail() &&
1022 $targetUser->canReceiveEmail();
1026 * This function previously returned a fully resolved style path URL to images or styles stored in
1027 * the legacy skins/common/ directory.
1029 * That directory has been removed in 1.24 and the function always returns an empty string.
1031 * @deprecated since 1.24
1032 * @param string $name The name or path of a skin resource file
1033 * @return string Empty string
1035 function getCommonStylePath( $name ) {
1036 wfDeprecated( __METHOD__, '1.24' );
1037 return '';
1041 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1042 * This method returns a url resolved using the configured skin style path
1043 * and includes the style version inside of the url.
1045 * Requires $stylename to be set, otherwise throws MWException.
1047 * @param string $name The name or path of a skin resource file
1048 * @return string The fully resolved style path url including styleversion
1049 * @throws MWException
1051 function getSkinStylePath( $name ) {
1052 global $wgStylePath, $wgStyleVersion;
1054 if ( $this->stylename === null ) {
1055 $class = get_class( $this );
1056 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1059 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1062 /* these are used extensively in SkinTemplate, but also some other places */
1065 * @param string $urlaction
1066 * @return string
1068 static function makeMainPageUrl( $urlaction = '' ) {
1069 $title = Title::newMainPage();
1070 self::checkTitle( $title, '' );
1072 return $title->getLocalURL( $urlaction );
1076 * Make a URL for a Special Page using the given query and protocol.
1078 * If $proto is set to null, make a local URL. Otherwise, make a full
1079 * URL with the protocol specified.
1081 * @param string $name Name of the Special page
1082 * @param string $urlaction Query to append
1083 * @param string|null $proto Protocol to use or null for a local URL
1084 * @return string
1086 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1087 $title = SpecialPage::getSafeTitleFor( $name );
1088 if ( is_null( $proto ) ) {
1089 return $title->getLocalURL( $urlaction );
1090 } else {
1091 return $title->getFullURL( $urlaction, false, $proto );
1096 * @param string $name
1097 * @param string $subpage
1098 * @param string $urlaction
1099 * @return string
1101 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1102 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1103 return $title->getLocalURL( $urlaction );
1107 * @param string $name
1108 * @param string $urlaction
1109 * @return string
1111 static function makeI18nUrl( $name, $urlaction = '' ) {
1112 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1113 self::checkTitle( $title, $name );
1114 return $title->getLocalURL( $urlaction );
1118 * @param string $name
1119 * @param string $urlaction
1120 * @return string
1122 static function makeUrl( $name, $urlaction = '' ) {
1123 $title = Title::newFromText( $name );
1124 self::checkTitle( $title, $name );
1126 return $title->getLocalURL( $urlaction );
1130 * If url string starts with http, consider as external URL, else
1131 * internal
1132 * @param string $name
1133 * @return string URL
1135 static function makeInternalOrExternalUrl( $name ) {
1136 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1137 return $name;
1138 } else {
1139 return self::makeUrl( $name );
1144 * this can be passed the NS number as defined in Language.php
1145 * @param string $name
1146 * @param string $urlaction
1147 * @param int $namespace
1148 * @return string
1150 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1151 $title = Title::makeTitleSafe( $namespace, $name );
1152 self::checkTitle( $title, $name );
1154 return $title->getLocalURL( $urlaction );
1158 * these return an array with the 'href' and boolean 'exists'
1159 * @param string $name
1160 * @param string $urlaction
1161 * @return array
1163 static function makeUrlDetails( $name, $urlaction = '' ) {
1164 $title = Title::newFromText( $name );
1165 self::checkTitle( $title, $name );
1167 return array(
1168 'href' => $title->getLocalURL( $urlaction ),
1169 'exists' => $title->isKnown(),
1174 * Make URL details where the article exists (or at least it's convenient to think so)
1175 * @param string $name Article name
1176 * @param string $urlaction
1177 * @return array
1179 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1180 $title = Title::newFromText( $name );
1181 self::checkTitle( $title, $name );
1183 return array(
1184 'href' => $title->getLocalURL( $urlaction ),
1185 'exists' => true
1190 * make sure we have some title to operate on
1192 * @param Title $title
1193 * @param string $name
1195 static function checkTitle( &$title, $name ) {
1196 if ( !is_object( $title ) ) {
1197 $title = Title::newFromText( $name );
1198 if ( !is_object( $title ) ) {
1199 $title = Title::newFromText( '--error: link target missing--' );
1205 * Build an array that represents the sidebar(s), the navigation bar among them.
1207 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1209 * The format of the returned array is array( heading => content, ... ), where:
1210 * - heading is the heading of a navigation portlet. It is either:
1211 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1212 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1213 * - plain text, which should be HTML-escaped by the skin
1214 * - content is the contents of the portlet. It is either:
1215 * - HTML text (<ul><li>...</li>...</ul>)
1216 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1217 * - (for a magic string as a key, any value)
1219 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1220 * and can technically insert anything in here; skin creators are expected to handle
1221 * values described above.
1223 * @return array
1225 function buildSidebar() {
1226 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1228 $that = $this;
1229 $callback = function () use ( $that ) {
1230 $bar = array();
1231 $that->addToSidebar( $bar, 'sidebar' );
1232 Hooks::run( 'SkinBuildSidebar', array( $that, &$bar ) );
1234 return $bar;
1237 if ( $wgEnableSidebarCache ) {
1238 $cache = ObjectCache::getMainWANInstance();
1239 $sidebar = $cache->getWithSetCallback(
1240 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1241 $wgSidebarCacheExpiry,
1242 $callback,
1243 array( 'lockTSE' => 30 )
1245 } else {
1246 $sidebar = $callback();
1249 // Apply post-processing to the cached value
1250 Hooks::run( 'SidebarBeforeOutput', array( $this, &$sidebar ) );
1252 return $sidebar;
1256 * Add content from a sidebar system message
1257 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1259 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1261 * @param array $bar
1262 * @param string $message
1264 public function addToSidebar( &$bar, $message ) {
1265 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1269 * Add content from plain text
1270 * @since 1.17
1271 * @param array $bar
1272 * @param string $text
1273 * @return array
1275 function addToSidebarPlain( &$bar, $text ) {
1276 $lines = explode( "\n", $text );
1278 $heading = '';
1280 foreach ( $lines as $line ) {
1281 if ( strpos( $line, '*' ) !== 0 ) {
1282 continue;
1284 $line = rtrim( $line, "\r" ); // for Windows compat
1286 if ( strpos( $line, '**' ) !== 0 ) {
1287 $heading = trim( $line, '* ' );
1288 if ( !array_key_exists( $heading, $bar ) ) {
1289 $bar[$heading] = array();
1291 } else {
1292 $line = trim( $line, '* ' );
1294 if ( strpos( $line, '|' ) !== false ) { // sanity check
1295 $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() );
1296 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1297 if ( count( $line ) !== 2 ) {
1298 // Second sanity check, could be hit by people doing
1299 // funky stuff with parserfuncs... (bug 33321)
1300 continue;
1303 $extraAttribs = array();
1305 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1306 if ( $msgLink->exists() ) {
1307 $link = $msgLink->text();
1308 if ( $link == '-' ) {
1309 continue;
1311 } else {
1312 $link = $line[0];
1314 $msgText = $this->msg( $line[1] );
1315 if ( $msgText->exists() ) {
1316 $text = $msgText->text();
1317 } else {
1318 $text = $line[1];
1321 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1322 $href = $link;
1324 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1325 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1326 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1327 $extraAttribs['rel'] = 'nofollow';
1330 global $wgExternalLinkTarget;
1331 if ( $wgExternalLinkTarget ) {
1332 $extraAttribs['target'] = $wgExternalLinkTarget;
1334 } else {
1335 $title = Title::newFromText( $link );
1337 if ( $title ) {
1338 $title = $title->fixSpecialName();
1339 $href = $title->getLinkURL();
1340 } else {
1341 $href = 'INVALID-TITLE';
1345 $bar[$heading][] = array_merge( array(
1346 'text' => $text,
1347 'href' => $href,
1348 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1349 'active' => false
1350 ), $extraAttribs );
1351 } else {
1352 continue;
1357 return $bar;
1361 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1362 * should be loaded by OutputPage. That module no longer exists and the return value of this
1363 * method is ignored.
1365 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1366 * can be used instead (SkinTemplate-based skins do it automatically).
1368 * @deprecated since 1.22
1369 * @return bool
1371 public function commonPrintStylesheet() {
1372 wfDeprecated( __METHOD__, '1.22' );
1373 return false;
1377 * Gets new talk page messages for the current user and returns an
1378 * appropriate alert message (or an empty string if there are no messages)
1379 * @return string
1381 function getNewtalks() {
1383 $newMessagesAlert = '';
1384 $user = $this->getUser();
1385 $newtalks = $user->getNewMessageLinks();
1386 $out = $this->getOutput();
1388 // Allow extensions to disable or modify the new messages alert
1389 if ( !Hooks::run( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1390 return '';
1392 if ( $newMessagesAlert ) {
1393 return $newMessagesAlert;
1396 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1397 $uTalkTitle = $user->getTalkPage();
1398 $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null;
1399 $nofAuthors = 0;
1400 if ( $lastSeenRev !== null ) {
1401 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1402 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1403 if ( $latestRev !== null ) {
1404 // Singular if only 1 unseen revision, plural if several unseen revisions.
1405 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1406 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1407 $lastSeenRev, $latestRev, 10, 'include_new' );
1409 } else {
1410 // Singular if no revision -> diff link will show latest change only in any case
1411 $plural = false;
1413 $plural = $plural ? 999 : 1;
1414 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1415 // the number of revisions or authors is not necessarily the same as the number of
1416 // "messages".
1417 $newMessagesLink = Linker::linkKnown(
1418 $uTalkTitle,
1419 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1420 array(),
1421 array( 'redirect' => 'no' )
1424 $newMessagesDiffLink = Linker::linkKnown(
1425 $uTalkTitle,
1426 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1427 array(),
1428 $lastSeenRev !== null
1429 ? array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1430 : array( 'diff' => 'cur' )
1433 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1434 $newMessagesAlert = $this->msg(
1435 'youhavenewmessagesfromusers',
1436 $newMessagesLink,
1437 $newMessagesDiffLink
1438 )->numParams( $nofAuthors, $plural );
1439 } else {
1440 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1441 $newMessagesAlert = $this->msg(
1442 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1443 $newMessagesLink,
1444 $newMessagesDiffLink
1445 )->numParams( $plural );
1447 $newMessagesAlert = $newMessagesAlert->text();
1448 # Disable CDN cache
1449 $out->setCdnMaxage( 0 );
1450 } elseif ( count( $newtalks ) ) {
1451 $sep = $this->msg( 'newtalkseparator' )->escaped();
1452 $msgs = array();
1454 foreach ( $newtalks as $newtalk ) {
1455 $msgs[] = Xml::element(
1456 'a',
1457 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1460 $parts = implode( $sep, $msgs );
1461 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1462 $out->setCdnMaxage( 0 );
1465 return $newMessagesAlert;
1469 * Get a cached notice
1471 * @param string $name Message name, or 'default' for $wgSiteNotice
1472 * @return string|bool HTML fragment, or false to indicate that the caller
1473 * should fall back to the next notice in its sequence
1475 private function getCachedNotice( $name ) {
1476 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1478 $needParse = false;
1480 if ( $name === 'default' ) {
1481 // special case
1482 global $wgSiteNotice;
1483 $notice = $wgSiteNotice;
1484 if ( empty( $notice ) ) {
1485 return false;
1487 } else {
1488 $msg = $this->msg( $name )->inContentLanguage();
1489 if ( $msg->isBlank() ) {
1490 return '';
1491 } elseif ( $msg->isDisabled() ) {
1492 return false;
1494 $notice = $msg->plain();
1497 // Use the extra hash appender to let eg SSL variants separately cache.
1498 $key = wfMemcKey( $name . $wgRenderHashAppend );
1499 $cachedNotice = $parserMemc->get( $key );
1500 if ( is_array( $cachedNotice ) ) {
1501 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1502 $notice = $cachedNotice['html'];
1503 } else {
1504 $needParse = true;
1506 } else {
1507 $needParse = true;
1510 if ( $needParse ) {
1511 $parsed = $this->getOutput()->parse( $notice );
1512 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1513 $notice = $parsed;
1516 $notice = Html::rawElement( 'div', array( 'id' => 'localNotice',
1517 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1518 return $notice;
1522 * Get the site notice
1524 * @return string HTML fragment
1526 function getSiteNotice() {
1527 $siteNotice = '';
1529 if ( Hooks::run( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1530 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1531 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1532 } else {
1533 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1534 if ( $anonNotice === false ) {
1535 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1536 } else {
1537 $siteNotice = $anonNotice;
1540 if ( $siteNotice === false ) {
1541 $siteNotice = $this->getCachedNotice( 'default' );
1545 Hooks::run( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1546 return $siteNotice;
1550 * Create a section edit link. This supersedes editSectionLink() and
1551 * editSectionLinkForOther().
1553 * @param Title $nt The title being linked to (may not be the same as
1554 * the current page, if the section is included from a template)
1555 * @param string $section The designation of the section being pointed to,
1556 * to be included in the link, like "&section=$section"
1557 * @param string $tooltip The tooltip to use for the link: will be escaped
1558 * and wrapped in the 'editsectionhint' message
1559 * @param string $lang Language code
1560 * @return string HTML to use for edit link
1562 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1563 // HTML generated here should probably have userlangattributes
1564 // added to it for LTR text on RTL pages
1566 $lang = wfGetLangObj( $lang );
1568 $attribs = array();
1569 if ( !is_null( $tooltip ) ) {
1570 # Bug 25462: undo double-escaping.
1571 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1572 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1573 ->inLanguage( $lang )->text();
1576 $links = array(
1577 'editsection' => array(
1578 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1579 'targetTitle' => $nt,
1580 'attribs' => $attribs,
1581 'query' => array( 'action' => 'edit', 'section' => $section ),
1582 'options' => array( 'noclasses', 'known' )
1586 Hooks::run( 'SkinEditSectionLinks', array( $this, $nt, $section, $tooltip, &$links, $lang ) );
1588 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1590 $linksHtml = array();
1591 foreach ( $links as $k => $linkDetails ) {
1592 $linksHtml[] = Linker::link(
1593 $linkDetails['targetTitle'],
1594 $linkDetails['text'],
1595 $linkDetails['attribs'],
1596 $linkDetails['query'],
1597 $linkDetails['options']
1601 $result .= implode(
1602 '<span class="mw-editsection-divider">'
1603 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1604 . '</span>',
1605 $linksHtml
1608 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1609 // Deprecated, use SkinEditSectionLinks hook instead
1610 Hooks::run(
1611 'DoEditSectionLink',
1612 array( $this, $nt, $section, $tooltip, &$result, $lang ),
1613 '1.25'
1615 return $result;
1619 * Use PHP's magic __call handler to intercept legacy calls to the linker
1620 * for backwards compatibility.
1622 * @param string $fname Name of called method
1623 * @param array $args Arguments to the method
1624 * @throws MWException
1625 * @return mixed
1627 function __call( $fname, $args ) {
1628 $realFunction = array( 'Linker', $fname );
1629 if ( is_callable( $realFunction ) ) {
1630 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1631 return call_user_func_array( $realFunction, $args );
1632 } else {
1633 $className = get_class( $this );
1634 throw new MWException( "Call to undefined method $className::$fname" );