Add support for Number grouping(commafy) based on CLDR number grouping patterns like...
[lhc/web/wiklou.git] / includes / Skin.php
1 <?php
2 /**
3 * @defgroup Skins Skins
4 */
5
6 if ( !defined( 'MEDIAWIKI' ) ) {
7 die( 1 );
8 }
9
10 /**
11 * The main skin class that provide methods and properties for all other skins.
12 * This base class is also the "Standard" skin.
13 *
14 * See docs/skin.txt for more information.
15 *
16 * @ingroup Skins
17 */
18 abstract class Skin extends ContextSource {
19 protected $skinname = 'standard';
20 protected $mRelevantTitle = null;
21 protected $mRelevantUser = null;
22
23 /**
24 * Fetch the set of available skins.
25 * @return array of strings
26 */
27 static function getSkinNames() {
28 global $wgValidSkinNames;
29 static $skinsInitialised = false;
30
31 if ( !$skinsInitialised || !count( $wgValidSkinNames ) ) {
32 # Get a list of available skins
33 # Build using the regular expression '^(.*).php$'
34 # Array keys are all lower case, array value keep the case used by filename
35 #
36 wfProfileIn( __METHOD__ . '-init' );
37
38 global $wgStyleDirectory;
39
40 $skinDir = dir( $wgStyleDirectory );
41
42 # while code from www.php.net
43 while ( false !== ( $file = $skinDir->read() ) ) {
44 // Skip non-PHP files, hidden files, and '.dep' includes
45 $matches = array();
46
47 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
48 $aSkin = $matches[1];
49 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
50 }
51 }
52 $skinDir->close();
53 $skinsInitialised = true;
54 wfProfileOut( __METHOD__ . '-init' );
55 }
56 return $wgValidSkinNames;
57 }
58
59 /**
60 * Fetch the list of usable skins in regards to $wgSkipSkins.
61 * Useful for Special:Preferences and other places where you
62 * only want to show skins users _can_ use.
63 * @return array of strings
64 */
65 public static function getUsableSkins() {
66 global $wgSkipSkins;
67
68 $usableSkins = self::getSkinNames();
69
70 foreach ( $wgSkipSkins as $skip ) {
71 unset( $usableSkins[$skip] );
72 }
73
74 return $usableSkins;
75 }
76
77 /**
78 * Normalize a skin preference value to a form that can be loaded.
79 * If a skin can't be found, it will fall back to the configured
80 * default (or the old 'Classic' skin if that's broken).
81 * @param $key String: 'monobook', 'standard', etc.
82 * @return string
83 */
84 static function normalizeKey( $key ) {
85 global $wgDefaultSkin;
86
87 $skinNames = Skin::getSkinNames();
88
89 if ( $key == '' ) {
90 // Don't return the default immediately;
91 // in a misconfiguration we need to fall back.
92 $key = $wgDefaultSkin;
93 }
94
95 if ( isset( $skinNames[$key] ) ) {
96 return $key;
97 }
98
99 // Older versions of the software used a numeric setting
100 // in the user preferences.
101 $fallback = array(
102 0 => $wgDefaultSkin,
103 1 => 'nostalgia',
104 2 => 'cologneblue'
105 );
106
107 if ( isset( $fallback[$key] ) ) {
108 $key = $fallback[$key];
109 }
110
111 if ( isset( $skinNames[$key] ) ) {
112 return $key;
113 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
114 return $wgDefaultSkin;
115 } else {
116 return 'vector';
117 }
118 }
119
120 /**
121 * Factory method for loading a skin of a given type
122 * @param $key String: 'monobook', 'standard', etc.
123 * @return Skin
124 */
125 static function &newFromKey( $key ) {
126 global $wgStyleDirectory;
127
128 $key = Skin::normalizeKey( $key );
129
130 $skinNames = Skin::getSkinNames();
131 $skinName = $skinNames[$key];
132 $className = "Skin{$skinName}";
133
134 # Grab the skin class and initialise it.
135 if ( !MWInit::classExists( $className ) ) {
136
137 if ( !defined( 'MW_COMPILED' ) ) {
138 // Preload base classes to work around APC/PHP5 bug
139 $deps = "{$wgStyleDirectory}/{$skinName}.deps.php";
140 if ( file_exists( $deps ) ) {
141 include_once( $deps );
142 }
143 require_once( "{$wgStyleDirectory}/{$skinName}.php" );
144 }
145
146 # Check if we got if not failback to default skin
147 if ( !MWInit::classExists( $className ) ) {
148 # DO NOT die if the class isn't found. This breaks maintenance
149 # scripts and can cause a user account to be unrecoverable
150 # except by SQL manipulation if a previously valid skin name
151 # is no longer valid.
152 wfDebug( "Skin class does not exist: $className\n" );
153 $className = 'SkinVector';
154 if ( !defined( 'MW_COMPILED' ) ) {
155 require_once( "{$wgStyleDirectory}/Vector.php" );
156 }
157 }
158 }
159 $skin = new $className( $key );
160 return $skin;
161 }
162
163 /** @return string skin name */
164 public function getSkinName() {
165 return $this->skinname;
166 }
167
168 function initPage( OutputPage $out ) {
169 wfProfileIn( __METHOD__ );
170
171 $this->preloadExistence();
172
173 wfProfileOut( __METHOD__ );
174 }
175
176 /**
177 * Preload the existence of three commonly-requested pages in a single query
178 */
179 function preloadExistence() {
180 $user = $this->getUser();
181
182 // User/talk link
183 $titles = array( $user->getUserPage(), $user->getTalkPage() );
184
185 // Other tab link
186 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
187 // nothing
188 } elseif ( $this->getTitle()->isTalkPage() ) {
189 $titles[] = $this->getTitle()->getSubjectPage();
190 } else {
191 $titles[] = $this->getTitle()->getTalkPage();
192 }
193
194 $lb = new LinkBatch( $titles );
195 $lb->setCaller( __METHOD__ );
196 $lb->execute();
197 }
198
199 /**
200 * Get the current revision ID
201 *
202 * @return Integer
203 */
204 public function getRevisionId() {
205 return $this->getOutput()->getRevisionId();
206 }
207
208 /**
209 * Whether the revision displayed is the latest revision of the page
210 *
211 * @return Boolean
212 */
213 public function isRevisionCurrent() {
214 $revID = $this->getRevisionId();
215 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
216 }
217
218 /**
219 * Set the "relevant" title
220 * @see self::getRelevantTitle()
221 * @param $t Title object to use
222 */
223 public function setRelevantTitle( $t ) {
224 $this->mRelevantTitle = $t;
225 }
226
227 /**
228 * Return the "relevant" title.
229 * A "relevant" title is not necessarily the actual title of the page.
230 * Special pages like Special:MovePage use set the page they are acting on
231 * as their "relevant" title, this allows the skin system to display things
232 * such as content tabs which belong to to that page instead of displaying
233 * a basic special page tab which has almost no meaning.
234 *
235 * @return Title
236 */
237 public function getRelevantTitle() {
238 if ( isset($this->mRelevantTitle) ) {
239 return $this->mRelevantTitle;
240 }
241 return $this->getTitle();
242 }
243
244 /**
245 * Set the "relevant" user
246 * @see self::getRelevantUser()
247 * @param $u User object to use
248 */
249 public function setRelevantUser( $u ) {
250 $this->mRelevantUser = $u;
251 }
252
253 /**
254 * Return the "relevant" user.
255 * A "relevant" user is similar to a relevant title. Special pages like
256 * Special:Contributions mark the user which they are relevant to so that
257 * things like the toolbox can display the information they usually are only
258 * able to display on a user's userpage and talkpage.
259 * @return User
260 */
261 public function getRelevantUser() {
262 if ( isset($this->mRelevantUser) ) {
263 return $this->mRelevantUser;
264 }
265 $title = $this->getRelevantTitle();
266 if( $title->getNamespace() == NS_USER || $title->getNamespace() == NS_USER_TALK ) {
267 $rootUser = strtok( $title->getText(), '/' );
268 if ( User::isIP( $rootUser ) ) {
269 $this->mRelevantUser = User::newFromName( $rootUser, false );
270 } else {
271 $user = User::newFromName( $rootUser );
272 if ( $user->isLoggedIn() ) {
273 $this->mRelevantUser = $user;
274 }
275 }
276 return $this->mRelevantUser;
277 }
278 return null;
279 }
280
281 /**
282 * Outputs the HTML generated by other functions.
283 * @param $out OutputPage
284 */
285 abstract function outputPage( OutputPage $out = null );
286
287 static function makeVariablesScript( $data ) {
288 if ( $data ) {
289 return Html::inlineScript(
290 ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) )
291 );
292 } else {
293 return '';
294 }
295 }
296
297 /**
298 * Generated JavaScript action=raw&gen=js
299 * This used to load MediaWiki:Common.js and the skin-specific style
300 * before the ResourceLoader.
301 *
302 * @deprecated since 1.18 Use the ResourceLoader instead. This may be removed at some
303 * point.
304 * @param $skinName String: If set, overrides the skin name
305 * @return String
306 */
307 public function generateUserJs( $skinName = null ) {
308 return '';
309 }
310
311 /**
312 * Generate user stylesheet for action=raw&gen=css
313 *
314 * @deprecated since 1.18 Use the ResourceLoader instead. This may be removed at some
315 * point.
316 * @return String
317 */
318 public function generateUserStylesheet() {
319 return '';
320 }
321
322 /**
323 * Get the query to generate a dynamic stylesheet
324 *
325 * @return array
326 */
327 public static function getDynamicStylesheetQuery() {
328 global $wgSquidMaxage;
329
330 return array(
331 'action' => 'raw',
332 'maxage' => $wgSquidMaxage,
333 'usemsgcache' => 'yes',
334 'ctype' => 'text/css',
335 'smaxage' => $wgSquidMaxage,
336 );
337 }
338
339 /**
340 * Add skin specific stylesheets
341 * Calling this method with an $out of anything but the same OutputPage
342 * inside ->getOutput() is deprecated. The $out arg is kept
343 * for compatibility purposes with skins.
344 * @param $out OutputPage
345 * @delete
346 */
347 abstract function setupSkinUserCss( OutputPage $out );
348
349 /**
350 * TODO: document
351 * @param $title Title
352 * @return String
353 */
354 function getPageClasses( $title ) {
355 $numeric = 'ns-' . $title->getNamespace();
356
357 if ( $title->getNamespace() == NS_SPECIAL ) {
358 $type = 'ns-special';
359 // bug 23315: provide a class based on the canonical special page name without subpages
360 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
361 if ( $canonicalName ) {
362 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
363 } else {
364 $type .= ' mw-invalidspecialpage';
365 }
366 } elseif ( $title->isTalkPage() ) {
367 $type = 'ns-talk';
368 } else {
369 $type = 'ns-subject';
370 }
371
372 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
373
374 return "$numeric $type $name";
375 }
376
377 /**
378 * This will be called by OutputPage::headElement when it is creating the
379 * <body> tag, skins can override it if they have a need to add in any
380 * body attributes or classes of their own.
381 * @param $out OutputPage
382 * @param $bodyAttrs Array
383 */
384 function addToBodyAttributes( $out, &$bodyAttrs ) {
385 // does nothing by default
386 }
387
388 /**
389 * URL to the logo
390 * @return String
391 */
392 function getLogo() {
393 global $wgLogo;
394 return $wgLogo;
395 }
396
397 function getCategoryLinks() {
398 global $wgUseCategoryBrowser;
399
400 $out = $this->getOutput();
401 $allCats = $out->getCategoryLinks();
402
403 if ( !count( $allCats ) ) {
404 return '';
405 }
406
407 $embed = "<li>";
408 $pop = "</li>";
409
410 $s = '';
411 $colon = wfMsgExt( 'colon-separator', 'escapenoentities' );
412
413 if ( !empty( $allCats['normal'] ) ) {
414 $t = $embed . implode( "{$pop}{$embed}" , $allCats['normal'] ) . $pop;
415
416 $msg = wfMsgExt( 'pagecategories', array( 'parsemag', 'escapenoentities' ), count( $allCats['normal'] ) );
417 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
418 Linker::link( Title::newFromText( wfMsgForContent( 'pagecategorieslink' ) ), $msg )
419 . $colon . '<ul>' . $t . '</ul>' . '</div>';
420 }
421
422 # Hidden categories
423 if ( isset( $allCats['hidden'] ) ) {
424 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
425 $class = ' mw-hidden-cats-user-shown';
426 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
427 $class = ' mw-hidden-cats-ns-shown';
428 } else {
429 $class = ' mw-hidden-cats-hidden';
430 }
431
432 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
433 wfMsgExt( 'hidden-categories', array( 'parsemag', 'escapenoentities' ), count( $allCats['hidden'] ) ) .
434 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}" , $allCats['hidden'] ) . $pop . '</ul>' .
435 '</div>';
436 }
437
438 # optional 'dmoz-like' category browser. Will be shown under the list
439 # of categories an article belong to
440 if ( $wgUseCategoryBrowser ) {
441 $s .= '<br /><hr />';
442
443 # get a big array of the parents tree
444 $parenttree = $this->getTitle()->getParentCategoryTree();
445 # Skin object passed by reference cause it can not be
446 # accessed under the method subfunction drawCategoryBrowser
447 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
448 # Clean out bogus first entry and sort them
449 unset( $tempout[0] );
450 asort( $tempout );
451 # Output one per line
452 $s .= implode( "<br />\n", $tempout );
453 }
454
455 return $s;
456 }
457
458 /**
459 * Render the array as a serie of links.
460 * @param $tree Array: categories tree returned by Title::getParentCategoryTree
461 * @return String separated by &gt;, terminate with "\n"
462 */
463 function drawCategoryBrowser( $tree ) {
464 $return = '';
465
466 foreach ( $tree as $element => $parent ) {
467 if ( empty( $parent ) ) {
468 # element start a new list
469 $return .= "\n";
470 } else {
471 # grab the others elements
472 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
473 }
474
475 # add our current element to the list
476 $eltitle = Title::newFromText( $element );
477 $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
478 }
479
480 return $return;
481 }
482
483 function getCategories() {
484 $out = $this->getOutput();
485
486 $catlinks = $this->getCategoryLinks();
487
488 $classes = 'catlinks';
489
490 // Check what we're showing
491 $allCats = $out->getCategoryLinks();
492 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
493 $this->getTitle()->getNamespace() == NS_CATEGORY;
494
495 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
496 $classes .= ' catlinks-allhidden';
497 }
498
499 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
500 }
501
502 /**
503 * This runs a hook to allow extensions placing their stuff after content
504 * and article metadata (e.g. categories).
505 * Note: This function has nothing to do with afterContent().
506 *
507 * This hook is placed here in order to allow using the same hook for all
508 * skins, both the SkinTemplate based ones and the older ones, which directly
509 * use this class to get their data.
510 *
511 * The output of this function gets processed in SkinTemplate::outputPage() for
512 * the SkinTemplate based skins, all other skins should directly echo it.
513 *
514 * @return String, empty by default, if not changed by any hook function.
515 */
516 protected function afterContentHook() {
517 $data = '';
518
519 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
520 // adding just some spaces shouldn't toggle the output
521 // of the whole <div/>, so we use trim() here
522 if ( trim( $data ) != '' ) {
523 // Doing this here instead of in the skins to
524 // ensure that the div has the same ID in all
525 // skins
526 $data = "<div id='mw-data-after-content'>\n" .
527 "\t$data\n" .
528 "</div>\n";
529 }
530 } else {
531 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
532 }
533
534 return $data;
535 }
536
537 /**
538 * Generate debug data HTML for displaying at the bottom of the main content
539 * area.
540 * @return String HTML containing debug data, if enabled (otherwise empty).
541 */
542 protected function generateDebugHTML() {
543 global $wgShowDebug;
544
545 if ( $wgShowDebug ) {
546 $listInternals = $this->formatDebugHTML( $this->getOutput()->mDebugtext );
547 return "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">" .
548 $listInternals . "</ul>\n";
549 }
550
551 return '';
552 }
553
554 private function formatDebugHTML( $debugText ) {
555 global $wgDebugTimestamps;
556
557 $lines = explode( "\n", $debugText );
558 $curIdent = 0;
559 $ret = '<li>';
560
561 foreach ( $lines as $line ) {
562 $pre = '';
563 if ( $wgDebugTimestamps ) {
564 $matches = array();
565 if ( preg_match( '/^(\d+\.\d+\s{2})/', $line, $matches ) ) {
566 $pre = $matches[1];
567 $line = substr( $line, strlen( $pre ) );
568 }
569 }
570 $display = ltrim( $line );
571 $ident = strlen( $line ) - strlen( $display );
572 $diff = $ident - $curIdent;
573
574 $display = $pre . $display;
575 if ( $display == '' ) {
576 $display = "\xc2\xa0";
577 }
578
579 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
580 $ident = $curIdent;
581 $diff = 0;
582 $display = '<span style="background:yellow;">' . htmlspecialchars( $display ) . '</span>';
583 } else {
584 $display = htmlspecialchars( $display );
585 }
586
587 if ( $diff < 0 ) {
588 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
589 } elseif ( $diff == 0 ) {
590 $ret .= "</li><li>\n";
591 } else {
592 $ret .= str_repeat( "<ul><li>\n", $diff );
593 }
594 $ret .= "<tt>$display</tt>\n";
595
596 $curIdent = $ident;
597 }
598
599 $ret .= str_repeat( '</li></ul>', $curIdent ) . '</li>';
600
601 return $ret;
602 }
603
604 /**
605 * This gets called shortly before the </body> tag.
606 *
607 * @return String HTML-wrapped JS code to be put before </body>
608 */
609 function bottomScripts() {
610 // TODO and the suckage continues. This function is really just a wrapper around
611 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
612 // up at some point
613 $bottomScriptText = $this->getOutput()->getBottomScripts();
614 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
615
616 return $bottomScriptText;
617 }
618
619 /**
620 * Text with the permalink to the source page,
621 * usually shown on the footer of a printed page
622 *
623 * @return string HTML text with an URL
624 */
625 function printSource() {
626 $oldid = $this->getRevisionId();
627 if ( $oldid ) {
628 $url = htmlspecialchars( $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid ) );
629 } else {
630 // oldid not available for non existing pages
631 $url = htmlspecialchars( $this->getTitle()->getCanonicalURL() );
632 }
633 return wfMsg( 'retrievedfrom', '<a href="' . $url . '">' . $url . '</a>' );
634 }
635
636 function getUndeleteLink() {
637 $action = $this->getRequest()->getVal( 'action', 'view' );
638
639 if ( $this->getUser()->isAllowed( 'deletedhistory' ) && !$this->getUser()->isBlocked() &&
640 ( $this->getTitle()->getArticleId() == 0 || $action == 'history' ) ) {
641 $n = $this->getTitle()->isDeleted();
642
643
644 if ( $n ) {
645 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
646 $msg = 'thisisdeleted';
647 } else {
648 $msg = 'viewdeleted';
649 }
650
651 return wfMsg(
652 $msg,
653 Linker::linkKnown(
654 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
655 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $this->getLang()->formatNum( $n ) )
656 )
657 );
658 }
659 }
660
661 return '';
662 }
663
664 function subPageSubtitle() {
665 $out = $this->getOutput();
666 $subpages = '';
667
668 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
669 return $subpages;
670 }
671
672 if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) {
673 $ptext = $this->getTitle()->getPrefixedText();
674 if ( preg_match( '/\//', $ptext ) ) {
675 $links = explode( '/', $ptext );
676 array_pop( $links );
677 $c = 0;
678 $growinglink = '';
679 $display = '';
680
681 foreach ( $links as $link ) {
682 $growinglink .= $link;
683 $display .= $link;
684 $linkObj = Title::newFromText( $growinglink );
685
686 if ( is_object( $linkObj ) && $linkObj->exists() ) {
687 $getlink = Linker::linkKnown(
688 $linkObj,
689 htmlspecialchars( $display )
690 );
691
692 $c++;
693
694 if ( $c > 1 ) {
695 $subpages .= wfMsgExt( 'pipe-separator', 'escapenoentities' );
696 } else {
697 $subpages .= '&lt; ';
698 }
699
700 $subpages .= $getlink;
701 $display = '';
702 } else {
703 $display .= '/';
704 }
705 $growinglink .= '/';
706 }
707 }
708 }
709
710 return $subpages;
711 }
712
713 /**
714 * Returns true if the IP should be shown in the header
715 * @return Bool
716 */
717 function showIPinHeader() {
718 global $wgShowIPinHeader;
719 return $wgShowIPinHeader && session_id() != '';
720 }
721
722 function getSearchLink() {
723 $searchPage = SpecialPage::getTitleFor( 'Search' );
724 return $searchPage->getLocalURL();
725 }
726
727 function escapeSearchLink() {
728 return htmlspecialchars( $this->getSearchLink() );
729 }
730
731 function getCopyright( $type = 'detect' ) {
732 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
733
734 if ( $type == 'detect' ) {
735 if ( !$this->isRevisionCurrent() && wfMsgForContent( 'history_copyright' ) !== '-' ) {
736 $type = 'history';
737 } else {
738 $type = 'normal';
739 }
740 }
741
742 if ( $type == 'history' ) {
743 $msg = 'history_copyright';
744 } else {
745 $msg = 'copyright';
746 }
747
748 if ( $wgRightsPage ) {
749 $title = Title::newFromText( $wgRightsPage );
750 $link = Linker::linkKnown( $title, $wgRightsText );
751 } elseif ( $wgRightsUrl ) {
752 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
753 } elseif ( $wgRightsText ) {
754 $link = $wgRightsText;
755 } else {
756 # Give up now
757 return '';
758 }
759
760 // Allow for site and per-namespace customization of copyright notice.
761 $forContent = true;
762
763 wfRunHooks( 'SkinCopyrightFooter', array( $this->getTitle(), $type, &$msg, &$link, &$forContent ) );
764
765 if ( $forContent ) {
766 $msg = wfMsgForContent( $msg, $link );
767 if ( $this->getLang()->getCode() !== $wgContLang->getCode() ) {
768 $msg = Html::rawElement( 'span', array( 'lang' => $wgContLang->getCode(), 'dir' => $wgContLang->getDir() ), $msg );
769 }
770 return $msg;
771 } else {
772 return wfMsg( $msg, $link );
773 }
774 }
775
776 function getCopyrightIcon() {
777 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
778
779 $out = '';
780
781 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
782 $out = $wgCopyrightIcon;
783 } elseif ( $wgRightsIcon ) {
784 $icon = htmlspecialchars( $wgRightsIcon );
785
786 if ( $wgRightsUrl ) {
787 $url = htmlspecialchars( $wgRightsUrl );
788 $out .= '<a href="' . $url . '">';
789 }
790
791 $text = htmlspecialchars( $wgRightsText );
792 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
793
794 if ( $wgRightsUrl ) {
795 $out .= '</a>';
796 }
797 }
798
799 return $out;
800 }
801
802 /**
803 * Gets the powered by MediaWiki icon.
804 * @return string
805 */
806 function getPoweredBy() {
807 global $wgStylePath;
808
809 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
810 $text = '<a href="http://www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
811 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
812 return $text;
813 }
814
815 /**
816 * Get the timestamp of the latest revision, formatted in user language
817 *
818 * @param $article Article object. Used if we're working with the current revision
819 * @return String
820 */
821 protected function lastModified( $article ) {
822 if ( !$this->isRevisionCurrent() ) {
823 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
824 } else {
825 $timestamp = $article->getTimestamp();
826 }
827
828 if ( $timestamp ) {
829 $d = $this->getLang()->date( $timestamp, true );
830 $t = $this->getLang()->time( $timestamp, true );
831 $s = ' ' . wfMsg( 'lastmodifiedat', $d, $t );
832 } else {
833 $s = '';
834 }
835
836 if ( wfGetLB()->getLaggedSlaveMode() ) {
837 $s .= ' <strong>' . wfMsg( 'laggedslavemode' ) . '</strong>';
838 }
839
840 return $s;
841 }
842
843 function logoText( $align = '' ) {
844 if ( $align != '' ) {
845 $a = " align='{$align}'";
846 } else {
847 $a = '';
848 }
849
850 $mp = wfMsgHtml( 'mainpage' );
851 $mptitle = Title::newMainPage();
852 $url = ( is_object( $mptitle ) ? $mptitle->escapeLocalURL() : '' );
853
854 $logourl = $this->getLogo();
855 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
856
857 return $s;
858 }
859
860 /**
861 * Renders a $wgFooterIcons icon acording to the method's arguments
862 * @param $icon Array: The icon to build the html for, see $wgFooterIcons for the format of this array
863 * @param $withImage Bool|String: Whether to use the icon's image or output a text-only footericon
864 * @return String HTML
865 */
866 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
867 if ( is_string( $icon ) ) {
868 $html = $icon;
869 } else { // Assuming array
870 $url = isset($icon["url"]) ? $icon["url"] : null;
871 unset( $icon["url"] );
872 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
873 $html = Html::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
874 } else {
875 $html = htmlspecialchars( $icon["alt"] );
876 }
877 if ( $url ) {
878 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
879 }
880 }
881 return $html;
882 }
883
884 /**
885 * Gets the link to the wiki's main page.
886 * @return string
887 */
888 function mainPageLink() {
889 $s = Linker::linkKnown(
890 Title::newMainPage(),
891 wfMsgHtml( 'mainpage' )
892 );
893
894 return $s;
895 }
896
897 public function footerLink( $desc, $page ) {
898 // if the link description has been set to "-" in the default language,
899 if ( wfMsgForContent( $desc ) == '-' ) {
900 // then it is disabled, for all languages.
901 return '';
902 } else {
903 // Otherwise, we display the link for the user, described in their
904 // language (which may or may not be the same as the default language),
905 // but we make the link target be the one site-wide page.
906 $title = Title::newFromText( wfMsgForContent( $page ) );
907
908 return Linker::linkKnown(
909 $title,
910 wfMsgExt( $desc, array( 'parsemag', 'escapenoentities' ) )
911 );
912 }
913 }
914
915 /**
916 * Gets the link to the wiki's privacy policy page.
917 * @return String HTML
918 */
919 function privacyLink() {
920 return $this->footerLink( 'privacy', 'privacypage' );
921 }
922
923 /**
924 * Gets the link to the wiki's about page.
925 * @return String HTML
926 */
927 function aboutLink() {
928 return $this->footerLink( 'aboutsite', 'aboutpage' );
929 }
930
931 /**
932 * Gets the link to the wiki's general disclaimers page.
933 * @return String HTML
934 */
935 function disclaimerLink() {
936 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
937 }
938
939 /**
940 * Return URL options for the 'edit page' link.
941 * This may include an 'oldid' specifier, if the current page view is such.
942 *
943 * @return array
944 * @private
945 */
946 function editUrlOptions() {
947 $options = array( 'action' => 'edit' );
948
949 if ( !$this->isRevisionCurrent() ) {
950 $options['oldid'] = intval( $this->getRevisionId() );
951 }
952
953 return $options;
954 }
955
956 function showEmailUser( $id ) {
957 $targetUser = User::newFromId( $id );
958 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
959 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
960 }
961
962 /**
963 * Return a fully resolved style path url to images or styles stored in the common folder.
964 * This method returns a url resolved using the configured skin style path
965 * and includes the style version inside of the url.
966 * @param $name String: The name or path of a skin resource file
967 * @return String The fully resolved style path url including styleversion
968 */
969 function getCommonStylePath( $name ) {
970 global $wgStylePath, $wgStyleVersion;
971 return "$wgStylePath/common/$name?$wgStyleVersion";
972 }
973
974 /**
975 * Return a fully resolved style path url to images or styles stored in the curent skins's folder.
976 * This method returns a url resolved using the configured skin style path
977 * and includes the style version inside of the url.
978 * @param $name String: The name or path of a skin resource file
979 * @return String The fully resolved style path url including styleversion
980 */
981 function getSkinStylePath( $name ) {
982 global $wgStylePath, $wgStyleVersion;
983 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
984 }
985
986 /* these are used extensively in SkinTemplate, but also some other places */
987 static function makeMainPageUrl( $urlaction = '' ) {
988 $title = Title::newMainPage();
989 self::checkTitle( $title, '' );
990
991 return $title->getLocalURL( $urlaction );
992 }
993
994 static function makeSpecialUrl( $name, $urlaction = '' ) {
995 $title = SpecialPage::getSafeTitleFor( $name );
996 return $title->getLocalURL( $urlaction );
997 }
998
999 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1000 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1001 return $title->getLocalURL( $urlaction );
1002 }
1003
1004 static function makeI18nUrl( $name, $urlaction = '' ) {
1005 $title = Title::newFromText( wfMsgForContent( $name ) );
1006 self::checkTitle( $title, $name );
1007 return $title->getLocalURL( $urlaction );
1008 }
1009
1010 static function makeUrl( $name, $urlaction = '' ) {
1011 $title = Title::newFromText( $name );
1012 self::checkTitle( $title, $name );
1013
1014 return $title->getLocalURL( $urlaction );
1015 }
1016
1017 /**
1018 * If url string starts with http, consider as external URL, else
1019 * internal
1020 * @param $name String
1021 * @return String URL
1022 */
1023 static function makeInternalOrExternalUrl( $name ) {
1024 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $name ) ) {
1025 return $name;
1026 } else {
1027 return self::makeUrl( $name );
1028 }
1029 }
1030
1031 # this can be passed the NS number as defined in Language.php
1032 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1033 $title = Title::makeTitleSafe( $namespace, $name );
1034 self::checkTitle( $title, $name );
1035
1036 return $title->getLocalURL( $urlaction );
1037 }
1038
1039 /* these return an array with the 'href' and boolean 'exists' */
1040 static function makeUrlDetails( $name, $urlaction = '' ) {
1041 $title = Title::newFromText( $name );
1042 self::checkTitle( $title, $name );
1043
1044 return array(
1045 'href' => $title->getLocalURL( $urlaction ),
1046 'exists' => $title->getArticleID() != 0,
1047 );
1048 }
1049
1050 /**
1051 * Make URL details where the article exists (or at least it's convenient to think so)
1052 * @param $name String Article name
1053 * @param $urlaction String
1054 * @return Array
1055 */
1056 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1057 $title = Title::newFromText( $name );
1058 self::checkTitle( $title, $name );
1059
1060 return array(
1061 'href' => $title->getLocalURL( $urlaction ),
1062 'exists' => true
1063 );
1064 }
1065
1066 # make sure we have some title to operate on
1067 static function checkTitle( &$title, $name ) {
1068 if ( !is_object( $title ) ) {
1069 $title = Title::newFromText( $name );
1070 if ( !is_object( $title ) ) {
1071 $title = Title::newFromText( '--error: link target missing--' );
1072 }
1073 }
1074 }
1075
1076 /**
1077 * Build an array that represents the sidebar(s), the navigation bar among them
1078 *
1079 * @return array
1080 */
1081 function buildSidebar() {
1082 global $parserMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1083 wfProfileIn( __METHOD__ );
1084
1085 $key = wfMemcKey( 'sidebar', $this->getLang()->getCode() );
1086
1087 if ( $wgEnableSidebarCache ) {
1088 $cachedsidebar = $parserMemc->get( $key );
1089 if ( $cachedsidebar ) {
1090 wfProfileOut( __METHOD__ );
1091 return $cachedsidebar;
1092 }
1093 }
1094
1095 $bar = array();
1096 $this->addToSidebar( $bar, 'sidebar' );
1097
1098 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1099 if ( $wgEnableSidebarCache ) {
1100 $parserMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1101 }
1102
1103 wfProfileOut( __METHOD__ );
1104 return $bar;
1105 }
1106 /**
1107 * Add content from a sidebar system message
1108 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1109 *
1110 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1111 *
1112 * @param &$bar array
1113 * @param $message String
1114 */
1115 function addToSidebar( &$bar, $message ) {
1116 $this->addToSidebarPlain( $bar, wfMsgForContentNoTrans( $message ) );
1117 }
1118
1119 /**
1120 * Add content from plain text
1121 * @since 1.17
1122 * @param &$bar array
1123 * @param $text string
1124 * @return Array
1125 */
1126 function addToSidebarPlain( &$bar, $text ) {
1127 $lines = explode( "\n", $text );
1128
1129 $heading = '';
1130
1131 foreach ( $lines as $line ) {
1132 if ( strpos( $line, '*' ) !== 0 ) {
1133 continue;
1134 }
1135 $line = rtrim( $line, "\r" ); // for Windows compat
1136
1137 if ( strpos( $line, '**' ) !== 0 ) {
1138 $heading = trim( $line, '* ' );
1139 if ( !array_key_exists( $heading, $bar ) ) {
1140 $bar[$heading] = array();
1141 }
1142 } else {
1143 $line = trim( $line, '* ' );
1144
1145 if ( strpos( $line, '|' ) !== false ) { // sanity check
1146 $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() );
1147 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1148 $extraAttribs = array();
1149
1150 $msgLink = wfMessage( $line[0] )->inContentLanguage();
1151 if ( $msgLink->exists() ) {
1152 $link = $msgLink->text();
1153 if ( $link == '-' ) {
1154 continue;
1155 }
1156 } else {
1157 $link = $line[0];
1158 }
1159
1160 $msgText = wfMessage( $line[1] );
1161 if ( $msgText->exists() ) {
1162 $text = $msgText->text();
1163 } else {
1164 $text = $line[1];
1165 }
1166
1167 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $link ) ) {
1168 $href = $link;
1169
1170 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1171 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1172 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1173 $extraAttribs['rel'] = 'nofollow';
1174 }
1175
1176 global $wgExternalLinkTarget;
1177 if ( $wgExternalLinkTarget) {
1178 $extraAttribs['target'] = $wgExternalLinkTarget;
1179 }
1180 } else {
1181 $title = Title::newFromText( $link );
1182
1183 if ( $title ) {
1184 $title = $title->fixSpecialName();
1185 $href = $title->getLinkURL();
1186 } else {
1187 $href = 'INVALID-TITLE';
1188 }
1189 }
1190
1191 $bar[$heading][] = array_merge( array(
1192 'text' => $text,
1193 'href' => $href,
1194 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1195 'active' => false
1196 ), $extraAttribs );
1197 } else {
1198 continue;
1199 }
1200 }
1201 }
1202
1203 return $bar;
1204 }
1205
1206 /**
1207 * Should we include common/wikiprintable.css? Skins that have their own
1208 * print stylesheet should override this and return false. (This is an
1209 * ugly hack to get Monobook to play nicely with
1210 * OutputPage::headElement().)
1211 *
1212 * @return bool
1213 */
1214 public function commonPrintStylesheet() {
1215 return true;
1216 }
1217
1218 /**
1219 * Gets new talk page messages for the current user.
1220 * @return MediaWiki message or if no new talk page messages, nothing
1221 */
1222 function getNewtalks() {
1223 $out = $this->getOutput();
1224
1225 $newtalks = $this->getUser()->getNewMessageLinks();
1226 $ntl = '';
1227
1228 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1229 $userTitle = $this->getUser()->getUserPage();
1230 $userTalkTitle = $userTitle->getTalkPage();
1231
1232 if ( !$userTalkTitle->equals( $out->getTitle() ) ) {
1233 $newMessagesLink = Linker::linkKnown(
1234 $userTalkTitle,
1235 wfMsgHtml( 'newmessageslink' ),
1236 array(),
1237 array( 'redirect' => 'no' )
1238 );
1239
1240 $newMessagesDiffLink = Linker::linkKnown(
1241 $userTalkTitle,
1242 wfMsgHtml( 'newmessagesdifflink' ),
1243 array(),
1244 array( 'diff' => 'cur' )
1245 );
1246
1247 $ntl = wfMsg(
1248 'youhavenewmessages',
1249 $newMessagesLink,
1250 $newMessagesDiffLink
1251 );
1252 # Disable Squid cache
1253 $out->setSquidMaxage( 0 );
1254 }
1255 } elseif ( count( $newtalks ) ) {
1256 // _>" " for BC <= 1.16
1257 $sep = str_replace( '_', ' ', wfMsgHtml( 'newtalkseparator' ) );
1258 $msgs = array();
1259
1260 foreach ( $newtalks as $newtalk ) {
1261 $msgs[] = Xml::element(
1262 'a',
1263 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1264 );
1265 }
1266 $parts = implode( $sep, $msgs );
1267 $ntl = wfMsgHtml( 'youhavenewmessagesmulti', $parts );
1268 $out->setSquidMaxage( 0 );
1269 }
1270
1271 return $ntl;
1272 }
1273
1274 /**
1275 * Get a cached notice
1276 *
1277 * @param $name String: message name, or 'default' for $wgSiteNotice
1278 * @return String: HTML fragment
1279 */
1280 private function getCachedNotice( $name ) {
1281 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1282
1283 wfProfileIn( __METHOD__ );
1284
1285 $needParse = false;
1286
1287 if( $name === 'default' ) {
1288 // special case
1289 global $wgSiteNotice;
1290 $notice = $wgSiteNotice;
1291 if( empty( $notice ) ) {
1292 wfProfileOut( __METHOD__ );
1293 return false;
1294 }
1295 } else {
1296 $msg = wfMessage( $name )->inContentLanguage();
1297 if( $msg->isDisabled() ) {
1298 wfProfileOut( __METHOD__ );
1299 return false;
1300 }
1301 $notice = $msg->plain();
1302 }
1303
1304 // Use the extra hash appender to let eg SSL variants separately cache.
1305 $key = wfMemcKey( $name . $wgRenderHashAppend );
1306 $cachedNotice = $parserMemc->get( $key );
1307 if( is_array( $cachedNotice ) ) {
1308 if( md5( $notice ) == $cachedNotice['hash'] ) {
1309 $notice = $cachedNotice['html'];
1310 } else {
1311 $needParse = true;
1312 }
1313 } else {
1314 $needParse = true;
1315 }
1316
1317 if ( $needParse ) {
1318 $parsed = $this->getOutput()->parse( $notice );
1319 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1320 $notice = $parsed;
1321 }
1322
1323 $notice = Html::rawElement( 'div', array( 'id' => 'localNotice',
1324 'lang' => $wgContLang->getCode(), 'dir' => $wgContLang->getDir() ), $notice );
1325 wfProfileOut( __METHOD__ );
1326 return $notice;
1327 }
1328
1329 /**
1330 * Get a notice based on page's namespace
1331 *
1332 * @return String: HTML fragment
1333 */
1334 function getNamespaceNotice() {
1335 wfProfileIn( __METHOD__ );
1336
1337 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1338 $namespaceNotice = $this->getCachedNotice( $key );
1339 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
1340 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1341 } else {
1342 $namespaceNotice = '';
1343 }
1344
1345 wfProfileOut( __METHOD__ );
1346 return $namespaceNotice;
1347 }
1348
1349 /**
1350 * Get the site notice
1351 *
1352 * @return String: HTML fragment
1353 */
1354 function getSiteNotice() {
1355 wfProfileIn( __METHOD__ );
1356 $siteNotice = '';
1357
1358 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1359 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1360 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1361 } else {
1362 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1363 if ( !$anonNotice ) {
1364 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1365 } else {
1366 $siteNotice = $anonNotice;
1367 }
1368 }
1369 if ( !$siteNotice ) {
1370 $siteNotice = $this->getCachedNotice( 'default' );
1371 }
1372 }
1373
1374 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1375 wfProfileOut( __METHOD__ );
1376 return $siteNotice;
1377 }
1378
1379 /**
1380 * Create a section edit link. This supersedes editSectionLink() and
1381 * editSectionLinkForOther().
1382 *
1383 * @param $nt Title The title being linked to (may not be the same as
1384 * $wgTitle, if the section is included from a template)
1385 * @param $section string The designation of the section being pointed to,
1386 * to be included in the link, like "&section=$section"
1387 * @param $tooltip string The tooltip to use for the link: will be escaped
1388 * and wrapped in the 'editsectionhint' message
1389 * @param $lang string Language code
1390 * @return string HTML to use for edit link
1391 */
1392 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1393 // HTML generated here should probably have userlangattributes
1394 // added to it for LTR text on RTL pages
1395 $attribs = array();
1396 if ( !is_null( $tooltip ) ) {
1397 # Bug 25462: undo double-escaping.
1398 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1399 $attribs['title'] = wfMsgExt( 'editsectionhint', array( 'language' => $lang, 'parsemag' ), $tooltip );
1400 }
1401 $link = Linker::link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1402 $attribs,
1403 array( 'action' => 'edit', 'section' => $section ),
1404 array( 'noclasses', 'known' )
1405 );
1406
1407 # Run the old hook. This takes up half of the function . . . hopefully
1408 # we can rid of it someday.
1409 $attribs = '';
1410 if ( $tooltip ) {
1411 $attribs = wfMsgExt( 'editsectionhint', array( 'language' => $lang, 'parsemag', 'escape' ), $tooltip );
1412 $attribs = " title=\"$attribs\"";
1413 }
1414 $result = null;
1415 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1416 if ( !is_null( $result ) ) {
1417 # For reverse compatibility, add the brackets *after* the hook is
1418 # run, and even add them to hook-provided text. (This is the main
1419 # reason that the EditSectionLink hook is deprecated in favor of
1420 # DoEditSectionLink: it can't change the brackets or the span.)
1421 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1422 return "<span class=\"editsection\">$result</span>";
1423 }
1424
1425 # Add the brackets and the span, and *then* run the nice new hook, with
1426 # clean and non-redundant arguments.
1427 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1428 $result = "<span class=\"editsection\">$result</span>";
1429
1430 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1431 return $result;
1432 }
1433
1434 /**
1435 * Use PHP's magic __call handler to intercept legacy calls to the linker
1436 * for backwards compatibility.
1437 *
1438 * @param $fname String Name of called method
1439 * @param $args Array Arguments to the method
1440 */
1441 function __call( $fname, $args ) {
1442 $realFunction = array( 'Linker', $fname );
1443 if ( is_callable( $realFunction ) ) {
1444 return call_user_func_array( $realFunction, $args );
1445 } else {
1446 $className = get_class( $this );
1447 throw new MWException( "Call to undefined method $className::$fname" );
1448 }
1449 }
1450
1451 }