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