Merge "Separate MonoBook skin from core"
[lhc/web/wiklou.git] / includes / Skin.php
1 <?php
2 /**
3 * Base class for all skins.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * @defgroup Skins Skins
25 */
26
27 /**
28 * The main skin class which provides methods and properties for all other skins.
29 *
30 * See docs/skin.txt for more information.
31 *
32 * @ingroup Skins
33 */
34 abstract class Skin extends ContextSource {
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
38
39 /**
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
42 */
43 public $stylename = null;
44
45 /**
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
48 */
49 static function getSkinNames() {
50 global $wgValidSkinNames;
51 static $skinsInitialised = false;
52
53 if ( !$skinsInitialised || !count( $wgValidSkinNames ) ) {
54 # Get a list of available skins
55 # Build using the regular expression '^(.*).php$'
56 # Array keys are all lower case, array value keep the case used by filename
57 #
58 wfProfileIn( __METHOD__ . '-init' );
59
60 global $wgStyleDirectory;
61
62 $skinDir = dir( $wgStyleDirectory );
63
64 if ( $skinDir !== false && $skinDir !== null ) {
65 # while code from www.php.net
66 while ( false !== ( $file = $skinDir->read() ) ) {
67 // Skip non-PHP files, hidden files, and '.dep' includes
68 $matches = array();
69
70 if ( preg_match( '/^([^.]*)\.php$/', $file, $matches ) ) {
71 $aSkin = $matches[1];
72
73 // Explicitly disallow loading core skins via the autodiscovery mechanism.
74 //
75 // They should be loaded already (in a non-autodicovery way), but old files might still
76 // exist on the server because our MW version upgrade process is widely documented as
77 // requiring just copying over all files, without removing old ones.
78 //
79 // This is one of the reasons we should have never used autodiscovery in the first
80 // place. This hack can be safely removed when autodiscovery is gone.
81 if ( in_array( $aSkin, array( 'CologneBlue', 'Modern', 'MonoBook', 'Vector' ) ) ) {
82 wfLogWarning(
83 "An old copy of the $aSkin skin was found in your skins/ directory. " .
84 "You should remove it to avoid problems in the future." .
85 "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for details."
86 );
87 continue;
88 }
89
90 wfLogWarning(
91 "A skin using autodiscovery mechanism, $aSkin, was found in your skins/ directory. " .
92 "The mechanism will be removed in MediaWiki 1.25 and the skin will no longer be recognized. " .
93 "See https://www.mediawiki.org/wiki/Manual:Skin_autodiscovery for information how to fix this."
94 );
95 $wgValidSkinNames[strtolower( $aSkin )] = $aSkin;
96 }
97 }
98 $skinDir->close();
99 }
100 $skinsInitialised = true;
101 wfProfileOut( __METHOD__ . '-init' );
102 }
103 return $wgValidSkinNames;
104 }
105
106 /**
107 * Fetch the skinname messages for available skins.
108 * @return string[]
109 */
110 static function getSkinNameMessages() {
111 $messages = array();
112 foreach ( self::getSkinNames() as $skinKey => $skinName ) {
113 $messages[] = "skinname-$skinKey";
114 }
115 return $messages;
116 }
117
118 /**
119 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
120 * Useful for Special:Preferences and other places where you
121 * only want to show skins users _can_ use.
122 * @return string[]
123 * @since 1.23
124 */
125 public static function getAllowedSkins() {
126 global $wgSkipSkins;
127
128 $allowedSkins = self::getSkinNames();
129
130 foreach ( $wgSkipSkins as $skip ) {
131 unset( $allowedSkins[$skip] );
132 }
133
134 return $allowedSkins;
135 }
136
137 /**
138 * @deprecated since 1.23, use getAllowedSkins
139 * @return string[]
140 */
141 public static function getUsableSkins() {
142 wfDeprecated( __METHOD__, '1.23' );
143 return self::getAllowedSkins();
144 }
145
146 /**
147 * Normalize a skin preference value to a form that can be loaded.
148 * If a skin can't be found, it will fall back to the configured
149 * default, or the hardcoded default if that's broken.
150 * @param string $key 'monobook', 'vector', etc.
151 * @return string
152 */
153 static function normalizeKey( $key ) {
154 global $wgDefaultSkin;
155
156 $skinNames = Skin::getSkinNames();
157
158 if ( $key == '' || $key == 'default' ) {
159 // Don't return the default immediately;
160 // in a misconfiguration we need to fall back.
161 $key = $wgDefaultSkin;
162 }
163
164 if ( isset( $skinNames[$key] ) ) {
165 return $key;
166 }
167
168 // Older versions of the software used a numeric setting
169 // in the user preferences.
170 $fallback = array(
171 0 => $wgDefaultSkin,
172 2 => 'cologneblue'
173 );
174
175 if ( isset( $fallback[$key] ) ) {
176 $key = $fallback[$key];
177 }
178
179 if ( isset( $skinNames[$key] ) ) {
180 return $key;
181 } elseif ( isset( $skinNames[$wgDefaultSkin] ) ) {
182 return $wgDefaultSkin;
183 } else {
184 return 'vector';
185 }
186 }
187
188 /**
189 * Factory method for loading a skin of a given type
190 * @param string $key 'monobook', 'vector', etc.
191 * @return Skin
192 */
193 static function &newFromKey( $key ) {
194 global $wgStyleDirectory;
195
196 $key = Skin::normalizeKey( $key );
197
198 $skinNames = Skin::getSkinNames();
199 $skinName = $skinNames[$key];
200 $className = "Skin{$skinName}";
201
202 # Grab the skin class and initialise it.
203 if ( !class_exists( $className ) ) {
204
205 require_once "{$wgStyleDirectory}/{$skinName}.php";
206
207 # Check if we got if not fallback to default skin
208 if ( !class_exists( $className ) ) {
209 # DO NOT die if the class isn't found. This breaks maintenance
210 # scripts and can cause a user account to be unrecoverable
211 # except by SQL manipulation if a previously valid skin name
212 # is no longer valid.
213 wfDebug( "Skin class does not exist: $className\n" );
214 $className = 'SkinVector';
215 }
216 }
217 $skin = new $className( $key );
218 return $skin;
219 }
220
221 /**
222 * @return string Skin name
223 */
224 public function getSkinName() {
225 return $this->skinname;
226 }
227
228 /**
229 * @param OutputPage $out
230 */
231 function initPage( OutputPage $out ) {
232 wfProfileIn( __METHOD__ );
233
234 $this->preloadExistence();
235
236 wfProfileOut( __METHOD__ );
237 }
238
239 /**
240 * Defines the ResourceLoader modules that should be added to the skin
241 * It is recommended that skins wishing to override call parent::getDefaultModules()
242 * and substitute out any modules they wish to change by using a key to look them up
243 * @return array Array of modules with helper keys for easy overriding
244 */
245 public function getDefaultModules() {
246 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
247 $wgAjaxWatch, $wgEnableAPI, $wgEnableWriteAPI;
248
249 $out = $this->getOutput();
250 $user = $out->getUser();
251 $modules = array(
252 // modules that enhance the page content in some way
253 'content' => array(
254 'mediawiki.page.ready',
255 ),
256 // modules that exist for legacy reasons
257 'legacy' => array(),
258 // modules relating to search functionality
259 'search' => array(),
260 // modules relating to functionality relating to watching an article
261 'watch' => array(),
262 // modules which relate to the current users preferences
263 'user' => array(),
264 );
265 if ( $wgIncludeLegacyJavaScript ) {
266 $modules['legacy'][] = 'mediawiki.legacy.wikibits';
267 }
268
269 if ( $wgPreloadJavaScriptMwUtil ) {
270 $modules['legacy'][] = 'mediawiki.util';
271 }
272
273 // Add various resources if required
274 if ( $wgUseAjax ) {
275 $modules['legacy'][] = 'mediawiki.legacy.ajax';
276
277 if ( $wgEnableAPI ) {
278 if ( $wgEnableWriteAPI && $wgAjaxWatch && $user->isLoggedIn()
279 && $user->isAllowed( 'writeapi' )
280 ) {
281 $modules['watch'][] = 'mediawiki.page.watch.ajax';
282 }
283
284 $modules['search'][] = 'mediawiki.searchSuggest';
285 }
286 }
287
288 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
289 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
290 }
291
292 // Crazy edit-on-double-click stuff
293 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
294 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
295 }
296 return $modules;
297 }
298
299 /**
300 * Preload the existence of three commonly-requested pages in a single query
301 */
302 function preloadExistence() {
303 $user = $this->getUser();
304
305 // User/talk link
306 $titles = array( $user->getUserPage(), $user->getTalkPage() );
307
308 // Other tab link
309 if ( $this->getTitle()->isSpecialPage() ) {
310 // nothing
311 } elseif ( $this->getTitle()->isTalkPage() ) {
312 $titles[] = $this->getTitle()->getSubjectPage();
313 } else {
314 $titles[] = $this->getTitle()->getTalkPage();
315 }
316
317 $lb = new LinkBatch( $titles );
318 $lb->setCaller( __METHOD__ );
319 $lb->execute();
320 }
321
322 /**
323 * Get the current revision ID
324 *
325 * @return int
326 */
327 public function getRevisionId() {
328 return $this->getOutput()->getRevisionId();
329 }
330
331 /**
332 * Whether the revision displayed is the latest revision of the page
333 *
334 * @return bool
335 */
336 public function isRevisionCurrent() {
337 $revID = $this->getRevisionId();
338 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
339 }
340
341 /**
342 * Set the "relevant" title
343 * @see self::getRelevantTitle()
344 * @param Title $t
345 */
346 public function setRelevantTitle( $t ) {
347 $this->mRelevantTitle = $t;
348 }
349
350 /**
351 * Return the "relevant" title.
352 * A "relevant" title is not necessarily the actual title of the page.
353 * Special pages like Special:MovePage use set the page they are acting on
354 * as their "relevant" title, this allows the skin system to display things
355 * such as content tabs which belong to to that page instead of displaying
356 * a basic special page tab which has almost no meaning.
357 *
358 * @return Title
359 */
360 public function getRelevantTitle() {
361 if ( isset( $this->mRelevantTitle ) ) {
362 return $this->mRelevantTitle;
363 }
364 return $this->getTitle();
365 }
366
367 /**
368 * Set the "relevant" user
369 * @see self::getRelevantUser()
370 * @param User $u
371 */
372 public function setRelevantUser( $u ) {
373 $this->mRelevantUser = $u;
374 }
375
376 /**
377 * Return the "relevant" user.
378 * A "relevant" user is similar to a relevant title. Special pages like
379 * Special:Contributions mark the user which they are relevant to so that
380 * things like the toolbox can display the information they usually are only
381 * able to display on a user's userpage and talkpage.
382 * @return User
383 */
384 public function getRelevantUser() {
385 if ( isset( $this->mRelevantUser ) ) {
386 return $this->mRelevantUser;
387 }
388 $title = $this->getRelevantTitle();
389 if ( $title->hasSubjectNamespace( NS_USER ) ) {
390 $rootUser = $title->getRootText();
391 if ( User::isIP( $rootUser ) ) {
392 $this->mRelevantUser = User::newFromName( $rootUser, false );
393 } else {
394 $user = User::newFromName( $rootUser, false );
395 if ( $user && $user->isLoggedIn() ) {
396 $this->mRelevantUser = $user;
397 }
398 }
399 return $this->mRelevantUser;
400 }
401 return null;
402 }
403
404 /**
405 * Outputs the HTML generated by other functions.
406 * @param OutputPage $out
407 */
408 abstract function outputPage( OutputPage $out = null );
409
410 /**
411 * @param array $data
412 * @return string
413 */
414 static function makeVariablesScript( $data ) {
415 if ( $data ) {
416 return Html::inlineScript(
417 ResourceLoader::makeLoaderConditionalScript( ResourceLoader::makeConfigSetScript( $data ) )
418 );
419 } else {
420 return '';
421 }
422 }
423
424 /**
425 * Make a "<script>" tag containing global variables
426 *
427 * @deprecated since 1.19
428 * @param mixed $unused
429 * @return string HTML fragment
430 */
431 public static function makeGlobalVariablesScript( $unused ) {
432 global $wgOut;
433
434 wfDeprecated( __METHOD__, '1.19' );
435
436 return self::makeVariablesScript( $wgOut->getJSVars() );
437 }
438
439 /**
440 * Get the query to generate a dynamic stylesheet
441 *
442 * @return array
443 */
444 public static function getDynamicStylesheetQuery() {
445 global $wgSquidMaxage;
446
447 return array(
448 'action' => 'raw',
449 'maxage' => $wgSquidMaxage,
450 'usemsgcache' => 'yes',
451 'ctype' => 'text/css',
452 'smaxage' => $wgSquidMaxage,
453 );
454 }
455
456 /**
457 * Add skin specific stylesheets
458 * Calling this method with an $out of anything but the same OutputPage
459 * inside ->getOutput() is deprecated. The $out arg is kept
460 * for compatibility purposes with skins.
461 * @param OutputPage $out
462 * @todo delete
463 */
464 abstract function setupSkinUserCss( OutputPage $out );
465
466 /**
467 * TODO: document
468 * @param Title $title
469 * @return string
470 */
471 function getPageClasses( $title ) {
472 $numeric = 'ns-' . $title->getNamespace();
473
474 if ( $title->isSpecialPage() ) {
475 $type = 'ns-special';
476 // bug 23315: provide a class based on the canonical special page name without subpages
477 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
478 if ( $canonicalName ) {
479 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
480 } else {
481 $type .= ' mw-invalidspecialpage';
482 }
483 } elseif ( $title->isTalkPage() ) {
484 $type = 'ns-talk';
485 } else {
486 $type = 'ns-subject';
487 }
488
489 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
490
491 return "$numeric $type $name";
492 }
493
494 /*
495 * Return values for <html> element
496 * @return array of associative name-to-value elements for <html> element
497 */
498 public function getHtmlElementAttributes() {
499 $lang = $this->getLanguage();
500 return array(
501 'lang' => $lang->getHtmlCode(),
502 'dir' => $lang->getDir(),
503 'class' => 'client-nojs',
504 );
505 }
506
507 /**
508 * This will be called by OutputPage::headElement when it is creating the
509 * "<body>" tag, skins can override it if they have a need to add in any
510 * body attributes or classes of their own.
511 * @param OutputPage $out
512 * @param array $bodyAttrs
513 */
514 function addToBodyAttributes( $out, &$bodyAttrs ) {
515 // does nothing by default
516 }
517
518 /**
519 * URL to the logo
520 * @return string
521 */
522 function getLogo() {
523 global $wgLogo;
524 return $wgLogo;
525 }
526
527 /**
528 * @return string
529 */
530 function getCategoryLinks() {
531 global $wgUseCategoryBrowser;
532
533 $out = $this->getOutput();
534 $allCats = $out->getCategoryLinks();
535
536 if ( !count( $allCats ) ) {
537 return '';
538 }
539
540 $embed = "<li>";
541 $pop = "</li>";
542
543 $s = '';
544 $colon = $this->msg( 'colon-separator' )->escaped();
545
546 if ( !empty( $allCats['normal'] ) ) {
547 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
548
549 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
550 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
551 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
552 Linker::link( Title::newFromText( $linkPage ), $msg )
553 . $colon . '<ul>' . $t . '</ul>' . '</div>';
554 }
555
556 # Hidden categories
557 if ( isset( $allCats['hidden'] ) ) {
558 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
559 $class = ' mw-hidden-cats-user-shown';
560 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
561 $class = ' mw-hidden-cats-ns-shown';
562 } else {
563 $class = ' mw-hidden-cats-hidden';
564 }
565
566 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
567 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
568 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
569 '</div>';
570 }
571
572 # optional 'dmoz-like' category browser. Will be shown under the list
573 # of categories an article belong to
574 if ( $wgUseCategoryBrowser ) {
575 $s .= '<br /><hr />';
576
577 # get a big array of the parents tree
578 $parenttree = $this->getTitle()->getParentCategoryTree();
579 # Skin object passed by reference cause it can not be
580 # accessed under the method subfunction drawCategoryBrowser
581 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
582 # Clean out bogus first entry and sort them
583 unset( $tempout[0] );
584 asort( $tempout );
585 # Output one per line
586 $s .= implode( "<br />\n", $tempout );
587 }
588
589 return $s;
590 }
591
592 /**
593 * Render the array as a series of links.
594 * @param array $tree Categories tree returned by Title::getParentCategoryTree
595 * @return string Separated by &gt;, terminate with "\n"
596 */
597 function drawCategoryBrowser( $tree ) {
598 $return = '';
599
600 foreach ( $tree as $element => $parent ) {
601 if ( empty( $parent ) ) {
602 # element start a new list
603 $return .= "\n";
604 } else {
605 # grab the others elements
606 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
607 }
608
609 # add our current element to the list
610 $eltitle = Title::newFromText( $element );
611 $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
612 }
613
614 return $return;
615 }
616
617 /**
618 * @return string
619 */
620 function getCategories() {
621 $out = $this->getOutput();
622
623 $catlinks = $this->getCategoryLinks();
624
625 $classes = 'catlinks';
626
627 // Check what we're showing
628 $allCats = $out->getCategoryLinks();
629 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
630 $this->getTitle()->getNamespace() == NS_CATEGORY;
631
632 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
633 $classes .= ' catlinks-allhidden';
634 }
635
636 return "<div id='catlinks' class='$classes'>{$catlinks}</div>";
637 }
638
639 /**
640 * This runs a hook to allow extensions placing their stuff after content
641 * and article metadata (e.g. categories).
642 * Note: This function has nothing to do with afterContent().
643 *
644 * This hook is placed here in order to allow using the same hook for all
645 * skins, both the SkinTemplate based ones and the older ones, which directly
646 * use this class to get their data.
647 *
648 * The output of this function gets processed in SkinTemplate::outputPage() for
649 * the SkinTemplate based skins, all other skins should directly echo it.
650 *
651 * @return string Empty by default, if not changed by any hook function.
652 */
653 protected function afterContentHook() {
654 $data = '';
655
656 if ( wfRunHooks( 'SkinAfterContent', array( &$data, $this ) ) ) {
657 // adding just some spaces shouldn't toggle the output
658 // of the whole <div/>, so we use trim() here
659 if ( trim( $data ) != '' ) {
660 // Doing this here instead of in the skins to
661 // ensure that the div has the same ID in all
662 // skins
663 $data = "<div id='mw-data-after-content'>\n" .
664 "\t$data\n" .
665 "</div>\n";
666 }
667 } else {
668 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
669 }
670
671 return $data;
672 }
673
674 /**
675 * Generate debug data HTML for displaying at the bottom of the main content
676 * area.
677 * @return string HTML containing debug data, if enabled (otherwise empty).
678 */
679 protected function generateDebugHTML() {
680 return MWDebug::getHTMLDebugLog();
681 }
682
683 /**
684 * This gets called shortly before the "</body>" tag.
685 *
686 * @return string HTML-wrapped JS code to be put before "</body>"
687 */
688 function bottomScripts() {
689 // TODO and the suckage continues. This function is really just a wrapper around
690 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
691 // up at some point
692 $bottomScriptText = $this->getOutput()->getBottomScripts();
693 wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) );
694
695 return $bottomScriptText;
696 }
697
698 /**
699 * Text with the permalink to the source page,
700 * usually shown on the footer of a printed page
701 *
702 * @return string HTML text with an URL
703 */
704 function printSource() {
705 $oldid = $this->getRevisionId();
706 if ( $oldid ) {
707 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
708 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
709 } else {
710 // oldid not available for non existing pages
711 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
712 }
713
714 return $this->msg( 'retrievedfrom', '<a dir="ltr" href="' . $url
715 . '">' . $url . '</a>' )->text();
716 }
717
718 /**
719 * @return string
720 */
721 function getUndeleteLink() {
722 $action = $this->getRequest()->getVal( 'action', 'view' );
723
724 if ( $this->getUser()->isAllowed( 'deletedhistory' ) &&
725 ( $this->getTitle()->getArticleID() == 0 || $action == 'history' ) ) {
726 $n = $this->getTitle()->isDeleted();
727
728 if ( $n ) {
729 if ( $this->getUser()->isAllowed( 'undelete' ) ) {
730 $msg = 'thisisdeleted';
731 } else {
732 $msg = 'viewdeleted';
733 }
734
735 return $this->msg( $msg )->rawParams(
736 Linker::linkKnown(
737 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
738 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
739 )->text();
740 }
741 }
742
743 return '';
744 }
745
746 /**
747 * @return string
748 */
749 function subPageSubtitle() {
750 $out = $this->getOutput();
751 $subpages = '';
752
753 if ( !wfRunHooks( 'SkinSubPageSubtitle', array( &$subpages, $this, $out ) ) ) {
754 return $subpages;
755 }
756
757 if ( $out->isArticle() && MWNamespace::hasSubpages( $out->getTitle()->getNamespace() ) ) {
758 $ptext = $this->getTitle()->getPrefixedText();
759 if ( preg_match( '/\//', $ptext ) ) {
760 $links = explode( '/', $ptext );
761 array_pop( $links );
762 $c = 0;
763 $growinglink = '';
764 $display = '';
765 $lang = $this->getLanguage();
766
767 foreach ( $links as $link ) {
768 $growinglink .= $link;
769 $display .= $link;
770 $linkObj = Title::newFromText( $growinglink );
771
772 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
773 $getlink = Linker::linkKnown(
774 $linkObj,
775 htmlspecialchars( $display )
776 );
777
778 $c++;
779
780 if ( $c > 1 ) {
781 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
782 } else {
783 $subpages .= '&lt; ';
784 }
785
786 $subpages .= $getlink;
787 $display = '';
788 } else {
789 $display .= '/';
790 }
791 $growinglink .= '/';
792 }
793 }
794 }
795
796 return $subpages;
797 }
798
799 /**
800 * Returns true if the IP should be shown in the header
801 * @return bool
802 */
803 function showIPinHeader() {
804 global $wgShowIPinHeader;
805 return $wgShowIPinHeader && session_id() != '';
806 }
807
808 /**
809 * @return string
810 */
811 function getSearchLink() {
812 $searchPage = SpecialPage::getTitleFor( 'Search' );
813 return $searchPage->getLocalURL();
814 }
815
816 /**
817 * @return string
818 */
819 function escapeSearchLink() {
820 return htmlspecialchars( $this->getSearchLink() );
821 }
822
823 /**
824 * @param string $type
825 * @return string
826 */
827 function getCopyright( $type = 'detect' ) {
828 global $wgRightsPage, $wgRightsUrl, $wgRightsText, $wgContLang;
829
830 if ( $type == 'detect' ) {
831 if ( !$this->isRevisionCurrent()
832 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
833 ) {
834 $type = 'history';
835 } else {
836 $type = 'normal';
837 }
838 }
839
840 if ( $type == 'history' ) {
841 $msg = 'history_copyright';
842 } else {
843 $msg = 'copyright';
844 }
845
846 if ( $wgRightsPage ) {
847 $title = Title::newFromText( $wgRightsPage );
848 $link = Linker::linkKnown( $title, $wgRightsText );
849 } elseif ( $wgRightsUrl ) {
850 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
851 } elseif ( $wgRightsText ) {
852 $link = $wgRightsText;
853 } else {
854 # Give up now
855 return '';
856 }
857
858 // Allow for site and per-namespace customization of copyright notice.
859 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
860 $forContent = true;
861
862 wfRunHooks(
863 'SkinCopyrightFooter',
864 array( $this->getTitle(), $type, &$msg, &$link, &$forContent )
865 );
866
867 return $this->msg( $msg )->rawParams( $link )->text();
868 }
869
870 /**
871 * @return null|string
872 */
873 function getCopyrightIcon() {
874 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgCopyrightIcon;
875
876 $out = '';
877
878 if ( isset( $wgCopyrightIcon ) && $wgCopyrightIcon ) {
879 $out = $wgCopyrightIcon;
880 } elseif ( $wgRightsIcon ) {
881 $icon = htmlspecialchars( $wgRightsIcon );
882
883 if ( $wgRightsUrl ) {
884 $url = htmlspecialchars( $wgRightsUrl );
885 $out .= '<a href="' . $url . '">';
886 }
887
888 $text = htmlspecialchars( $wgRightsText );
889 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
890
891 if ( $wgRightsUrl ) {
892 $out .= '</a>';
893 }
894 }
895
896 return $out;
897 }
898
899 /**
900 * Gets the powered by MediaWiki icon.
901 * @return string
902 */
903 function getPoweredBy() {
904 global $wgStylePath;
905
906 $url = htmlspecialchars( "$wgStylePath/common/images/poweredby_mediawiki_88x31.png" );
907 $text = '<a href="//www.mediawiki.org/"><img src="' . $url
908 . '" height="31" width="88" alt="Powered by MediaWiki" /></a>';
909 wfRunHooks( 'SkinGetPoweredBy', array( &$text, $this ) );
910 return $text;
911 }
912
913 /**
914 * Get the timestamp of the latest revision, formatted in user language
915 *
916 * @return string
917 */
918 protected function lastModified() {
919 $timestamp = $this->getOutput()->getRevisionTimestamp();
920
921 # No cached timestamp, load it from the database
922 if ( $timestamp === null ) {
923 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
924 }
925
926 if ( $timestamp ) {
927 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
928 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
929 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->text();
930 } else {
931 $s = '';
932 }
933
934 if ( wfGetLB()->getLaggedSlaveMode() ) {
935 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->text() . '</strong>';
936 }
937
938 return $s;
939 }
940
941 /**
942 * @param string $align
943 * @return string
944 */
945 function logoText( $align = '' ) {
946 if ( $align != '' ) {
947 $a = " style='float: {$align};'";
948 } else {
949 $a = '';
950 }
951
952 $mp = $this->msg( 'mainpage' )->escaped();
953 $mptitle = Title::newMainPage();
954 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
955
956 $logourl = $this->getLogo();
957 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
958
959 return $s;
960 }
961
962 /**
963 * Renders a $wgFooterIcons icon according to the method's arguments
964 * @param array $icon The icon to build the html for, see $wgFooterIcons
965 * for the format of this array.
966 * @param bool|string $withImage Whether to use the icon's image or output
967 * a text-only footericon.
968 * @return string HTML
969 */
970 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
971 if ( is_string( $icon ) ) {
972 $html = $icon;
973 } else { // Assuming array
974 $url = isset( $icon["url"] ) ? $icon["url"] : null;
975 unset( $icon["url"] );
976 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
977 // do this the lazy way, just pass icon data as an attribute array
978 $html = Html::element( 'img', $icon );
979 } else {
980 $html = htmlspecialchars( $icon["alt"] );
981 }
982 if ( $url ) {
983 $html = Html::rawElement( 'a', array( "href" => $url ), $html );
984 }
985 }
986 return $html;
987 }
988
989 /**
990 * Gets the link to the wiki's main page.
991 * @return string
992 */
993 function mainPageLink() {
994 $s = Linker::linkKnown(
995 Title::newMainPage(),
996 $this->msg( 'mainpage' )->escaped()
997 );
998
999 return $s;
1000 }
1001
1002 /**
1003 * Returns an HTML link for use in the footer
1004 * @param string $desc i18n message key for the link text
1005 * @param string $page i18n message key for the page to link to
1006 * @return string HTML anchor
1007 */
1008 public function footerLink( $desc, $page ) {
1009 // if the link description has been set to "-" in the default language,
1010 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1011 // then it is disabled, for all languages.
1012 return '';
1013 } else {
1014 // Otherwise, we display the link for the user, described in their
1015 // language (which may or may not be the same as the default language),
1016 // but we make the link target be the one site-wide page.
1017 $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1018
1019 return Linker::linkKnown(
1020 $title,
1021 $this->msg( $desc )->escaped()
1022 );
1023 }
1024 }
1025
1026 /**
1027 * Gets the link to the wiki's privacy policy page.
1028 * @return string HTML
1029 */
1030 function privacyLink() {
1031 return $this->footerLink( 'privacy', 'privacypage' );
1032 }
1033
1034 /**
1035 * Gets the link to the wiki's about page.
1036 * @return string HTML
1037 */
1038 function aboutLink() {
1039 return $this->footerLink( 'aboutsite', 'aboutpage' );
1040 }
1041
1042 /**
1043 * Gets the link to the wiki's general disclaimers page.
1044 * @return string HTML
1045 */
1046 function disclaimerLink() {
1047 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1048 }
1049
1050 /**
1051 * Return URL options for the 'edit page' link.
1052 * This may include an 'oldid' specifier, if the current page view is such.
1053 *
1054 * @return array
1055 * @private
1056 */
1057 function editUrlOptions() {
1058 $options = array( 'action' => 'edit' );
1059
1060 if ( !$this->isRevisionCurrent() ) {
1061 $options['oldid'] = intval( $this->getRevisionId() );
1062 }
1063
1064 return $options;
1065 }
1066
1067 /**
1068 * @param User|int $id
1069 * @return bool
1070 */
1071 function showEmailUser( $id ) {
1072 if ( $id instanceof User ) {
1073 $targetUser = $id;
1074 } else {
1075 $targetUser = User::newFromId( $id );
1076 }
1077
1078 # The sending user must have a confirmed email address and the target
1079 # user must have a confirmed email address and allow emails from users.
1080 return $this->getUser()->canSendEmail() &&
1081 $targetUser->canReceiveEmail();
1082 }
1083
1084 /**
1085 * Return a fully resolved style path url to images or styles stored in the common folder.
1086 * This method returns a url resolved using the configured skin style path
1087 * and includes the style version inside of the url.
1088 * @param string $name The name or path of a skin resource file
1089 * @return string The fully resolved style path url including styleversion
1090 */
1091 function getCommonStylePath( $name ) {
1092 global $wgStylePath, $wgStyleVersion;
1093 return "$wgStylePath/common/$name?$wgStyleVersion";
1094 }
1095
1096 /**
1097 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1098 * This method returns a url resolved using the configured skin style path
1099 * and includes the style version inside of the url.
1100 *
1101 * Requires $stylename to be set, otherwise throws MWException.
1102 *
1103 * @param string $name The name or path of a skin resource file
1104 * @return string The fully resolved style path url including styleversion
1105 */
1106 function getSkinStylePath( $name ) {
1107 global $wgStylePath, $wgStyleVersion;
1108
1109 if ( $this->stylename === null ) {
1110 $class = get_class( $this );
1111 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1112 }
1113
1114 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1115 }
1116
1117 /* these are used extensively in SkinTemplate, but also some other places */
1118
1119 /**
1120 * @param string $urlaction
1121 * @return string
1122 */
1123 static function makeMainPageUrl( $urlaction = '' ) {
1124 $title = Title::newMainPage();
1125 self::checkTitle( $title, '' );
1126
1127 return $title->getLocalURL( $urlaction );
1128 }
1129
1130 /**
1131 * Make a URL for a Special Page using the given query and protocol.
1132 *
1133 * If $proto is set to null, make a local URL. Otherwise, make a full
1134 * URL with the protocol specified.
1135 *
1136 * @param string $name Name of the Special page
1137 * @param string $urlaction Query to append
1138 * @param string|null $proto Protocol to use or null for a local URL
1139 * @return string
1140 */
1141 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1142 $title = SpecialPage::getSafeTitleFor( $name );
1143 if ( is_null( $proto ) ) {
1144 return $title->getLocalURL( $urlaction );
1145 } else {
1146 return $title->getFullURL( $urlaction, false, $proto );
1147 }
1148 }
1149
1150 /**
1151 * @param string $name
1152 * @param string $subpage
1153 * @param string $urlaction
1154 * @return string
1155 */
1156 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1157 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1158 return $title->getLocalURL( $urlaction );
1159 }
1160
1161 /**
1162 * @param string $name
1163 * @param string $urlaction
1164 * @return string
1165 */
1166 static function makeI18nUrl( $name, $urlaction = '' ) {
1167 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1168 self::checkTitle( $title, $name );
1169 return $title->getLocalURL( $urlaction );
1170 }
1171
1172 /**
1173 * @param string $name
1174 * @param string $urlaction
1175 * @return string
1176 */
1177 static function makeUrl( $name, $urlaction = '' ) {
1178 $title = Title::newFromText( $name );
1179 self::checkTitle( $title, $name );
1180
1181 return $title->getLocalURL( $urlaction );
1182 }
1183
1184 /**
1185 * If url string starts with http, consider as external URL, else
1186 * internal
1187 * @param string $name
1188 * @return string URL
1189 */
1190 static function makeInternalOrExternalUrl( $name ) {
1191 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1192 return $name;
1193 } else {
1194 return self::makeUrl( $name );
1195 }
1196 }
1197
1198 /**
1199 * this can be passed the NS number as defined in Language.php
1200 * @param string $name
1201 * @param string $urlaction
1202 * @param int $namespace
1203 * @return string
1204 */
1205 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1206 $title = Title::makeTitleSafe( $namespace, $name );
1207 self::checkTitle( $title, $name );
1208
1209 return $title->getLocalURL( $urlaction );
1210 }
1211
1212 /**
1213 * these return an array with the 'href' and boolean 'exists'
1214 * @param string $name
1215 * @param string $urlaction
1216 * @return array
1217 */
1218 static function makeUrlDetails( $name, $urlaction = '' ) {
1219 $title = Title::newFromText( $name );
1220 self::checkTitle( $title, $name );
1221
1222 return array(
1223 'href' => $title->getLocalURL( $urlaction ),
1224 'exists' => $title->getArticleID() != 0,
1225 );
1226 }
1227
1228 /**
1229 * Make URL details where the article exists (or at least it's convenient to think so)
1230 * @param string $name Article name
1231 * @param string $urlaction
1232 * @return array
1233 */
1234 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1235 $title = Title::newFromText( $name );
1236 self::checkTitle( $title, $name );
1237
1238 return array(
1239 'href' => $title->getLocalURL( $urlaction ),
1240 'exists' => true
1241 );
1242 }
1243
1244 /**
1245 * make sure we have some title to operate on
1246 *
1247 * @param Title $title
1248 * @param string $name
1249 */
1250 static function checkTitle( &$title, $name ) {
1251 if ( !is_object( $title ) ) {
1252 $title = Title::newFromText( $name );
1253 if ( !is_object( $title ) ) {
1254 $title = Title::newFromText( '--error: link target missing--' );
1255 }
1256 }
1257 }
1258
1259 /**
1260 * Build an array that represents the sidebar(s), the navigation bar among them.
1261 *
1262 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1263 *
1264 * The format of the returned array is array( heading => content, ... ), where:
1265 * - heading is the heading of a navigation portlet. It is either:
1266 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1267 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1268 * - plain text, which should be HTML-escaped by the skin
1269 * - content is the contents of the portlet. It is either:
1270 * - HTML text (<ul><li>...</li>...</ul>)
1271 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1272 * - (for a magic string as a key, any value)
1273 *
1274 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1275 * and can technically insert anything in here; skin creators are expected to handle
1276 * values described above.
1277 *
1278 * @return array
1279 */
1280 function buildSidebar() {
1281 global $wgMemc, $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1282 wfProfileIn( __METHOD__ );
1283
1284 $key = wfMemcKey( 'sidebar', $this->getLanguage()->getCode() );
1285
1286 if ( $wgEnableSidebarCache ) {
1287 $cachedsidebar = $wgMemc->get( $key );
1288 if ( $cachedsidebar ) {
1289 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$cachedsidebar ) );
1290
1291 wfProfileOut( __METHOD__ );
1292 return $cachedsidebar;
1293 }
1294 }
1295
1296 $bar = array();
1297 $this->addToSidebar( $bar, 'sidebar' );
1298
1299 wfRunHooks( 'SkinBuildSidebar', array( $this, &$bar ) );
1300 if ( $wgEnableSidebarCache ) {
1301 $wgMemc->set( $key, $bar, $wgSidebarCacheExpiry );
1302 }
1303
1304 wfRunHooks( 'SidebarBeforeOutput', array( $this, &$bar ) );
1305
1306 wfProfileOut( __METHOD__ );
1307 return $bar;
1308 }
1309
1310 /**
1311 * Add content from a sidebar system message
1312 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1313 *
1314 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1315 *
1316 * @param array $bar
1317 * @param string $message
1318 */
1319 function addToSidebar( &$bar, $message ) {
1320 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1321 }
1322
1323 /**
1324 * Add content from plain text
1325 * @since 1.17
1326 * @param array $bar
1327 * @param string $text
1328 * @return array
1329 */
1330 function addToSidebarPlain( &$bar, $text ) {
1331 $lines = explode( "\n", $text );
1332
1333 $heading = '';
1334
1335 foreach ( $lines as $line ) {
1336 if ( strpos( $line, '*' ) !== 0 ) {
1337 continue;
1338 }
1339 $line = rtrim( $line, "\r" ); // for Windows compat
1340
1341 if ( strpos( $line, '**' ) !== 0 ) {
1342 $heading = trim( $line, '* ' );
1343 if ( !array_key_exists( $heading, $bar ) ) {
1344 $bar[$heading] = array();
1345 }
1346 } else {
1347 $line = trim( $line, '* ' );
1348
1349 if ( strpos( $line, '|' ) !== false ) { // sanity check
1350 $line = MessageCache::singleton()->transform( $line, false, null, $this->getTitle() );
1351 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1352 if ( count( $line ) !== 2 ) {
1353 // Second sanity check, could be hit by people doing
1354 // funky stuff with parserfuncs... (bug 33321)
1355 continue;
1356 }
1357
1358 $extraAttribs = array();
1359
1360 $msgLink = $this->msg( $line[0] )->inContentLanguage();
1361 if ( $msgLink->exists() ) {
1362 $link = $msgLink->text();
1363 if ( $link == '-' ) {
1364 continue;
1365 }
1366 } else {
1367 $link = $line[0];
1368 }
1369 $msgText = $this->msg( $line[1] );
1370 if ( $msgText->exists() ) {
1371 $text = $msgText->text();
1372 } else {
1373 $text = $line[1];
1374 }
1375
1376 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1377 $href = $link;
1378
1379 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1380 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1381 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1382 $extraAttribs['rel'] = 'nofollow';
1383 }
1384
1385 global $wgExternalLinkTarget;
1386 if ( $wgExternalLinkTarget ) {
1387 $extraAttribs['target'] = $wgExternalLinkTarget;
1388 }
1389 } else {
1390 $title = Title::newFromText( $link );
1391
1392 if ( $title ) {
1393 $title = $title->fixSpecialName();
1394 $href = $title->getLinkURL();
1395 } else {
1396 $href = 'INVALID-TITLE';
1397 }
1398 }
1399
1400 $bar[$heading][] = array_merge( array(
1401 'text' => $text,
1402 'href' => $href,
1403 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1404 'active' => false
1405 ), $extraAttribs );
1406 } else {
1407 continue;
1408 }
1409 }
1410 }
1411
1412 return $bar;
1413 }
1414
1415 /**
1416 * This function previously controlled whether the 'mediawiki.legacy.wikiprintable' module
1417 * should be loaded by OutputPage. That module no longer exists and the return value of this
1418 * method is ignored.
1419 *
1420 * If your skin doesn't provide its own print styles, the 'mediawiki.legacy.commonPrint' module
1421 * can be used instead (SkinTemplate-based skins do it automatically).
1422 *
1423 * @deprecated since 1.22
1424 * @return bool
1425 */
1426 public function commonPrintStylesheet() {
1427 wfDeprecated( __METHOD__, '1.22' );
1428 return false;
1429 }
1430
1431 /**
1432 * Gets new talk page messages for the current user and returns an
1433 * appropriate alert message (or an empty string if there are no messages)
1434 * @return string
1435 */
1436 function getNewtalks() {
1437
1438 $newMessagesAlert = '';
1439 $user = $this->getUser();
1440 $newtalks = $user->getNewMessageLinks();
1441 $out = $this->getOutput();
1442
1443 // Allow extensions to disable or modify the new messages alert
1444 if ( !wfRunHooks( 'GetNewMessagesAlert', array( &$newMessagesAlert, $newtalks, $user, $out ) ) ) {
1445 return '';
1446 }
1447 if ( $newMessagesAlert ) {
1448 return $newMessagesAlert;
1449 }
1450
1451 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1452 $uTalkTitle = $user->getTalkPage();
1453 $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null;
1454 $nofAuthors = 0;
1455 if ( $lastSeenRev !== null ) {
1456 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1457 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1458 if ( $latestRev !== null ) {
1459 // Singular if only 1 unseen revision, plural if several unseen revisions.
1460 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1461 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1462 $lastSeenRev, $latestRev, 10, 'include_new' );
1463 }
1464 } else {
1465 // Singular if no revision -> diff link will show latest change only in any case
1466 $plural = false;
1467 }
1468 $plural = $plural ? 999 : 1;
1469 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1470 // the number of revisions or authors is not necessarily the same as the number of
1471 // "messages".
1472 $newMessagesLink = Linker::linkKnown(
1473 $uTalkTitle,
1474 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1475 array(),
1476 array( 'redirect' => 'no' )
1477 );
1478
1479 $newMessagesDiffLink = Linker::linkKnown(
1480 $uTalkTitle,
1481 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1482 array(),
1483 $lastSeenRev !== null
1484 ? array( 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' )
1485 : array( 'diff' => 'cur' )
1486 );
1487
1488 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1489 $newMessagesAlert = $this->msg(
1490 'youhavenewmessagesfromusers',
1491 $newMessagesLink,
1492 $newMessagesDiffLink
1493 )->numParams( $nofAuthors, $plural );
1494 } else {
1495 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1496 $newMessagesAlert = $this->msg(
1497 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1498 $newMessagesLink,
1499 $newMessagesDiffLink
1500 )->numParams( $plural );
1501 }
1502 $newMessagesAlert = $newMessagesAlert->text();
1503 # Disable Squid cache
1504 $out->setSquidMaxage( 0 );
1505 } elseif ( count( $newtalks ) ) {
1506 $sep = $this->msg( 'newtalkseparator' )->escaped();
1507 $msgs = array();
1508
1509 foreach ( $newtalks as $newtalk ) {
1510 $msgs[] = Xml::element(
1511 'a',
1512 array( 'href' => $newtalk['link'] ), $newtalk['wiki']
1513 );
1514 }
1515 $parts = implode( $sep, $msgs );
1516 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1517 $out->setSquidMaxage( 0 );
1518 }
1519
1520 return $newMessagesAlert;
1521 }
1522
1523 /**
1524 * Get a cached notice
1525 *
1526 * @param string $name Message name, or 'default' for $wgSiteNotice
1527 * @return string HTML fragment
1528 */
1529 private function getCachedNotice( $name ) {
1530 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1531
1532 wfProfileIn( __METHOD__ );
1533
1534 $needParse = false;
1535
1536 if ( $name === 'default' ) {
1537 // special case
1538 global $wgSiteNotice;
1539 $notice = $wgSiteNotice;
1540 if ( empty( $notice ) ) {
1541 wfProfileOut( __METHOD__ );
1542 return false;
1543 }
1544 } else {
1545 $msg = $this->msg( $name )->inContentLanguage();
1546 if ( $msg->isDisabled() ) {
1547 wfProfileOut( __METHOD__ );
1548 return false;
1549 }
1550 $notice = $msg->plain();
1551 }
1552
1553 // Use the extra hash appender to let eg SSL variants separately cache.
1554 $key = wfMemcKey( $name . $wgRenderHashAppend );
1555 $cachedNotice = $parserMemc->get( $key );
1556 if ( is_array( $cachedNotice ) ) {
1557 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1558 $notice = $cachedNotice['html'];
1559 } else {
1560 $needParse = true;
1561 }
1562 } else {
1563 $needParse = true;
1564 }
1565
1566 if ( $needParse ) {
1567 $parsed = $this->getOutput()->parse( $notice );
1568 $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1569 $notice = $parsed;
1570 }
1571
1572 $notice = Html::rawElement( 'div', array( 'id' => 'localNotice',
1573 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ), $notice );
1574 wfProfileOut( __METHOD__ );
1575 return $notice;
1576 }
1577
1578 /**
1579 * Get a notice based on page's namespace
1580 *
1581 * @return string HTML fragment
1582 */
1583 function getNamespaceNotice() {
1584 wfProfileIn( __METHOD__ );
1585
1586 $key = 'namespacenotice-' . $this->getTitle()->getNsText();
1587 $namespaceNotice = $this->getCachedNotice( $key );
1588 if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
1589 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
1590 } else {
1591 $namespaceNotice = '';
1592 }
1593
1594 wfProfileOut( __METHOD__ );
1595 return $namespaceNotice;
1596 }
1597
1598 /**
1599 * Get the site notice
1600 *
1601 * @return string HTML fragment
1602 */
1603 function getSiteNotice() {
1604 wfProfileIn( __METHOD__ );
1605 $siteNotice = '';
1606
1607 if ( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice, $this ) ) ) {
1608 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1609 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1610 } else {
1611 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1612 if ( !$anonNotice ) {
1613 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1614 } else {
1615 $siteNotice = $anonNotice;
1616 }
1617 }
1618 if ( !$siteNotice ) {
1619 $siteNotice = $this->getCachedNotice( 'default' );
1620 }
1621 }
1622
1623 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice, $this ) );
1624 wfProfileOut( __METHOD__ );
1625 return $siteNotice;
1626 }
1627
1628 /**
1629 * Create a section edit link. This supersedes editSectionLink() and
1630 * editSectionLinkForOther().
1631 *
1632 * @param Title $nt The title being linked to (may not be the same as
1633 * the current page, if the section is included from a template)
1634 * @param string $section The designation of the section being pointed to,
1635 * to be included in the link, like "&section=$section"
1636 * @param string $tooltip The tooltip to use for the link: will be escaped
1637 * and wrapped in the 'editsectionhint' message
1638 * @param string $lang Language code
1639 * @return string HTML to use for edit link
1640 */
1641 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1642 // HTML generated here should probably have userlangattributes
1643 // added to it for LTR text on RTL pages
1644
1645 $lang = wfGetLangObj( $lang );
1646
1647 $attribs = array();
1648 if ( !is_null( $tooltip ) ) {
1649 # Bug 25462: undo double-escaping.
1650 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1651 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1652 ->inLanguage( $lang )->text();
1653 }
1654 $link = Linker::link( $nt, wfMessage( 'editsection' )->inLanguage( $lang )->text(),
1655 $attribs,
1656 array( 'action' => 'edit', 'section' => $section ),
1657 array( 'noclasses', 'known' )
1658 );
1659
1660 # Add the brackets and the span and run the hook.
1661 $result = '<span class="mw-editsection">'
1662 . '<span class="mw-editsection-bracket">[</span>'
1663 . $link
1664 . '<span class="mw-editsection-bracket">]</span>'
1665 . '</span>';
1666
1667 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1668 return $result;
1669 }
1670
1671 /**
1672 * Use PHP's magic __call handler to intercept legacy calls to the linker
1673 * for backwards compatibility.
1674 *
1675 * @param string $fname Name of called method
1676 * @param array $args Arguments to the method
1677 * @throws MWException
1678 * @return mixed
1679 */
1680 function __call( $fname, $args ) {
1681 $realFunction = array( 'Linker', $fname );
1682 if ( is_callable( $realFunction ) ) {
1683 wfDeprecated( get_class( $this ) . '::' . $fname, '1.21' );
1684 return call_user_func_array( $realFunction, $args );
1685 } else {
1686 $className = get_class( $this );
1687 throw new MWException( "Call to undefined method $className::$fname" );
1688 }
1689 }
1690
1691 }