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