(bug 41368) Added category information to InfoAction.
[lhc/web/wiklou.git] / includes / actions / InfoAction.php
1 <?php
2 /**
3 * Displays information about a page.
4 *
5 * Copyright © 2011 Alexandre Emsenhuber
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20 *
21 * @file
22 * @ingroup Actions
23 */
24
25 class InfoAction extends FormlessAction {
26 /**
27 * Returns the name of the action this object responds to.
28 *
29 * @return string lowercase
30 */
31 public function getName() {
32 return 'info';
33 }
34
35 /**
36 * Whether this action can still be executed by a blocked user.
37 *
38 * @return bool
39 */
40 public function requiresUnblock() {
41 return false;
42 }
43
44 /**
45 * Whether this action requires the wiki not to be locked.
46 *
47 * @return bool
48 */
49 public function requiresWrite() {
50 return false;
51 }
52
53 /**
54 * Shows page information on GET request.
55 *
56 * @return string Page information that will be added to the output
57 */
58 public function onView() {
59 $content = '';
60
61 // Validate revision
62 $oldid = $this->page->getOldID();
63 if ( $oldid ) {
64 $revision = $this->page->getRevisionFetched();
65
66 // Revision is missing
67 if ( $revision === null ) {
68 return $this->msg( 'missing-revision', $oldid )->parse();
69 }
70
71 // Revision is not current
72 if ( !$revision->isCurrent() ) {
73 return $this->msg( 'pageinfo-not-current' )->plain();
74 }
75 }
76
77 // Page header
78 if ( !$this->msg( 'pageinfo-header' )->isDisabled() ) {
79 $content .= $this->msg( 'pageinfo-header' )->parse();
80 }
81
82 // Hide "This page is a member of # hidden categories" explanation
83 $content .= Html::element( 'style', array(),
84 '.mw-hiddenCategoriesExplanation { display: none; }' );
85
86 // Hide "Templates used on this page" explanation
87 $content .= Html::element( 'style', array(),
88 '.mw-templatesUsedExplanation { display: none; }' );
89
90 // Get page information
91 $pageInfo = $this->pageInfo();
92
93 // Allow extensions to add additional information
94 wfRunHooks( 'InfoAction', array( $this->getContext(), &$pageInfo ) );
95
96 // Render page information
97 foreach ( $pageInfo as $header => $infoTable ) {
98 $content .= $this->makeHeader( $this->msg( "pageinfo-${header}" )->escaped() );
99 $table = '';
100 foreach ( $infoTable as $infoRow ) {
101 $name = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->escaped() : $infoRow[0];
102 $value = ( $infoRow[1] instanceof Message ) ? $infoRow[1]->escaped() : $infoRow[1];
103 $table = $this->addRow( $table, $name, $value );
104 }
105 $content = $this->addTable( $content, $table );
106 }
107
108 // Page footer
109 if ( !$this->msg( 'pageinfo-footer' )->isDisabled() ) {
110 $content .= $this->msg( 'pageinfo-footer' )->parse();
111 }
112
113 // Page credits
114 /*if ( $this->page->exists() ) {
115 $content .= Html::rawElement( 'div', array( 'id' => 'mw-credits' ), $this->getContributors() );
116 }*/
117
118 return $content;
119 }
120
121 /**
122 * Creates a header that can be added to the output.
123 *
124 * @param $header The header text.
125 * @return string The HTML.
126 */
127 protected function makeHeader( $header ) {
128 global $wgParser;
129 $spanAttribs = array( 'class' => 'mw-headline', 'id' => $wgParser->guessSectionNameFromWikiText( $header ) );
130 return Html::rawElement( 'h2', array(), Html::element( 'span', $spanAttribs, $header ) );
131 }
132
133 /**
134 * Adds a row to a table that will be added to the content.
135 *
136 * @param $table string The table that will be added to the content
137 * @param $name string The name of the row
138 * @param $value string The value of the row
139 * @return string The table with the row added
140 */
141 protected function addRow( $table, $name, $value ) {
142 return $table . Html::rawElement( 'tr', array(),
143 Html::rawElement( 'td', array( 'style' => 'vertical-align: top;' ), $name ) .
144 Html::rawElement( 'td', array(), $value )
145 );
146 }
147
148 /**
149 * Adds a table to the content that will be added to the output.
150 *
151 * @param $content string The content that will be added to the output
152 * @param $table string The table
153 * @return string The content with the table added
154 */
155 protected function addTable( $content, $table ) {
156 return $content . Html::rawElement( 'table', array( 'class' => 'wikitable mw-page-info' ),
157 $table );
158 }
159
160 /**
161 * Returns page information in an easily-manipulated format. Array keys are used so extensions
162 * may add additional information in arbitrary positions. Array values are arrays with one
163 * element to be rendered as a header, arrays with two elements to be rendered as a table row.
164 *
165 * @return array
166 */
167 protected function pageInfo() {
168 global $wgContLang, $wgRCMaxAge, $wgMemc, $wgUnwatchedPageThreshold;
169
170 $user = $this->getUser();
171 $lang = $this->getLanguage();
172 $title = $this->getTitle();
173 $id = $title->getArticleID();
174
175 $memcKey = wfMemcKey( 'infoaction', $title->getPrefixedText(), $this->page->getLatest() );
176 $pageCounts = $wgMemc->get( $memcKey );
177 if ( $pageCounts === false ) {
178 // Get page information that would be too "expensive" to retrieve by normal means
179 $pageCounts = self::pageCounts( $title );
180
181 $wgMemc->set( $memcKey, $pageCounts );
182 }
183
184 // Get page properties
185 $dbr = wfGetDB( DB_SLAVE );
186 $result = $dbr->select(
187 'page_props',
188 array( 'pp_propname', 'pp_value' ),
189 array( 'pp_page' => $id ),
190 __METHOD__
191 );
192
193 $pageProperties = array();
194 foreach ( $result as $row ) {
195 $pageProperties[$row->pp_propname] = $row->pp_value;
196 }
197
198 // Basic information
199 $pageInfo = array();
200 $pageInfo['header-basic'] = array();
201
202 // Display title
203 $displayTitle = $title->getPrefixedText();
204 if ( !empty( $pageProperties['displaytitle'] ) ) {
205 $displayTitle = $pageProperties['displaytitle'];
206 }
207
208 $pageInfo['header-basic'][] = array(
209 $this->msg( 'pageinfo-display-title' ), $displayTitle
210 );
211
212 // Is it a redirect? If so, where to?
213 if ( $title->isRedirect() ) {
214 $pageInfo['header-basic'][] = array(
215 $this->msg( 'pageinfo-redirectsto' ),
216 Linker::link( $this->page->getRedirectTarget() ) .
217 $this->msg( 'word-separator' )->text() .
218 $this->msg( 'parentheses', Linker::link(
219 $this->page->getRedirectTarget(),
220 $this->msg( 'pageinfo-redirectsto-info' )->escaped(),
221 array(),
222 array( 'action' => 'info' )
223 ) )->text()
224 );
225 }
226
227 // Default sort key
228 $sortKey = $title->getCategorySortKey();
229 if ( !empty( $pageProperties['defaultsort'] ) ) {
230 $sortKey = $pageProperties['defaultsort'];
231 }
232
233 $pageInfo['header-basic'][] = array( $this->msg( 'pageinfo-default-sort' ), $sortKey );
234
235 // Page length (in bytes)
236 $pageInfo['header-basic'][] = array(
237 $this->msg( 'pageinfo-length' ), $lang->formatNum( $title->getLength() )
238 );
239
240 // Page ID (number not localised, as it's a database ID)
241 $pageInfo['header-basic'][] = array( $this->msg( 'pageinfo-article-id' ), $id );
242
243 // Language in which the page content is (supposed to be) written
244 $pageLang = $title->getPageLanguage()->getCode();
245 $pageInfo['header-basic'][] = array( $this->msg( 'pageinfo-language' ),
246 Language::fetchLanguageName( $pageLang, $lang->getCode() )
247 . ' ' . $this->msg( 'parentheses', $pageLang ) );
248
249 // Search engine status
250 $pOutput = new ParserOutput();
251 if ( isset( $pageProperties['noindex'] ) ) {
252 $pOutput->setIndexPolicy( 'noindex' );
253 }
254
255 // Use robot policy logic
256 $policy = $this->page->getRobotPolicy( 'view', $pOutput );
257 $pageInfo['header-basic'][] = array(
258 $this->msg( 'pageinfo-robot-policy' ), $this->msg( "pageinfo-robot-${policy['index']}" )
259 );
260
261 if ( isset( $pageCounts['views'] ) ) {
262 // Number of views
263 $pageInfo['header-basic'][] = array(
264 $this->msg( 'pageinfo-views' ), $lang->formatNum( $pageCounts['views'] )
265 );
266 }
267
268 if (
269 $user->isAllowed( 'unwatchedpages' ) ||
270 ( $wgUnwatchedPageThreshold !== false &&
271 $pageCounts['watchers'] >= $wgUnwatchedPageThreshold )
272 ) {
273 // Number of page watchers
274 $pageInfo['header-basic'][] = array(
275 $this->msg( 'pageinfo-watchers' ), $lang->formatNum( $pageCounts['watchers'] )
276 );
277 }
278
279 // Redirects to this page
280 $whatLinksHere = SpecialPage::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
281 $pageInfo['header-basic'][] = array(
282 Linker::link(
283 $whatLinksHere,
284 $this->msg( 'pageinfo-redirects-name' )->escaped(),
285 array(),
286 array( 'hidelinks' => 1, 'hidetrans' => 1 )
287 ),
288 $this->msg( 'pageinfo-redirects-value' )
289 ->numParams( count( $title->getRedirectsHere() ) )
290 );
291
292 // Is it counted as a content page?
293 if ( $this->page->isCountable() ) {
294 $pageInfo['header-basic'][] = array(
295 $this->msg( 'pageinfo-contentpage' ),
296 $this->msg( 'pageinfo-contentpage-yes' )
297 );
298 }
299
300 // Subpages of this page, if subpages are enabled for the current NS
301 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
302 $prefixIndex = SpecialPage::getTitleFor( 'Prefixindex', $title->getPrefixedText() . '/' );
303 $pageInfo['header-basic'][] = array(
304 Linker::link( $prefixIndex, $this->msg( 'pageinfo-subpages-name' )->escaped() ),
305 $this->msg( 'pageinfo-subpages-value' )
306 ->numParams(
307 $pageCounts['subpages']['total'],
308 $pageCounts['subpages']['redirects'],
309 $pageCounts['subpages']['nonredirects'] )
310 );
311 }
312
313 if ( $title->inNamespace( NS_CATEGORY ) ) {
314 $category = Category::newFromTitle( $title );
315 $pageInfo['category-info'] = array(
316 array(
317 $this->msg( 'pageinfo-category-pages' ),
318 $lang->formatNum( $category->getPageCount() )
319 ),
320 array(
321 $this->msg( 'pageinfo-category-subcats' ),
322 $lang->formatNum( $category->getSubcatCount() )
323 ),
324 array(
325 $this->msg( 'pageinfo-category-files' ),
326 $lang->formatNum( $category->getFileCount() )
327 )
328 );
329 }
330
331 // Page protection
332 $pageInfo['header-restrictions'] = array();
333
334 // Is this page effected by the cascading protection of something which includes it?
335 if ( $title->isCascadeProtected() ) {
336 $cascadingFrom = '';
337 $sources = $title->getCascadeProtectionSources(); // Array deferencing is in PHP 5.4 :(
338
339 foreach ( $sources[0] as $sourceTitle ) {
340 $cascadingFrom .= Html::rawElement( 'li', array(), Linker::linkKnown( $sourceTitle ) );
341 }
342
343 $cascadingFrom = Html::rawElement( 'ul', array(), $cascadingFrom );
344 $pageInfo['header-restrictions'][] = array(
345 $this->msg( 'pageinfo-protect-cascading-from' ),
346 $cascadingFrom
347 );
348 }
349
350 // Is out protection set to cascade to other pages?
351 if ( $title->areRestrictionsCascading() ) {
352 $pageInfo['header-restrictions'][] = array(
353 $this->msg( 'pageinfo-protect-cascading' ),
354 $this->msg( 'pageinfo-protect-cascading-yes' )
355 );
356 }
357
358 // Page protection
359 foreach ( $title->getRestrictionTypes() as $restrictionType ) {
360 $protectionLevel = implode( ', ', $title->getRestrictions( $restrictionType ) );
361
362 if ( $protectionLevel == '' ) {
363 // Allow all users
364 $message = $this->msg( 'protect-default' )->escaped();
365 } else {
366 // Administrators only
367 $message = $this->msg( "protect-level-$protectionLevel" );
368 if ( $message->isDisabled() ) {
369 // Require "$1" permission
370 $message = $this->msg( "protect-fallback", $protectionLevel )->parse();
371 } else {
372 $message = $message->escaped();
373 }
374 }
375
376 $pageInfo['header-restrictions'][] = array(
377 $this->msg( "restriction-$restrictionType" ), $message
378 );
379 }
380
381 if ( !$this->page->exists() ) {
382 return $pageInfo;
383 }
384
385 // Edit history
386 $pageInfo['header-edits'] = array();
387
388 $firstRev = $this->page->getOldestRevision();
389
390 // Page creator
391 $pageInfo['header-edits'][] = array(
392 $this->msg( 'pageinfo-firstuser' ),
393 Linker::revUserTools( $firstRev )
394 );
395
396 // Date of page creation
397 $pageInfo['header-edits'][] = array(
398 $this->msg( 'pageinfo-firsttime' ),
399 Linker::linkKnown(
400 $title,
401 $lang->userTimeAndDate( $firstRev->getTimestamp(), $user ),
402 array(),
403 array( 'oldid' => $firstRev->getId() )
404 )
405 );
406
407 // Latest editor
408 $pageInfo['header-edits'][] = array(
409 $this->msg( 'pageinfo-lastuser' ),
410 Linker::revUserTools( $this->page->getRevision() )
411 );
412
413 // Date of latest edit
414 $pageInfo['header-edits'][] = array(
415 $this->msg( 'pageinfo-lasttime' ),
416 Linker::linkKnown(
417 $title,
418 $lang->userTimeAndDate( $this->page->getTimestamp(), $user ),
419 array(),
420 array( 'oldid' => $this->page->getLatest() )
421 )
422 );
423
424 // Total number of edits
425 $pageInfo['header-edits'][] = array(
426 $this->msg( 'pageinfo-edits' ), $lang->formatNum( $pageCounts['edits'] )
427 );
428
429 // Total number of distinct authors
430 $pageInfo['header-edits'][] = array(
431 $this->msg( 'pageinfo-authors' ), $lang->formatNum( $pageCounts['authors'] )
432 );
433
434 // Recent number of edits (within past 30 days)
435 $pageInfo['header-edits'][] = array(
436 $this->msg( 'pageinfo-recent-edits', $lang->formatDuration( $wgRCMaxAge ) ),
437 $lang->formatNum( $pageCounts['recent_edits'] )
438 );
439
440 // Recent number of distinct authors
441 $pageInfo['header-edits'][] = array(
442 $this->msg( 'pageinfo-recent-authors' ), $lang->formatNum( $pageCounts['recent_authors'] )
443 );
444
445 // Array of MagicWord objects
446 $magicWords = MagicWord::getDoubleUnderscoreArray();
447
448 // Array of magic word IDs
449 $wordIDs = $magicWords->names;
450
451 // Array of IDs => localized magic words
452 $localizedWords = $wgContLang->getMagicWords();
453
454 $listItems = array();
455 foreach ( $pageProperties as $property => $value ) {
456 if ( in_array( $property, $wordIDs ) ) {
457 $listItems[] = Html::element( 'li', array(), $localizedWords[$property][1] );
458 }
459 }
460
461 $localizedList = Html::rawElement( 'ul', array(), implode( '', $listItems ) );
462 $hiddenCategories = $this->page->getHiddenCategories();
463 $transcludedTemplates = $title->getTemplateLinksFrom();
464
465 if ( count( $listItems ) > 0
466 || count( $hiddenCategories ) > 0
467 || count( $transcludedTemplates ) > 0 ) {
468 // Page properties
469 $pageInfo['header-properties'] = array();
470
471 // Magic words
472 if ( count( $listItems ) > 0 ) {
473 $pageInfo['header-properties'][] = array(
474 $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
475 $localizedList
476 );
477 }
478
479 // Hidden categories
480 if ( count( $hiddenCategories ) > 0 ) {
481 $pageInfo['header-properties'][] = array(
482 $this->msg( 'pageinfo-hidden-categories' )
483 ->numParams( count( $hiddenCategories ) ),
484 Linker::formatHiddenCategories( $hiddenCategories )
485 );
486 }
487
488 // Transcluded templates
489 if ( count( $transcludedTemplates ) > 0 ) {
490 $pageInfo['header-properties'][] = array(
491 $this->msg( 'pageinfo-templates' )
492 ->numParams( count( $transcludedTemplates ) ),
493 Linker::formatTemplates( $transcludedTemplates )
494 );
495 }
496 }
497
498 return $pageInfo;
499 }
500
501 /**
502 * Returns page counts that would be too "expensive" to retrieve by normal means.
503 *
504 * @param Title $title Title to get counts for
505 * @return array
506 */
507 protected static function pageCounts( Title $title ) {
508 global $wgRCMaxAge, $wgDisableCounters;
509
510 wfProfileIn( __METHOD__ );
511 $id = $title->getArticleID();
512
513 $dbr = wfGetDB( DB_SLAVE );
514 $result = array();
515
516 if ( !$wgDisableCounters ) {
517 // Number of views
518 $views = (int) $dbr->selectField(
519 'page',
520 'page_counter',
521 array( 'page_id' => $id ),
522 __METHOD__
523 );
524 $result['views'] = $views;
525 }
526
527 // Number of page watchers
528 $watchers = (int) $dbr->selectField(
529 'watchlist',
530 'COUNT(*)',
531 array(
532 'wl_namespace' => $title->getNamespace(),
533 'wl_title' => $title->getDBkey(),
534 ),
535 __METHOD__
536 );
537 $result['watchers'] = $watchers;
538
539 // Total number of edits
540 $edits = (int) $dbr->selectField(
541 'revision',
542 'COUNT(rev_page)',
543 array( 'rev_page' => $id ),
544 __METHOD__
545 );
546 $result['edits'] = $edits;
547
548 // Total number of distinct authors
549 $authors = (int) $dbr->selectField(
550 'revision',
551 'COUNT(DISTINCT rev_user_text)',
552 array( 'rev_page' => $id ),
553 __METHOD__
554 );
555 $result['authors'] = $authors;
556
557 // "Recent" threshold defined by $wgRCMaxAge
558 $threshold = $dbr->timestamp( time() - $wgRCMaxAge );
559
560 // Recent number of edits
561 $edits = (int) $dbr->selectField(
562 'revision',
563 'COUNT(rev_page)',
564 array(
565 'rev_page' => $id ,
566 "rev_timestamp >= $threshold"
567 ),
568 __METHOD__
569 );
570 $result['recent_edits'] = $edits;
571
572 // Recent number of distinct authors
573 $authors = (int) $dbr->selectField(
574 'revision',
575 'COUNT(DISTINCT rev_user_text)',
576 array(
577 'rev_page' => $id,
578 "rev_timestamp >= $threshold"
579 ),
580 __METHOD__
581 );
582 $result['recent_authors'] = $authors;
583
584 // Subpages (if enabled)
585 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
586 $conds = array( 'page_namespace' => $title->getNamespace() );
587 $conds[] = 'page_title ' . $dbr->buildLike( $title->getDBkey() . '/', $dbr->anyString() );
588
589 // Subpages of this page (redirects)
590 $conds['page_is_redirect'] = 1;
591 $result['subpages']['redirects'] = (int) $dbr->selectField(
592 'page',
593 'COUNT(page_id)',
594 $conds,
595 __METHOD__ );
596
597 // Subpages of this page (non-redirects)
598 $conds['page_is_redirect'] = 0;
599 $result['subpages']['nonredirects'] = (int) $dbr->selectField(
600 'page',
601 'COUNT(page_id)',
602 $conds,
603 __METHOD__
604 );
605
606 // Subpages of this page (total)
607 $result['subpages']['total'] = $result['subpages']['redirects']
608 + $result['subpages']['nonredirects'];
609 }
610
611 wfProfileOut( __METHOD__ );
612 return $result;
613 }
614
615 /**
616 * Returns the name that goes in the "<h1>" page title.
617 *
618 * @return string
619 */
620 protected function getPageTitle() {
621 return $this->msg( 'pageinfo-title', $this->getTitle()->getPrefixedText() )->text();
622 }
623
624 /**
625 * Get a list of contributors of $article
626 * @return string: html
627 */
628 protected function getContributors() {
629 global $wgHiddenPrefs;
630
631 $contributors = $this->page->getContributors();
632 $real_names = array();
633 $user_names = array();
634 $anon_ips = array();
635
636 # Sift for real versus user names
637 foreach ( $contributors as $user ) {
638 $page = $user->isAnon()
639 ? SpecialPage::getTitleFor( 'Contributions', $user->getName() )
640 : $user->getUserPage();
641
642 if ( $user->getID() == 0 ) {
643 $anon_ips[] = Linker::link( $page, htmlspecialchars( $user->getName() ) );
644 } elseif ( !in_array( 'realname', $wgHiddenPrefs ) && $user->getRealName() ) {
645 $real_names[] = Linker::link( $page, htmlspecialchars( $user->getRealName() ) );
646 } else {
647 $user_names[] = Linker::link( $page, htmlspecialchars( $user->getName() ) );
648 }
649 }
650
651 $lang = $this->getLanguage();
652
653 $real = $lang->listToText( $real_names );
654
655 # "ThisSite user(s) A, B and C"
656 if ( count( $user_names ) ) {
657 $user = $this->msg( 'siteusers' )->rawParams( $lang->listToText( $user_names ) )->params(
658 count( $user_names ) )->escaped();
659 } else {
660 $user = false;
661 }
662
663 if ( count( $anon_ips ) ) {
664 $anon = $this->msg( 'anonusers' )->rawParams( $lang->listToText( $anon_ips ) )->params(
665 count( $anon_ips ) )->escaped();
666 } else {
667 $anon = false;
668 }
669
670 # This is the big list, all mooshed together. We sift for blank strings
671 $fulllist = array();
672 foreach ( array( $real, $user, $anon ) as $s ) {
673 if ( $s !== '' ) {
674 array_push( $fulllist, $s );
675 }
676 }
677
678 $count = count( $fulllist );
679 # "Based on work by ..."
680 return $count
681 ? $this->msg( 'othercontribs' )->rawParams(
682 $lang->listToText( $fulllist ) )->params( $count )->escaped()
683 : '';
684 }
685
686 /**
687 * Returns the description that goes below the "<h1>" tag.
688 *
689 * @return string
690 */
691 protected function getDescription() {
692 return '';
693 }
694 }