Non-word characters don't terminate tag names.
[mediawiki.git] / includes / Skin.php
blobde9c9dc9282348d1105aa9312623788924a806e3
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.
29 * This base class is also the "Standard" skin.
31 * See docs/skin.txt for more information.
33 * @ingroup Skins
35 abstract class Skin extends ContextSource {
36 protected $skinname = 'standard';
37 protected $mRelevantTitle = null;
38 protected $mRelevantUser = null;
40 /**
41 * Fetch the set of available skins.
42 * @return array associative array of strings
44 static function getSkinNames() {
45 global $wgValidSkinNames;
46 static $skinsInitialised = false;
48 if ( !$skinsInitialised || !count( $wgValidSkinNames ) ) {
49 # Get a list of available skins
50 # Build using the regular expression '^(.*).php$'
51 # Array keys are all lower case, array value keep the case used by filename
53 wfProfileIn( __METHOD__ . '-init' );
55 global $wgStyleDirectory;
57 $skinDir = dir( $wgStyleDirectory );
59 if ( $skinDir !== false && $skinDir !== null ) {
60 # while code from www.php.net
61 while ( false !== ( $file = $skinDir->read() ) ) {
62 // Skip non-PHP files, hidden files, and '.dep' includes
63 $matches = array();
65 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
66 $aSkin = $matches[1];
67 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
70 $skinDir->close();
72 $skinsInitialised = true;
73 wfProfileOut( __METHOD__ . '-init' );
75 return $wgValidSkinNames;
78 /**
79 * Fetch the skinname messages for available skins.
80 * @return array of strings
82 static function getSkinNameMessages() {
83 $messages = array();
84 foreach ( self::getSkinNames() as $skinKey => $skinName ) {
85 $messages[] = "skinname-$skinKey";
87 return $messages;
90 /**
91 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
92 * Useful for Special:Preferences and other places where you
93 * only want to show skins users _can_ use.
94 * @return array of strings
96 public static function getUsableSkins() {
97 global $wgSkipSkins;
99 $allowedSkins = self::getSkinNames();
101 foreach ( $wgSkipSkins as $skip ) {
102 unset( $allowedSkins[$skip] );
105 return $allowedSkins;
109 * Normalize a skin preference value to a form that can be loaded.
110 * If a skin can't be found, it will fall back to the configured
111 * default (or the old 'Classic' skin if that's broken).
112 * @param string $key 'monobook', 'standard', etc.
113 * @return string
115 static function normalizeKey( $key ) {
116 global $wgDefaultSkin;
118 $skinNames = Skin::getSkinNames();
120 if ( $key == '' || $key == 'default' ) {
121 // Don't return the default immediately;
122 // in a misconfiguration we need to fall back.
123 $key = $wgDefaultSkin;
126 if ( isset( $skinNames[$key] ) ) {
127 return $key;
130 // Older versions of the software used a numeric setting
131 // in the user preferences.
132 $fallback = array(
133 0 => $wgDefaultSkin,
134 2 => 'cologneblue'
137 if ( isset( $fallback[$key] ) ) {
138 $key = $fallback[$key];
141 if ( isset( $skinNames[$key] ) ) {
142 return $key;
143 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
144 return $wgDefaultSkin;
145 } else {
146 return 'vector';
151 * Factory method for loading a skin of a given type
152 * @param string $key 'monobook', 'standard', etc.
153 * @return Skin
155 static function &newFromKey( $key ) {
156 global $wgStyleDirectory;
158 $key = Skin::normalizeKey( $key );
160 $skinNames = Skin::getSkinNames();
161 $skinName = $skinNames[$key];
162 $className = "Skin{$skinName}";
164 # Grab the skin class and initialise it.
165 if ( !class_exists( $className ) ) {
167 require_once "{$wgStyleDirectory}/{$skinName}.php";
169 # Check if we got if not fallback to default skin
170 if ( !class_exists( $className ) ) {
171 # DO NOT die if the class isn't found. This breaks maintenance
172 # scripts and can cause a user account to be unrecoverable
173 # except by SQL manipulation if a previously valid skin name
174 # is no longer valid.
175 wfDebug( "Skin class does not exist: $className\n" );
176 $className = 'SkinVector';
177 require_once "{$wgStyleDirectory}/Vector.php";
180 $skin = new $className( $key );
181 return $skin;
184 /** @return string skin name */
185 public function getSkinName() {
186 return $this->skinname;
190 * @param $out OutputPage
192 function initPage( OutputPage $out ) {
193 wfProfileIn( __METHOD__ );
195 $this->preloadExistence();
197 wfProfileOut( __METHOD__ );
201 * Defines the ResourceLoader modules that should be added to the skin
202 * It is recommended that skins wishing to override call parent::getDefaultModules()
203 * and substitute out any modules they wish to change by using a key to look them up
204 * @return Array of modules with helper keys for easy overriding
206 public function getDefaultModules() {
207 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
208 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
210 $out = $this->getOutput();
211 $user = $out->getUser();
212 $modules = array(
213 // modules that enhance the page content in some way
214 'content' => array(
215 'mediawiki.page.ready',
217 // modules that exist for legacy reasons
218 'legacy' => array(),
219 // modules relating to search functionality
220 'search' => array(),
221 // modules relating to functionality relating to watching an article
222 'watch' => array(),
223 // modules which relate to the current users preferences
224 'user' => array(),
226 if ( $wgIncludeLegacyJavaScript ) {
227 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
230 if ( $wgPreloadJavaScriptMwUtil ) {
231 $modules['legacy'][] = 'mediawiki.util';
234 // Add various resources if required
235 if ( $wgUseAjax ) {
236 $modules['legacy'][] = 'mediawiki.legacy.ajax';
238 if ( $wgEnableAPI ) {
239 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
240 && $user->isAllowed( 'writeapi' )
242 $modules['watch'][] = 'mediawiki.page.watch.ajax';
245 if ( !$user->getOption( 'disablesuggest', false ) ) {
246 $modules['search'][] = 'mediawiki.searchSuggest';
251 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
252 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
255 // Crazy edit-on-double-click stuff
256 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
257 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
259 return $modules;
263 * Preload the existence of three commonly-requested pages in a single query
265 function preloadExistence() {
266 $user = $this->getUser();
268 // User/talk link
269 $titles = array( $user->getUserPage(), $user->getTalkPage() );
271 // Other tab link
272 if ( $this->getTitle()->isSpecialPage() ) {
273 // nothing
274 } elseif ( $this->getTitle()->isTalkPage() ) {
275 $titles[] = $this->getTitle()->getSubjectPage();
276 } else {
277 $titles[] = $this->getTitle()->getTalkPage();
280 $lb = new LinkBatch( $titles );
281 $lb->setCaller( __METHOD__ );
282 $lb->execute();
286 * Get the current revision ID
288 * @return Integer
290 public function getRevisionId() {
291 return $this->getOutput()->getRevisionId();
295 * Whether the revision displayed is the latest revision of the page
297 * @return Boolean
299 public function isRevisionCurrent() {
300 $revID = $this->getRevisionId();
301 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
305 * Set the "relevant" title
306 * @see self::getRelevantTitle()
307 * @param $t Title object to use
309 public function setRelevantTitle( $t ) {
310 $this->mRelevantTitle = $t;
314 * Return the "relevant" title.
315 * A "relevant" title is not necessarily the actual title of the page.
316 * Special pages like Special:MovePage use set the page they are acting on
317 * as their "relevant" title, this allows the skin system to display things
318 * such as content tabs which belong to to that page instead of displaying
319 * a basic special page tab which has almost no meaning.
321 * @return Title
323 public function getRelevantTitle() {
324 if ( isset( $this->mRelevantTitle ) ) {
325 return $this->mRelevantTitle;
327 return $this->getTitle();
331 * Set the "relevant" user
332 * @see self::getRelevantUser()
333 * @param $u User object to use
335 public function setRelevantUser( $u ) {
336 $this->mRelevantUser = $u;
340 * Return the "relevant" user.
341 * A "relevant" user is similar to a relevant title. Special pages like
342 * Special:Contributions mark the user which they are relevant to so that
343 * things like the toolbox can display the information they usually are only
344 * able to display on a user's userpage and talkpage.
345 * @return User
347 public function getRelevantUser() {
348 if ( isset( $this->mRelevantUser ) ) {
349 return $this->mRelevantUser;
351 $title = $this->getRelevantTitle();
352 if ( $title->hasSubjectNamespace( NS_USER ) ) {
353 $rootUser = $title->getRootText();
354 if ( User::isIP( $rootUser ) ) {
355 $this->mRelevantUser = User::newFromName( $rootUser, false );
356 } else {
357 $user = User::newFromName( $rootUser, false );
358 if ( $user && $user->isLoggedIn() ) {
359 $this->mRelevantUser = $user;
362 return $this->mRelevantUser;
364 return null;
368 * Outputs the HTML generated by other functions.
369 * @param $out OutputPage
371 abstract function outputPage( OutputPage $out = null );
374 * @param $data array
375 * @return string
377 static function makeVariablesScript( $data ) {
378 if ( $data ) {
379 return Html::inlineScript(
380 ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) )
382 } else {
383 return '';
388 * Make a "<script>" tag containing global variables
390 * @deprecated in 1.19
391 * @param $unused
392 * @return string HTML fragment
394 public static function makeGlobalVariablesScript( $unused ) {
395 global $wgOut;
397 wfDeprecated( __METHOD__, '1.19' );
399 return self::makeVariablesScript( $wgOut->getJSVars() );
403 * Get the query to generate a dynamic stylesheet
405 * @return array
407 public static function getDynamicStylesheetQuery() {
408 global $wgSquidMaxage;
410 return array(
411 'action' => 'raw',
412 'maxage' => $wgSquidMaxage,
413 'usemsgcache' => 'yes',
414 'ctype' => 'text/css',
415 'smaxage' => $wgSquidMaxage,
420 * Add skin specific stylesheets
421 * Calling this method with an $out of anything but the same OutputPage
422 * inside ->getOutput() is deprecated. The $out arg is kept
423 * for compatibility purposes with skins.
424 * @param $out OutputPage
425 * @todo delete
427 abstract function setupSkinUserCss( OutputPage $out );
430 * TODO: document
431 * @param $title Title
432 * @return String
434 function getPageClasses( $title ) {
435 $numeric = 'ns-' . $title->getNamespace();
437 if ( $title->isSpecialPage() ) {
438 $type = 'ns-special';
439 // bug 23315: provide a class based on the canonical special page name without subpages
440 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
441 if ( $canonicalName ) {
442 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
443 } else {
444 $type .= ' mw-invalidspecialpage';
446 } elseif ( $title->isTalkPage() ) {
447 $type = 'ns-talk';
448 } else {
449 $type = 'ns-subject';
452 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
454 return "$numeric $type $name";
458 * This will be called by OutputPage::headElement when it is creating the
459 * "<body>" tag, skins can override it if they have a need to add in any
460 * body attributes or classes of their own.
461 * @param $out OutputPage
462 * @param $bodyAttrs Array
464 function addToBodyAttributes( $out, &$bodyAttrs ) {
465 // does nothing by default
469 * URL to the logo
470 * @return String
472 function getLogo() {
473 global $wgLogo;
474 return $wgLogo;
478 * @return string
480 function getCategoryLinks() {
481 global $wgUseCategoryBrowser;
483 $out = $this->getOutput();
484 $allCats = $out->getCategoryLinks();
486 if ( !count( $allCats ) ) {
487 return '';
490 $embed = "<li>";
491 $pop = "</li>";
493 $s = '';
494 $colon = $this->msg( 'colon-separator' )->escaped();
496 if ( !empty( $allCats['normal'] ) ) {
497 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
499 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
500 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
501 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
502 Linker::link( Title::newFromText( $linkPage ), $msg )
503 . $colon . '<ul>' . $t . '</ul>' . '</div>';
506 # Hidden categories
507 if ( isset( $allCats['hidden'] ) ) {
508 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
509 $class = ' mw-hidden-cats-user-shown';
510 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
511 $class = ' mw-hidden-cats-ns-shown';
512 } else {
513 $class = ' mw-hidden-cats-hidden';
516 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
517 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
518 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
519 '</div>';
522 # optional 'dmoz-like' category browser. Will be shown under the list
523 # of categories an article belong to
524 if ( $wgUseCategoryBrowser ) {
525 $s .= '<br /><hr />';
527 # get a big array of the parents tree
528 $parenttree = $this->getTitle()->getParentCategoryTree();
529 # Skin object passed by reference cause it can not be
530 # accessed under the method subfunction drawCategoryBrowser
531 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
532 # Clean out bogus first entry and sort them
533 unset( $tempout[0] );
534 asort( $tempout );
535 # Output one per line
536 $s .= implode( "<br />\n", $tempout );
539 return $s;
543 * Render the array as a series of links.
544 * @param array $tree categories tree returned by Title::getParentCategoryTree
545 * @return String separated by &gt;, terminate with "\n"
547 function drawCategoryBrowser( $tree ) {
548 $return = '';
550 foreach ( $tree as $element => $parent ) {
551 if ( empty( $parent ) ) {
552 # element start a new list
553 $return .= "\n";
554 } else {
555 # grab the others elements
556 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
559 # add our current element to the list
560 $eltitle = Title::newFromText( $element );
561 $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
564 return $return;
568 * @return string
570 function getCategories() {
571 $out = $this->getOutput();
573 $catlinks = $this->getCategoryLinks();
575 $classes = 'catlinks';
577 // Check what we're showing
578 $allCats = $out->getCategoryLinks();
579 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
580 $this->getTitle()->getNamespace() == NS_CATEGORY;
582 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
583 $classes .= ' catlinks-allhidden';
586 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
590 * This runs a hook to allow extensions placing their stuff after content
591 * and article metadata (e.g. categories).
592 * Note: This function has nothing to do with afterContent().
594 * This hook is placed here in order to allow using the same hook for all
595 * skins, both the SkinTemplate based ones and the older ones, which directly
596 * use this class to get their data.
598 * The output of this function gets processed in SkinTemplate::outputPage() for
599 * the SkinTemplate based skins, all other skins should directly echo it.
601 * @return String, empty by default, if not changed by any hook function.
603 protected function afterContentHook() {
604 $data = '';
606 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
607 // adding just some spaces shouldn't toggle the output
608 // of the whole <div/>, so we use trim() here
609 if ( trim( $data ) != '' ) {
610 // Doing this here instead of in the skins to
611 // ensure that the div has the same ID in all
612 // skins
613 $data = "<div id='mw-data-after-content'>\n" .
614 "\t$data\n" .
615 "</div>\n";
617 } else {
618 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
621 return $data;
625 * Generate debug data HTML for displaying at the bottom of the main content
626 * area.
627 * @return String HTML containing debug data, if enabled (otherwise empty).
629 protected function generateDebugHTML() {
630 return MWDebug::getHTMLDebugLog();
634 * This gets called shortly before the "</body>" tag.
636 * @return String HTML-wrapped JS code to be put before "</body>"
638 function bottomScripts() {
639 // TODO and the suckage continues. This function is really just a wrapper around
640 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
641 // up at some point
642 $bottomScriptText = $this->getOutput()->getBottomScripts();
643 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
645 return $bottomScriptText;
649 * Text with the permalink to the source page,
650 * usually shown on the footer of a printed page
652 * @return string HTML text with an URL
654 function printSource() {
655 $oldid = $this->getRevisionId();
656 if ( $oldid ) {
657 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ) ) );
658 } else {
659 // oldid not available for non existing pages
660 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
662 return $this->msg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' )->text();
666 * @return String
668 function getUndeleteLink() {
669 $action = $this->getRequest()->getVal( 'action', 'view' );
671 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
672 ( $this->getTitle()->getArticleID() == 0 || $action == 'history' ) ) {
673 $n = $this->getTitle()->isDeleted();
675 if ( $n ) {
676 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
677 $msg = 'thisisdeleted';
678 } else {
679 $msg = 'viewdeleted';
682 return $this->msg( $msg )->rawParams(
683 Linker::linkKnown(
684 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
685 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
686 )->text();
690 return '';
694 * @return string
696 function subPageSubtitle() {
697 global $wgLang;
698 $out = $this->getOutput();
699 $subpages = '';
701 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
702 return $subpages;
705 if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) {
706 $ptext = $this->getTitle()->getPrefixedText();
707 if ( preg_match( '/\//', $ptext ) ) {
708 $links = explode( '/', $ptext );
709 array_pop( $links );
710 $c = 0;
711 $growinglink = '';
712 $display = '';
714 foreach ( $links as $link ) {
715 $growinglink .= $link;
716 $display .= $link;
717 $linkObj = Title::newFromText( $growinglink );
719 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
720 $getlink = Linker::linkKnown(
721 $linkObj,
722 htmlspecialchars( $display )
725 $c++;
727 if ( $c > 1 ) {
728 $subpages .= $wgLang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
729 } else {
730 $subpages .= '&lt; ';
733 $subpages .= $getlink;
734 $display = '';
735 } else {
736 $display .= '/';
738 $growinglink .= '/';
743 return $subpages;
747 * Returns true if the IP should be shown in the header
748 * @return Bool
750 function showIPinHeader() {
751 global $wgShowIPinHeader;
752 return $wgShowIPinHeader && session_id() != '';
756 * @return String
758 function getSearchLink() {
759 $searchPage = SpecialPage::getTitleFor( 'Search' );
760 return $searchPage->getLocalURL();
764 * @return string
766 function escapeSearchLink() {
767 return htmlspecialchars( $this->getSearchLink() );
771 * @param $type string
772 * @return string
774 function getCopyright( $type = 'detect' ) {
775 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
777 if ( $type == 'detect' ) {
778 if ( !$this->isRevisionCurrent() && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled() ) {
779 $type = 'history';
780 } else {
781 $type = 'normal';
785 if ( $type == 'history' ) {
786 $msg = 'history_copyright';
787 } else {
788 $msg = 'copyright';
791 if ( $wgRightsPage ) {
792 $title = Title::newFromText( $wgRightsPage );
793 $link = Linker::linkKnown( $title, $wgRightsText );
794 } elseif ( $wgRightsUrl ) {
795 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
796 } elseif ( $wgRightsText ) {
797 $link = $wgRightsText;
798 } else {
799 # Give up now
800 return '';
803 // Allow for site and per-namespace customization of copyright notice.
804 $forContent = true;
806 wfRunHooks( 'SkinCopyrightFooter', array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) );
808 $msgObj = $this->msg( $msg )->rawParams( $link );
809 if ( $forContent ) {
810 $msg = $msgObj->inContentLanguage()->text();
811 if ( $this->getLanguage()->getCode() !== $wgContLang->getCode() ) {
812 $msg = Html::rawElement( 'span', array( 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $msg );
814 return $msg;
815 } else {
816 return $msgObj->text();
821 * @return null|string
823 function getCopyrightIcon() {
824 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
826 $out = '';
828 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
829 $out = $wgCopyrightIcon;
830 } elseif ( $wgRightsIcon ) {
831 $icon = htmlspecialchars( $wgRightsIcon );
833 if ( $wgRightsUrl ) {
834 $url = htmlspecialchars( $wgRightsUrl );
835 $out .= '<a href="' . $url . '">';
838 $text = htmlspecialchars( $wgRightsText );
839 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
841 if ( $wgRightsUrl ) {
842 $out .= '</a>';
846 return $out;
850 * Gets the powered by MediaWiki icon.
851 * @return string
853 function getPoweredBy() {
854 global $wgStylePath;
856 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
857 $text = '<a href="//www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
858 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
859 return $text;
863 * Get the timestamp of the latest revision, formatted in user language
865 * @return String
867 protected function lastModified() {
868 $timestamp = $this->getOutput()->getRevisionTimestamp();
870 # No cached timestamp, load it from the database
871 if ( $timestamp === null ) {
872 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
875 if ( $timestamp ) {
876 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
877 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
878 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
879 } else {
880 $s = '';
883 if ( wfGetLB()->getLaggedSlaveMode() ) {
884 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
887 return $s;
891 * @param $align string
892 * @return string
894 function logoText( $align = '' ) {
895 if ( $align != '' ) {
896 $a = " style='float: {$align};'";
897 } else {
898 $a = '';
901 $mp = $this->msg( 'mainpage' )->escaped();
902 $mptitle = Title::newMainPage();
903 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
905 $logourl = $this->getLogo();
906 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
908 return $s;
912 * Renders a $wgFooterIcons icon according to the method's arguments
913 * @param array $icon The icon to build the html for, see $wgFooterIcons for the format of this array
914 * @param bool|String $withImage Whether to use the icon's image or output a text-only footericon
915 * @return String HTML
917 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
918 if ( is_string( $icon ) ) {
919 $html = $icon;
920 } else { // Assuming array
921 $url = isset( $icon["url"] ) ? $icon["url"] : null;
922 unset( $icon["url"] );
923 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
924 $html = Html::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
925 } else {
926 $html = htmlspecialchars( $icon["alt"] );
928 if ( $url ) {
929 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
932 return $html;
936 * Gets the link to the wiki's main page.
937 * @return string
939 function mainPageLink() {
940 $s = Linker::linkKnown(
941 Title::newMainPage(),
942 $this->msg( 'mainpage' )->escaped()
945 return $s;
949 * @param $desc
950 * @param $page
951 * @return string
953 public function footerLink( $desc, $page ) {
954 // if the link description has been set to "-" in the default language,
955 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
956 // then it is disabled, for all languages.
957 return '';
958 } else {
959 // Otherwise, we display the link for the user, described in their
960 // language (which may or may not be the same as the default language),
961 // but we make the link target be the one site-wide page.
962 $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
964 return Linker::linkKnown(
965 $title,
966 $this->msg( $desc )->escaped()
972 * Gets the link to the wiki's privacy policy page.
973 * @return String HTML
975 function privacyLink() {
976 return $this->footerLink( 'privacy', 'privacypage' );
980 * Gets the link to the wiki's about page.
981 * @return String HTML
983 function aboutLink() {
984 return $this->footerLink( 'aboutsite', 'aboutpage' );
988 * Gets the link to the wiki's general disclaimers page.
989 * @return String HTML
991 function disclaimerLink() {
992 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
996 * Return URL options for the 'edit page' link.
997 * This may include an 'oldid' specifier, if the current page view is such.
999 * @return array
1000 * @private
1002 function editUrlOptions() {
1003 $options = array( 'action' => 'edit' );
1005 if ( !$this->isRevisionCurrent() ) {
1006 $options['oldid'] = intval( $this->getRevisionId() );
1009 return $options;
1013 * @param $id User|int
1014 * @return bool
1016 function showEmailUser( $id ) {
1017 if ( $id instanceof User ) {
1018 $targetUser = $id;
1019 } else {
1020 $targetUser = User::newFromId( $id );
1022 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
1023 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
1027 * Return a fully resolved style path url to images or styles stored in the common folder.
1028 * This method returns a url resolved using the configured skin style path
1029 * and includes the style version inside of the url.
1030 * @param string $name The name or path of a skin resource file
1031 * @return String The fully resolved style path url including styleversion
1033 function getCommonStylePath( $name ) {
1034 global $wgStylePath, $wgStyleVersion;
1035 return "$wgStylePath/common/$name?$wgStyleVersion";
1039 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1040 * This method returns a url resolved using the configured skin style path
1041 * and includes the style version inside of the url.
1042 * @param string $name The name or path of a skin resource file
1043 * @return String The fully resolved style path url including styleversion
1045 function getSkinStylePath( $name ) {
1046 global $wgStylePath, $wgStyleVersion;
1047 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1050 /* these are used extensively in SkinTemplate, but also some other places */
1053 * @param $urlaction string
1054 * @return String
1056 static function makeMainPageUrl( $urlaction = '' ) {
1057 $title = Title::newMainPage();
1058 self::checkTitle( $title, '' );
1060 return $title->getLocalURL( $urlaction );
1064 * Make a URL for a Special Page using the given query and protocol.
1066 * If $proto is set to null, make a local URL. Otherwise, make a full
1067 * URL with the protocol specified.
1069 * @param string $name Name of the Special page
1070 * @param string $urlaction Query to append
1071 * @param $proto Protocol to use or null for a local URL
1072 * @return String
1074 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1075 $title = SpecialPage::getSafeTitleFor( $name );
1076 if ( is_null( $proto ) ) {
1077 return $title->getLocalURL( $urlaction );
1078 } else {
1079 return $title->getFullURL( $urlaction, false, $proto );
1084 * @param $name string
1085 * @param $subpage string
1086 * @param $urlaction string
1087 * @return String
1089 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1090 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1091 return $title->getLocalURL( $urlaction );
1095 * @param $name string
1096 * @param $urlaction string
1097 * @return String
1099 static function makeI18nUrl( $name, $urlaction = '' ) {
1100 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1101 self::checkTitle( $title, $name );
1102 return $title->getLocalURL( $urlaction );
1106 * @param $name string
1107 * @param $urlaction string
1108 * @return String
1110 static function makeUrl( $name, $urlaction = '' ) {
1111 $title = Title::newFromText( $name );
1112 self::checkTitle( $title, $name );
1114 return $title->getLocalURL( $urlaction );
1118 * If url string starts with http, consider as external URL, else
1119 * internal
1120 * @param $name String
1121 * @return String URL
1123 static function makeInternalOrExternalUrl( $name ) {
1124 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1125 return $name;
1126 } else {
1127 return self::makeUrl( $name );
1132 * this can be passed the NS number as defined in Language.php
1133 * @param $name
1134 * @param $urlaction string
1135 * @param $namespace int
1136 * @return String
1138 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1139 $title = Title::makeTitleSafe( $namespace, $name );
1140 self::checkTitle( $title, $name );
1142 return $title->getLocalURL( $urlaction );
1146 * these return an array with the 'href' and boolean 'exists'
1147 * @param $name
1148 * @param $urlaction string
1149 * @return array
1151 static function makeUrlDetails( $name, $urlaction = '' ) {
1152 $title = Title::newFromText( $name );
1153 self::checkTitle( $title, $name );
1155 return array(
1156 'href' => $title->getLocalURL( $urlaction ),
1157 'exists' => $title->getArticleID() != 0,
1162 * Make URL details where the article exists (or at least it's convenient to think so)
1163 * @param string $name Article name
1164 * @param $urlaction String
1165 * @return Array
1167 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1168 $title = Title::newFromText( $name );
1169 self::checkTitle( $title, $name );
1171 return array(
1172 'href' => $title->getLocalURL( $urlaction ),
1173 'exists' => true
1178 * make sure we have some title to operate on
1180 * @param $title Title
1181 * @param $name string
1183 static function checkTitle( &$title, $name ) {
1184 if ( !is_object( $title ) ) {
1185 $title = Title::newFromText( $name );
1186 if ( !is_object( $title ) ) {
1187 $title = Title::newFromText( '--error: link target missing--' );
1193 * Build an array that represents the sidebar(s), the navigation bar among them.
1195 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1197 * The format of the returned array is array( heading => content, ... ), where:
1198 * - heading is the heading of a navigation portlet. It is either:
1199 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1200 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1201 * - plain text, which should be HTML-escaped by the skin
1202 * - content is the contents of the portlet. It is either:
1203 * - HTML text (<ul><li>...</li>...</ul>)
1204 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1205 * - (for a magic string as a key, any value)
1207 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1208 * and can technically insert anything in here; skin creators are expected to handle
1209 * values described above.
1211 * @return array
1213 function buildSidebar() {
1214 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1215 wfProfileIn( __METHOD__ );
1217 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1219 if ( $wgEnableSidebarCache ) {
1220 $cachedsidebar = $wgMemc->get( $key );
1221 if ( $cachedsidebar ) {
1222 wfProfileOut( __METHOD__ );
1223 return $cachedsidebar;
1227 $bar = array();
1228 $this->addToSidebar( $bar, 'sidebar' );
1230 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1231 if ( $wgEnableSidebarCache ) {
1232 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1235 wfProfileOut( __METHOD__ );
1236 return $bar;
1239 * Add content from a sidebar system message
1240 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1242 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1244 * @param $bar array
1245 * @param $message String
1247 function addToSidebar( &$bar, $message ) {
1248 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1252 * Add content from plain text
1253 * @since 1.17
1254 * @param $bar array
1255 * @param $text string
1256 * @return Array
1258 function addToSidebarPlain( &$bar, $text ) {
1259 $lines = explode( "\n", $text );
1261 $heading = '';
1263 foreach ( $lines as $line ) {
1264 if ( strpos( $line, '*' ) !== 0 ) {
1265 continue;
1267 $line = rtrim( $line, "\r" ); // for Windows compat
1269 if ( strpos( $line, '**' ) !== 0 ) {
1270 $heading = trim( $line, '* ' );
1271 if ( !array_key_exists( $heading, $bar ) ) {
1272 $bar[$heading] = array();
1274 } else {
1275 $line = trim( $line, '* ' );
1277 if ( strpos( $line, '|' ) !== false ) { // sanity check
1278 $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() );
1279 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1280 if ( count( $line ) !== 2 ) {
1281 // Second sanity check, could be hit by people doing
1282 // funky stuff with parserfuncs... (bug 33321)
1283 continue;
1286 $extraAttribs = array();
1288 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1289 if ( $msgLink->exists() ) {
1290 $link = $msgLink->text();
1291 if ( $link == '-' ) {
1292 continue;
1294 } else {
1295 $link = $line[0];
1297 $msgText = $this->msg( $line[1] );
1298 if ( $msgText->exists() ) {
1299 $text = $msgText->text();
1300 } else {
1301 $text = $line[1];
1304 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1305 $href = $link;
1307 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1308 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1309 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1310 $extraAttribs['rel'] = 'nofollow';
1313 global $wgExternalLinkTarget;
1314 if ( $wgExternalLinkTarget ) {
1315 $extraAttribs['target'] = $wgExternalLinkTarget;
1317 } else {
1318 $title = Title::newFromText( $link );
1320 if ( $title ) {
1321 $title = $title->fixSpecialName();
1322 $href = $title->getLinkURL();
1323 } else {
1324 $href = 'INVALID-TITLE';
1328 $bar[$heading][] = array_merge( array(
1329 'text' => $text,
1330 'href' => $href,
1331 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1332 'active' => false
1333 ), $extraAttribs );
1334 } else {
1335 continue;
1340 return $bar;
1344 * Should we load mediawiki.legacy.wikiprintable? Skins that have their own
1345 * print stylesheet should override this and return false. (This is an
1346 * ugly hack to get Monobook to play nicely with OutputPage::headElement().)
1348 * @return bool
1350 public function commonPrintStylesheet() {
1351 return true;
1355 * Gets new talk page messages for the current user and returns an
1356 * appropriate alert message (or an empty string if there are no messages)
1357 * @return String
1359 function getNewtalks() {
1361 $newMessagesAlert = '';
1362 $user = $this->getUser();
1363 $newtalks = $user->getNewMessageLinks();
1364 $out = $this->getOutput();
1366 // Allow extensions to disable or modify the new messages alert
1367 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1368 return '';
1370 if ( $newMessagesAlert ) {
1371 return $newMessagesAlert;
1374 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1375 $uTalkTitle = $user->getTalkPage();
1377 if ( !$uTalkTitle->equals( $out->getTitle() ) ) {
1378 $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null;
1379 $nofAuthors = 0;
1380 if ( $lastSeenRev !== null ) {
1381 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1382 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1383 if ( $latestRev !== null ) {
1384 // Singular if only 1 unseen revision, plural if several unseen revisions.
1385 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1386 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1387 $lastSeenRev, $latestRev, 10, 'include_new' );
1389 } else {
1390 // Singular if no revision -> diff link will show latest change only in any case
1391 $plural = false;
1393 $plural = $plural ? 2 : 1;
1394 // 2 signifies "more than one revision". We don't know how many, and even if we did,
1395 // the number of revisions or authors is not necessarily the same as the number of
1396 // "messages".
1397 $newMessagesLink = Linker::linkKnown(
1398 $uTalkTitle,
1399 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1400 array(),
1401 array( 'redirect' => 'no' )
1404 $newMessagesDiffLink = Linker::linkKnown(
1405 $uTalkTitle,
1406 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1407 array(),
1408 $lastSeenRev !== null
1409 ? array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1410 : array( 'diff' => 'cur' )
1413 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1414 $newMessagesAlert = $this->msg(
1415 'youhavenewmessagesfromusers',
1416 $newMessagesLink,
1417 $newMessagesDiffLink
1418 )->numParams( $nofAuthors );
1419 } else {
1420 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1421 $newMessagesAlert = $this->msg(
1422 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1423 $newMessagesLink,
1424 $newMessagesDiffLink
1427 $newMessagesAlert = $newMessagesAlert->text();
1428 # Disable Squid cache
1429 $out->setSquidMaxage( 0 );
1431 } elseif ( count( $newtalks ) ) {
1432 $sep = $this->msg( 'newtalkseparator' )->escaped();
1433 $msgs = array();
1435 foreach ( $newtalks as $newtalk ) {
1436 $msgs[] = Xml::element(
1437 'a',
1438 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1441 $parts = implode( $sep, $msgs );
1442 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1443 $out->setSquidMaxage( 0 );
1446 return $newMessagesAlert;
1450 * Get a cached notice
1452 * @param string $name message name, or 'default' for $wgSiteNotice
1453 * @return String: HTML fragment
1455 private function getCachedNotice( $name ) {
1456 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1458 wfProfileIn( __METHOD__ );
1460 $needParse = false;
1462 if ( $name === 'default' ) {
1463 // special case
1464 global $wgSiteNotice;
1465 $notice = $wgSiteNotice;
1466 if ( empty( $notice ) ) {
1467 wfProfileOut( __METHOD__ );
1468 return false;
1470 } else {
1471 $msg = $this->msg( $name )->inContentLanguage();
1472 if ( $msg->isDisabled() ) {
1473 wfProfileOut( __METHOD__ );
1474 return false;
1476 $notice = $msg->plain();
1479 // Use the extra hash appender to let eg SSL variants separately cache.
1480 $key = wfMemcKey( $name . $wgRenderHashAppend );
1481 $cachedNotice = $parserMemc->get( $key );
1482 if ( is_array( $cachedNotice ) ) {
1483 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1484 $notice = $cachedNotice['html'];
1485 } else {
1486 $needParse = true;
1488 } else {
1489 $needParse = true;
1492 if ( $needParse ) {
1493 $parsed = $this->getOutput()->parse( $notice );
1494 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1495 $notice = $parsed;
1498 $notice = Html::rawElement( 'div', array( 'id' => 'localNotice',
1499 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1500 wfProfileOut( __METHOD__ );
1501 return $notice;
1505 * Get a notice based on page's namespace
1507 * @return String: HTML fragment
1509 function getNamespaceNotice() {
1510 wfProfileIn( __METHOD__ );
1512 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1513 $namespaceNotice = $this->getCachedNotice( $key );
1514 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
1515 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1516 } else {
1517 $namespaceNotice = '';
1520 wfProfileOut( __METHOD__ );
1521 return $namespaceNotice;
1525 * Get the site notice
1527 * @return String: HTML fragment
1529 function getSiteNotice() {
1530 wfProfileIn( __METHOD__ );
1531 $siteNotice = '';
1533 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1534 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1535 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1536 } else {
1537 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1538 if ( !$anonNotice ) {
1539 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1540 } else {
1541 $siteNotice = $anonNotice;
1544 if ( !$siteNotice ) {
1545 $siteNotice = $this->getCachedNotice( 'default' );
1549 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1550 wfProfileOut( __METHOD__ );
1551 return $siteNotice;
1555 * Create a section edit link. This supersedes editSectionLink() and
1556 * editSectionLinkForOther().
1558 * @param $nt Title The title being linked to (may not be the same as
1559 * $wgTitle, if the section is included from a template)
1560 * @param string $section The designation of the section being pointed to,
1561 * to be included in the link, like "&section=$section"
1562 * @param string $tooltip The tooltip to use for the link: will be escaped
1563 * and wrapped in the 'editsectionhint' message
1564 * @param $lang string Language code
1565 * @return string HTML to use for edit link
1567 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1568 // HTML generated here should probably have userlangattributes
1569 // added to it for LTR text on RTL pages
1571 $lang = wfGetLangObj( $lang );
1573 $attribs = array();
1574 if ( !is_null( $tooltip ) ) {
1575 # Bug 25462: undo double-escaping.
1576 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1577 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1578 ->inLanguage( $lang )->text();
1580 $link = Linker::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1581 $attribs,
1582 array( 'action' => 'edit', 'section' => $section ),
1583 array( 'noclasses', 'known' )
1586 # Add the brackets and the span and run the hook.
1587 $result = '<span class="mw-editsection">'
1588 . '<span class="mw-editsection-bracket">[</span>'
1589 . $link
1590 . '<span class="mw-editsection-bracket">]</span>'
1591 . '</span>';
1593 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1594 return $result;
1598 * Use PHP's magic __call handler to intercept legacy calls to the linker
1599 * for backwards compatibility.
1601 * @param string $fname Name of called method
1602 * @param array $args Arguments to the method
1603 * @throws MWException
1604 * @return mixed
1606 function __call( $fname, $args ) {
1607 $realFunction = array( 'Linker', $fname );
1608 if ( is_callable( $realFunction ) ) {
1609 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1610 return call_user_func_array( $realFunction, $args );
1611 } else {
1612 $className = get_class( $this );
1613 throw new MWException( "Call to undefined method $className::$fname" );