Use Skin->getCategories() instead of Skin->getCategoryLinks() and manually wrapping...
[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;
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 return wfMsgForContent( $msg, $link );
767 } else {
768 return wfMsg( $msg, $link );
769 }
770 }
771
772 function getCopyrightIcon() {
773 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
774
775 $out = '';
776
777 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
778 $out = $wgCopyrightIcon;
779 } elseif ( $wgRightsIcon ) {
780 $icon = htmlspecialchars( $wgRightsIcon );
781
782 if ( $wgRightsUrl ) {
783 $url = htmlspecialchars( $wgRightsUrl );
784 $out .= '<a href="' . $url . '">';
785 }
786
787 $text = htmlspecialchars( $wgRightsText );
788 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
789
790 if ( $wgRightsUrl ) {
791 $out .= '</a>';
792 }
793 }
794
795 return $out;
796 }
797
798 /**
799 * Gets the powered by MediaWiki icon.
800 * @return string
801 */
802 function getPoweredBy() {
803 global $wgStylePath;
804
805 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
806 $text = '<a href="http://www.mediawiki.org/"><img src="' . $url . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
807 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
808 return $text;
809 }
810
811 /**
812 * Get the timestamp of the latest revision, formatted in user language
813 *
814 * @param $article Article object. Used if we're working with the current revision
815 * @return String
816 */
817 protected function lastModified( $article ) {
818 if ( !$this->isRevisionCurrent() ) {
819 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
820 } else {
821 $timestamp = $article->getTimestamp();
822 }
823
824 if ( $timestamp ) {
825 $d = $this->getLang()->date( $timestamp, true );
826 $t = $this->getLang()->time( $timestamp, true );
827 $s = ' ' . wfMsg( 'lastmodifiedat', $d, $t );
828 } else {
829 $s = '';
830 }
831
832 if ( wfGetLB()->getLaggedSlaveMode() ) {
833 $s .= ' <strong>' . wfMsg( 'laggedslavemode' ) . '</strong>';
834 }
835
836 return $s;
837 }
838
839 function logoText( $align = '' ) {
840 if ( $align != '' ) {
841 $a = " align='{$align}'";
842 } else {
843 $a = '';
844 }
845
846 $mp = wfMsgHtml( 'mainpage' );
847 $mptitle = Title::newMainPage();
848 $url = ( is_object( $mptitle ) ? $mptitle->escapeLocalURL() : '' );
849
850 $logourl = $this->getLogo();
851 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
852
853 return $s;
854 }
855
856 /**
857 * Renders a $wgFooterIcons icon acording to the method's arguments
858 * @param $icon Array: The icon to build the html for, see $wgFooterIcons for the format of this array
859 * @param $withImage Bool|String: Whether to use the icon's image or output a text-only footericon
860 * @return String HTML
861 */
862 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
863 if ( is_string( $icon ) ) {
864 $html = $icon;
865 } else { // Assuming array
866 $url = isset($icon["url"]) ? $icon["url"] : null;
867 unset( $icon["url"] );
868 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
869 $html = Html::element( 'img', $icon ); // do this the lazy way, just pass icon data as an attribute array
870 } else {
871 $html = htmlspecialchars( $icon["alt"] );
872 }
873 if ( $url ) {
874 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
875 }
876 }
877 return $html;
878 }
879
880 /**
881 * Gets the link to the wiki's main page.
882 * @return string
883 */
884 function mainPageLink() {
885 $s = Linker::linkKnown(
886 Title::newMainPage(),
887 wfMsgHtml( 'mainpage' )
888 );
889
890 return $s;
891 }
892
893 public function footerLink( $desc, $page ) {
894 // if the link description has been set to "-" in the default language,
895 if ( wfMsgForContent( $desc ) == '-' ) {
896 // then it is disabled, for all languages.
897 return '';
898 } else {
899 // Otherwise, we display the link for the user, described in their
900 // language (which may or may not be the same as the default language),
901 // but we make the link target be the one site-wide page.
902 $title = Title::newFromText( wfMsgForContent( $page ) );
903
904 return Linker::linkKnown(
905 $title,
906 wfMsgExt( $desc, array( 'parsemag', 'escapenoentities' ) )
907 );
908 }
909 }
910
911 /**
912 * Gets the link to the wiki's privacy policy page.
913 * @return String HTML
914 */
915 function privacyLink() {
916 return $this->footerLink( 'privacy', 'privacypage' );
917 }
918
919 /**
920 * Gets the link to the wiki's about page.
921 * @return String HTML
922 */
923 function aboutLink() {
924 return $this->footerLink( 'aboutsite', 'aboutpage' );
925 }
926
927 /**
928 * Gets the link to the wiki's general disclaimers page.
929 * @return String HTML
930 */
931 function disclaimerLink() {
932 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
933 }
934
935 /**
936 * Return URL options for the 'edit page' link.
937 * This may include an 'oldid' specifier, if the current page view is such.
938 *
939 * @return array
940 * @private
941 */
942 function editUrlOptions() {
943 $options = array( 'action' => 'edit' );
944
945 if ( !$this->isRevisionCurrent() ) {
946 $options['oldid'] = intval( $this->getRevisionId() );
947 }
948
949 return $options;
950 }
951
952 function showEmailUser( $id ) {
953 $targetUser = User::newFromId( $id );
954 return $this->getUser()->canSendEmail() && # the sending user must have a confirmed email address
955 $targetUser->canReceiveEmail(); # the target user must have a confirmed email address and allow emails from users
956 }
957
958 /**
959 * Return a fully resolved style path url to images or styles stored in the common folder.
960 * This method returns a url resolved using the configured skin style path
961 * and includes the style version inside of the url.
962 * @param $name String: The name or path of a skin resource file
963 * @return String The fully resolved style path url including styleversion
964 */
965 function getCommonStylePath( $name ) {
966 global $wgStylePath, $wgStyleVersion;
967 return "$wgStylePath/common/$name?$wgStyleVersion";
968 }
969
970 /**
971 * Return a fully resolved style path url to images or styles stored in the curent skins's folder.
972 * This method returns a url resolved using the configured skin style path
973 * and includes the style version inside of the url.
974 * @param $name String: The name or path of a skin resource file
975 * @return String The fully resolved style path url including styleversion
976 */
977 function getSkinStylePath( $name ) {
978 global $wgStylePath, $wgStyleVersion;
979 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
980 }
981
982 /* these are used extensively in SkinTemplate, but also some other places */
983 static function makeMainPageUrl( $urlaction = '' ) {
984 $title = Title::newMainPage();
985 self::checkTitle( $title, '' );
986
987 return $title->getLocalURL( $urlaction );
988 }
989
990 static function makeSpecialUrl( $name, $urlaction = '' ) {
991 $title = SpecialPage::getSafeTitleFor( $name );
992 return $title->getLocalURL( $urlaction );
993 }
994
995 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
996 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
997 return $title->getLocalURL( $urlaction );
998 }
999
1000 static function makeI18nUrl( $name, $urlaction = '' ) {
1001 $title = Title::newFromText( wfMsgForContent( $name ) );
1002 self::checkTitle( $title, $name );
1003 return $title->getLocalURL( $urlaction );
1004 }
1005
1006 static function makeUrl( $name, $urlaction = '' ) {
1007 $title = Title::newFromText( $name );
1008 self::checkTitle( $title, $name );
1009
1010 return $title->getLocalURL( $urlaction );
1011 }
1012
1013 /**
1014 * If url string starts with http, consider as external URL, else
1015 * internal
1016 * @param $name String
1017 * @return String URL
1018 */
1019 static function makeInternalOrExternalUrl( $name ) {
1020 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $name ) ) {
1021 return $name;
1022 } else {
1023 return self::makeUrl( $name );
1024 }
1025 }
1026
1027 # this can be passed the NS number as defined in Language.php
1028 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1029 $title = Title::makeTitleSafe( $namespace, $name );
1030 self::checkTitle( $title, $name );
1031
1032 return $title->getLocalURL( $urlaction );
1033 }
1034
1035 /* these return an array with the 'href' and boolean 'exists' */
1036 static function makeUrlDetails( $name, $urlaction = '' ) {
1037 $title = Title::newFromText( $name );
1038 self::checkTitle( $title, $name );
1039
1040 return array(
1041 'href' => $title->getLocalURL( $urlaction ),
1042 'exists' => $title->getArticleID() != 0,
1043 );
1044 }
1045
1046 /**
1047 * Make URL details where the article exists (or at least it's convenient to think so)
1048 * @param $name String Article name
1049 * @param $urlaction String
1050 * @return Array
1051 */
1052 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1053 $title = Title::newFromText( $name );
1054 self::checkTitle( $title, $name );
1055
1056 return array(
1057 'href' => $title->getLocalURL( $urlaction ),
1058 'exists' => true
1059 );
1060 }
1061
1062 # make sure we have some title to operate on
1063 static function checkTitle( &$title, $name ) {
1064 if ( !is_object( $title ) ) {
1065 $title = Title::newFromText( $name );
1066 if ( !is_object( $title ) ) {
1067 $title = Title::newFromText( '--error: link target missing--' );
1068 }
1069 }
1070 }
1071
1072 /**
1073 * Build an array that represents the sidebar(s), the navigation bar among them
1074 *
1075 * @return array
1076 */
1077 function buildSidebar() {
1078 global $parserMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1079 wfProfileIn( __METHOD__ );
1080
1081 $key = wfMemcKey( 'sidebar', $this->getLang()->getCode() );
1082
1083 if ( $wgEnableSidebarCache ) {
1084 $cachedsidebar = $parserMemc->get( $key );
1085 if ( $cachedsidebar ) {
1086 wfProfileOut( __METHOD__ );
1087 return $cachedsidebar;
1088 }
1089 }
1090
1091 $bar = array();
1092 $this->addToSidebar( $bar, 'sidebar' );
1093
1094 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1095 if ( $wgEnableSidebarCache ) {
1096 $parserMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1097 }
1098
1099 wfProfileOut( __METHOD__ );
1100 return $bar;
1101 }
1102 /**
1103 * Add content from a sidebar system message
1104 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1105 *
1106 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1107 *
1108 * @param &$bar array
1109 * @param $message String
1110 */
1111 function addToSidebar( &$bar, $message ) {
1112 $this->addToSidebarPlain( $bar, wfMsgForContentNoTrans( $message ) );
1113 }
1114
1115 /**
1116 * Add content from plain text
1117 * @since 1.17
1118 * @param &$bar array
1119 * @param $text string
1120 * @return Array
1121 */
1122 function addToSidebarPlain( &$bar, $text ) {
1123 $lines = explode( "\n", $text );
1124
1125 $heading = '';
1126
1127 foreach ( $lines as $line ) {
1128 if ( strpos( $line, '*' ) !== 0 ) {
1129 continue;
1130 }
1131 $line = rtrim( $line, "\r" ); // for Windows compat
1132
1133 if ( strpos( $line, '**' ) !== 0 ) {
1134 $heading = trim( $line, '* ' );
1135 if ( !array_key_exists( $heading, $bar ) ) {
1136 $bar[$heading] = array();
1137 }
1138 } else {
1139 $line = trim( $line, '* ' );
1140
1141 if ( strpos( $line, '|' ) !== false ) { // sanity check
1142 $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() );
1143 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1144 $extraAttribs = array();
1145
1146 $msgLink = wfMessage( $line[0] )->inContentLanguage();
1147 if ( $msgLink->exists() ) {
1148 $link = $msgLink->text();
1149 if ( $link == '-' ) {
1150 continue;
1151 }
1152 } else {
1153 $link = $line[0];
1154 }
1155
1156 $msgText = wfMessage( $line[1] );
1157 if ( $msgText->exists() ) {
1158 $text = $msgText->text();
1159 } else {
1160 $text = $line[1];
1161 }
1162
1163 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $link ) ) {
1164 $href = $link;
1165
1166 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1167 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1168 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1169 $extraAttribs['rel'] = 'nofollow';
1170 }
1171
1172 global $wgExternalLinkTarget;
1173 if ( $wgExternalLinkTarget) {
1174 $extraAttribs['target'] = $wgExternalLinkTarget;
1175 }
1176 } else {
1177 $title = Title::newFromText( $link );
1178
1179 if ( $title ) {
1180 $title = $title->fixSpecialName();
1181 $href = $title->getLinkURL();
1182 } else {
1183 $href = 'INVALID-TITLE';
1184 }
1185 }
1186
1187 $bar[$heading][] = array_merge( array(
1188 'text' => $text,
1189 'href' => $href,
1190 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1191 'active' => false
1192 ), $extraAttribs );
1193 } else {
1194 continue;
1195 }
1196 }
1197 }
1198
1199 return $bar;
1200 }
1201
1202 /**
1203 * Should we include common/wikiprintable.css? Skins that have their own
1204 * print stylesheet should override this and return false. (This is an
1205 * ugly hack to get Monobook to play nicely with
1206 * OutputPage::headElement().)
1207 *
1208 * @return bool
1209 */
1210 public function commonPrintStylesheet() {
1211 return true;
1212 }
1213
1214 /**
1215 * Gets new talk page messages for the current user.
1216 * @return MediaWiki message or if no new talk page messages, nothing
1217 */
1218 function getNewtalks() {
1219 $out = $this->getOutput();
1220
1221 $newtalks = $this->getUser()->getNewMessageLinks();
1222 $ntl = '';
1223
1224 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1225 $userTitle = $this->getUser()->getUserPage();
1226 $userTalkTitle = $userTitle->getTalkPage();
1227
1228 if ( !$userTalkTitle->equals( $out->getTitle() ) ) {
1229 $newMessagesLink = Linker::linkKnown(
1230 $userTalkTitle,
1231 wfMsgHtml( 'newmessageslink' ),
1232 array(),
1233 array( 'redirect' => 'no' )
1234 );
1235
1236 $newMessagesDiffLink = Linker::linkKnown(
1237 $userTalkTitle,
1238 wfMsgHtml( 'newmessagesdifflink' ),
1239 array(),
1240 array( 'diff' => 'cur' )
1241 );
1242
1243 $ntl = wfMsg(
1244 'youhavenewmessages',
1245 $newMessagesLink,
1246 $newMessagesDiffLink
1247 );
1248 # Disable Squid cache
1249 $out->setSquidMaxage( 0 );
1250 }
1251 } elseif ( count( $newtalks ) ) {
1252 // _>" " for BC <= 1.16
1253 $sep = str_replace( '_', ' ', wfMsgHtml( 'newtalkseparator' ) );
1254 $msgs = array();
1255
1256 foreach ( $newtalks as $newtalk ) {
1257 $msgs[] = Xml::element(
1258 'a',
1259 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1260 );
1261 }
1262 $parts = implode( $sep, $msgs );
1263 $ntl = wfMsgHtml( 'youhavenewmessagesmulti', $parts );
1264 $out->setSquidMaxage( 0 );
1265 }
1266
1267 return $ntl;
1268 }
1269
1270 /**
1271 * Get a cached notice
1272 *
1273 * @param $name String: message name, or 'default' for $wgSiteNotice
1274 * @return String: HTML fragment
1275 */
1276 private function getCachedNotice( $name ) {
1277 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1278
1279 wfProfileIn( __METHOD__ );
1280
1281 $needParse = false;
1282
1283 if( $name === 'default' ) {
1284 // special case
1285 global $wgSiteNotice;
1286 $notice = $wgSiteNotice;
1287 if( empty( $notice ) ) {
1288 wfProfileOut( __METHOD__ );
1289 return false;
1290 }
1291 } else {
1292 $msg = wfMessage( $name )->inContentLanguage();
1293 if( $msg->isDisabled() ) {
1294 wfProfileOut( __METHOD__ );
1295 return false;
1296 }
1297 $notice = $msg->plain();
1298 }
1299
1300 // Use the extra hash appender to let eg SSL variants separately cache.
1301 $key = wfMemcKey( $name . $wgRenderHashAppend );
1302 $cachedNotice = $parserMemc->get( $key );
1303 if( is_array( $cachedNotice ) ) {
1304 if( md5( $notice ) == $cachedNotice['hash'] ) {
1305 $notice = $cachedNotice['html'];
1306 } else {
1307 $needParse = true;
1308 }
1309 } else {
1310 $needParse = true;
1311 }
1312
1313 if ( $needParse ) {
1314 $parsed = $this->getOutput()->parse( $notice );
1315 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1316 $notice = $parsed;
1317 }
1318
1319 $notice = Html::rawElement( 'div', array( 'id' => 'localNotice',
1320 'lang' => $wgContLang->getCode(), 'dir' => $wgContLang->getDir() ), $notice );
1321 wfProfileOut( __METHOD__ );
1322 return $notice;
1323 }
1324
1325 /**
1326 * Get a notice based on page's namespace
1327 *
1328 * @return String: HTML fragment
1329 */
1330 function getNamespaceNotice() {
1331 wfProfileIn( __METHOD__ );
1332
1333 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1334 $namespaceNotice = $this->getCachedNotice( $key );
1335 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
1336 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1337 } else {
1338 $namespaceNotice = '';
1339 }
1340
1341 wfProfileOut( __METHOD__ );
1342 return $namespaceNotice;
1343 }
1344
1345 /**
1346 * Get the site notice
1347 *
1348 * @return String: HTML fragment
1349 */
1350 function getSiteNotice() {
1351 wfProfileIn( __METHOD__ );
1352 $siteNotice = '';
1353
1354 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1355 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1356 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1357 } else {
1358 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1359 if ( !$anonNotice ) {
1360 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1361 } else {
1362 $siteNotice = $anonNotice;
1363 }
1364 }
1365 if ( !$siteNotice ) {
1366 $siteNotice = $this->getCachedNotice( 'default' );
1367 }
1368 }
1369
1370 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1371 wfProfileOut( __METHOD__ );
1372 return $siteNotice;
1373 }
1374
1375 /**
1376 * Create a section edit link. This supersedes editSectionLink() and
1377 * editSectionLinkForOther().
1378 *
1379 * @param $nt Title The title being linked to (may not be the same as
1380 * $wgTitle, if the section is included from a template)
1381 * @param $section string The designation of the section being pointed to,
1382 * to be included in the link, like "&section=$section"
1383 * @param $tooltip string The tooltip to use for the link: will be escaped
1384 * and wrapped in the 'editsectionhint' message
1385 * @param $lang string Language code
1386 * @return string HTML to use for edit link
1387 */
1388 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1389 // HTML generated here should probably have userlangattributes
1390 // added to it for LTR text on RTL pages
1391 $attribs = array();
1392 if ( !is_null( $tooltip ) ) {
1393 # Bug 25462: undo double-escaping.
1394 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1395 $attribs['title'] = wfMsgExt( 'editsectionhint', array( 'language' => $lang, 'parsemag' ), $tooltip );
1396 }
1397 $link = Linker::link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1398 $attribs,
1399 array( 'action' => 'edit', 'section' => $section ),
1400 array( 'noclasses', 'known' )
1401 );
1402
1403 # Run the old hook. This takes up half of the function . . . hopefully
1404 # we can rid of it someday.
1405 $attribs = '';
1406 if ( $tooltip ) {
1407 $attribs = wfMsgExt( 'editsectionhint', array( 'language' => $lang, 'parsemag', 'escape' ), $tooltip );
1408 $attribs = " title=\"$attribs\"";
1409 }
1410 $result = null;
1411 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1412 if ( !is_null( $result ) ) {
1413 # For reverse compatibility, add the brackets *after* the hook is
1414 # run, and even add them to hook-provided text. (This is the main
1415 # reason that the EditSectionLink hook is deprecated in favor of
1416 # DoEditSectionLink: it can't change the brackets or the span.)
1417 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1418 return "<span class=\"editsection\">$result</span>";
1419 }
1420
1421 # Add the brackets and the span, and *then* run the nice new hook, with
1422 # clean and non-redundant arguments.
1423 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1424 $result = "<span class=\"editsection\">$result</span>";
1425
1426 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1427 return $result;
1428 }
1429
1430 /**
1431 * Use PHP's magic __call handler to intercept legacy calls to the linker
1432 * for backwards compatibility.
1433 *
1434 * @param $fname String Name of called method
1435 * @param $args Array Arguments to the method
1436 */
1437 function __call( $fname, $args ) {
1438 $realFunction = array( 'Linker', $fname );
1439 if ( is_callable( $realFunction ) ) {
1440 return call_user_func_array( $realFunction, $args );
1441 } else {
1442 $className = get_class( $this );
1443 throw new MWException( "Call to undefined method $className::$fname" );
1444 }
1445 }
1446
1447 }