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