(bug 39490) Add caching 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;
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->getRevision()->getId() );
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 ( $user->isAllowed( 'unwatchedpages' ) ) {
269 // Number of page watchers
270 $pageInfo['header-basic'][] = array(
271 $this->msg( 'pageinfo-watchers' ), $lang->formatNum( $pageCounts['watchers'] )
272 );
273 }
274
275 // Redirects to this page
276 $whatLinksHere = SpecialPage::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
277 $pageInfo['header-basic'][] = array(
278 Linker::link(
279 $whatLinksHere,
280 $this->msg( 'pageinfo-redirects-name' )->escaped(),
281 array(),
282 array( 'hidelinks' => 1, 'hidetrans' => 1 )
283 ),
284 $this->msg( 'pageinfo-redirects-value' )
285 ->numParams( count( $title->getRedirectsHere() ) )
286 );
287
288 // Is it counted as a content page?
289 if ( $this->page->isCountable() ) {
290 $pageInfo['header-basic'][] = array(
291 $this->msg( 'pageinfo-contentpage' ),
292 $this->msg( 'pageinfo-contentpage-yes' )
293 );
294 }
295
296 // Subpages of this page, if subpages are enabled for the current NS
297 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
298 $prefixIndex = SpecialPage::getTitleFor( 'Prefixindex', $title->getPrefixedText() . '/' );
299 $pageInfo['header-basic'][] = array(
300 Linker::link( $prefixIndex, $this->msg( 'pageinfo-subpages-name' )->escaped() ),
301 $this->msg( 'pageinfo-subpages-value' )
302 ->numParams(
303 $pageCounts['subpages']['total'],
304 $pageCounts['subpages']['redirects'],
305 $pageCounts['subpages']['nonredirects'] )
306 );
307 }
308
309 // Page protection
310 $pageInfo['header-restrictions'] = array();
311
312 // Is this page effected by the cascading protection of something which includes it?
313 if ( $title->isCascadeProtected() ) {
314 $cascadingFrom = '';
315 $sources = $title->getCascadeProtectionSources(); // Array deferencing is in PHP 5.4 :(
316
317 foreach ( $sources[0] as $sourceTitle ) {
318 $cascadingFrom .= Html::rawElement( 'li', array(), Linker::linkKnown( $sourceTitle ) );
319 }
320
321 $cascadingFrom = Html::rawElement( 'ul', array(), $cascadingFrom );
322 $pageInfo['header-restrictions'][] = array(
323 $this->msg( 'pageinfo-protect-cascading-from' ),
324 $cascadingFrom
325 );
326 }
327
328 // Is out protection set to cascade to other pages?
329 if ( $title->areRestrictionsCascading() ) {
330 $pageInfo['header-restrictions'][] = array(
331 $this->msg( 'pageinfo-protect-cascading' ),
332 $this->msg( 'pageinfo-protect-cascading-yes' )
333 );
334 }
335
336 // Page protection
337 foreach ( $title->getRestrictionTypes() as $restrictionType ) {
338 $protectionLevel = implode( ', ', $title->getRestrictions( $restrictionType ) );
339
340 if ( $protectionLevel == '' ) {
341 // Allow all users
342 $message = $this->msg( 'protect-default' )->escaped();
343 } else {
344 // Administrators only
345 $message = $this->msg( "protect-level-$protectionLevel" );
346 if ( $message->isDisabled() ) {
347 // Require "$1" permission
348 $message = $this->msg( "protect-fallback", $protectionLevel )->parse();
349 } else {
350 $message = $message->escaped();
351 }
352 }
353
354 $pageInfo['header-restrictions'][] = array(
355 $this->msg( "restriction-$restrictionType" ), $message
356 );
357 }
358
359 if ( !$this->page->exists() ) {
360 return $pageInfo;
361 }
362
363 // Edit history
364 $pageInfo['header-edits'] = array();
365
366 $firstRev = $this->page->getOldestRevision();
367
368 // Page creator
369 $pageInfo['header-edits'][] = array(
370 $this->msg( 'pageinfo-firstuser' ),
371 Linker::revUserTools( $firstRev )
372 );
373
374 // Date of page creation
375 $pageInfo['header-edits'][] = array(
376 $this->msg( 'pageinfo-firsttime' ),
377 Linker::linkKnown(
378 $title,
379 $lang->userTimeAndDate( $firstRev->getTimestamp(), $user ),
380 array(),
381 array( 'oldid' => $firstRev->getId() )
382 )
383 );
384
385 // Latest editor
386 $pageInfo['header-edits'][] = array(
387 $this->msg( 'pageinfo-lastuser' ),
388 Linker::revUserTools( $this->page->getRevision() )
389 );
390
391 // Date of latest edit
392 $pageInfo['header-edits'][] = array(
393 $this->msg( 'pageinfo-lasttime' ),
394 Linker::linkKnown(
395 $title,
396 $lang->userTimeAndDate( $this->page->getTimestamp(), $user ),
397 array(),
398 array( 'oldid' => $this->page->getLatest() )
399 )
400 );
401
402 // Total number of edits
403 $pageInfo['header-edits'][] = array(
404 $this->msg( 'pageinfo-edits' ), $lang->formatNum( $pageCounts['edits'] )
405 );
406
407 // Total number of distinct authors
408 $pageInfo['header-edits'][] = array(
409 $this->msg( 'pageinfo-authors' ), $lang->formatNum( $pageCounts['authors'] )
410 );
411
412 // Recent number of edits (within past 30 days)
413 $pageInfo['header-edits'][] = array(
414 $this->msg( 'pageinfo-recent-edits', $lang->formatDuration( $wgRCMaxAge ) ),
415 $lang->formatNum( $pageCounts['recent_edits'] )
416 );
417
418 // Recent number of distinct authors
419 $pageInfo['header-edits'][] = array(
420 $this->msg( 'pageinfo-recent-authors' ), $lang->formatNum( $pageCounts['recent_authors'] )
421 );
422
423 // Array of MagicWord objects
424 $magicWords = MagicWord::getDoubleUnderscoreArray();
425
426 // Array of magic word IDs
427 $wordIDs = $magicWords->names;
428
429 // Array of IDs => localized magic words
430 $localizedWords = $wgContLang->getMagicWords();
431
432 $listItems = array();
433 foreach ( $pageProperties as $property => $value ) {
434 if ( in_array( $property, $wordIDs ) ) {
435 $listItems[] = Html::element( 'li', array(), $localizedWords[$property][1] );
436 }
437 }
438
439 $localizedList = Html::rawElement( 'ul', array(), implode( '', $listItems ) );
440 $hiddenCategories = $this->page->getHiddenCategories();
441 $transcludedTemplates = $title->getTemplateLinksFrom();
442
443 if ( count( $listItems ) > 0
444 || count( $hiddenCategories ) > 0
445 || count( $transcludedTemplates ) > 0 ) {
446 // Page properties
447 $pageInfo['header-properties'] = array();
448
449 // Magic words
450 if ( count( $listItems ) > 0 ) {
451 $pageInfo['header-properties'][] = array(
452 $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
453 $localizedList
454 );
455 }
456
457 // Hidden categories
458 if ( count( $hiddenCategories ) > 0 ) {
459 $pageInfo['header-properties'][] = array(
460 $this->msg( 'pageinfo-hidden-categories' )
461 ->numParams( count( $hiddenCategories ) ),
462 Linker::formatHiddenCategories( $hiddenCategories )
463 );
464 }
465
466 // Transcluded templates
467 if ( count( $transcludedTemplates ) > 0 ) {
468 $pageInfo['header-properties'][] = array(
469 $this->msg( 'pageinfo-templates' )
470 ->numParams( count( $transcludedTemplates ) ),
471 Linker::formatTemplates( $transcludedTemplates )
472 );
473 }
474 }
475
476 return $pageInfo;
477 }
478
479 /**
480 * Returns page counts that would be too "expensive" to retrieve by normal means.
481 *
482 * @param Title $title Title to get counts for
483 * @return array
484 */
485 protected static function pageCounts( Title $title ) {
486 global $wgRCMaxAge, $wgDisableCounters;
487
488 wfProfileIn( __METHOD__ );
489 $id = $title->getArticleID();
490
491 $dbr = wfGetDB( DB_SLAVE );
492 $result = array();
493
494 if ( !$wgDisableCounters ) {
495 // Number of views
496 $views = (int) $dbr->selectField(
497 'page',
498 'page_counter',
499 array( 'page_id' => $id ),
500 __METHOD__
501 );
502 $result['views'] = $views;
503 }
504
505 // Number of page watchers
506 $watchers = (int) $dbr->selectField(
507 'watchlist',
508 'COUNT(*)',
509 array(
510 'wl_namespace' => $title->getNamespace(),
511 'wl_title' => $title->getDBkey(),
512 ),
513 __METHOD__
514 );
515 $result['watchers'] = $watchers;
516
517 // Total number of edits
518 $edits = (int) $dbr->selectField(
519 'revision',
520 'COUNT(rev_page)',
521 array( 'rev_page' => $id ),
522 __METHOD__
523 );
524 $result['edits'] = $edits;
525
526 // Total number of distinct authors
527 $authors = (int) $dbr->selectField(
528 'revision',
529 'COUNT(DISTINCT rev_user_text)',
530 array( 'rev_page' => $id ),
531 __METHOD__
532 );
533 $result['authors'] = $authors;
534
535 // "Recent" threshold defined by $wgRCMaxAge
536 $threshold = $dbr->timestamp( time() - $wgRCMaxAge );
537
538 // Recent number of edits
539 $edits = (int) $dbr->selectField(
540 'revision',
541 'COUNT(rev_page)',
542 array(
543 'rev_page' => $id ,
544 "rev_timestamp >= $threshold"
545 ),
546 __METHOD__
547 );
548 $result['recent_edits'] = $edits;
549
550 // Recent number of distinct authors
551 $authors = (int) $dbr->selectField(
552 'revision',
553 'COUNT(DISTINCT rev_user_text)',
554 array(
555 'rev_page' => $id,
556 "rev_timestamp >= $threshold"
557 ),
558 __METHOD__
559 );
560 $result['recent_authors'] = $authors;
561
562 // Subpages (if enabled)
563 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
564 $conds = array( 'page_namespace' => $title->getNamespace() );
565 $conds[] = 'page_title ' . $dbr->buildLike( $title->getDBkey() . '/', $dbr->anyString() );
566
567 // Subpages of this page (redirects)
568 $conds['page_is_redirect'] = 1;
569 $result['subpages']['redirects'] = (int) $dbr->selectField(
570 'page',
571 'COUNT(page_id)',
572 $conds,
573 __METHOD__ );
574
575 // Subpages of this page (non-redirects)
576 $conds['page_is_redirect'] = 0;
577 $result['subpages']['nonredirects'] = (int) $dbr->selectField(
578 'page',
579 'COUNT(page_id)',
580 $conds,
581 __METHOD__
582 );
583
584 // Subpages of this page (total)
585 $result['subpages']['total'] = $result['subpages']['redirects']
586 + $result['subpages']['nonredirects'];
587 }
588
589 wfProfileOut( __METHOD__ );
590 return $result;
591 }
592
593 /**
594 * Returns the name that goes in the "<h1>" page title.
595 *
596 * @return string
597 */
598 protected function getPageTitle() {
599 return $this->msg( 'pageinfo-title', $this->getTitle()->getPrefixedText() )->text();
600 }
601
602 /**
603 * Get a list of contributors of $article
604 * @return string: html
605 */
606 protected function getContributors() {
607 global $wgHiddenPrefs;
608
609 $contributors = $this->page->getContributors();
610 $real_names = array();
611 $user_names = array();
612 $anon_ips = array();
613
614 # Sift for real versus user names
615 foreach ( $contributors as $user ) {
616 $page = $user->isAnon()
617 ? SpecialPage::getTitleFor( 'Contributions', $user->getName() )
618 : $user->getUserPage();
619
620 if ( $user->getID() == 0 ) {
621 $anon_ips[] = Linker::link( $page, htmlspecialchars( $user->getName() ) );
622 } elseif ( !in_array( 'realname', $wgHiddenPrefs ) && $user->getRealName() ) {
623 $real_names[] = Linker::link( $page, htmlspecialchars( $user->getRealName() ) );
624 } else {
625 $user_names[] = Linker::link( $page, htmlspecialchars( $user->getName() ) );
626 }
627 }
628
629 $lang = $this->getLanguage();
630
631 $real = $lang->listToText( $real_names );
632
633 # "ThisSite user(s) A, B and C"
634 if ( count( $user_names ) ) {
635 $user = $this->msg( 'siteusers' )->rawParams( $lang->listToText( $user_names ) )->params(
636 count( $user_names ) )->escaped();
637 } else {
638 $user = false;
639 }
640
641 if ( count( $anon_ips ) ) {
642 $anon = $this->msg( 'anonusers' )->rawParams( $lang->listToText( $anon_ips ) )->params(
643 count( $anon_ips ) )->escaped();
644 } else {
645 $anon = false;
646 }
647
648 # This is the big list, all mooshed together. We sift for blank strings
649 $fulllist = array();
650 foreach ( array( $real, $user, $anon ) as $s ) {
651 if ( $s !== '' ) {
652 array_push( $fulllist, $s );
653 }
654 }
655
656 $count = count( $fulllist );
657 # "Based on work by ..."
658 return $count
659 ? $this->msg( 'othercontribs' )->rawParams(
660 $lang->listToText( $fulllist ) )->params( $count )->escaped()
661 : '';
662 }
663
664 /**
665 * Returns the description that goes below the "<h1>" tag.
666 *
667 * @return string
668 */
669 protected function getDescription() {
670 return '';
671 }
672 }