Implement extension registration from an extension.json file
[mediawiki.git] / includes / CategoryViewer.php
blob4d23ed2e486b53dbabda14ae1a3655d0f99b0c0a
1 <?php
2 /**
3 * List and paging of category members.
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.
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.
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
20 * @file
23 class CategoryViewer extends ContextSource {
24 /** @var int */
25 public $limit;
27 /** @var array */
28 public $from;
30 /** @var array */
31 public $until;
33 /** @var string[] */
34 public $articles;
36 /** @var array */
37 public $articles_start_char;
39 /** @var array */
40 public $children;
42 /** @var array */
43 public $children_start_char;
45 /** @var bool */
46 public $showGallery;
48 /** @var array */
49 public $imgsNoGallery_start_char;
51 /** @var array */
52 public $imgsNoGallery;
54 /** @var array */
55 public $nextPage;
57 /** @var array */
58 protected $prevPage;
60 /** @var array */
61 public $flip;
63 /** @var Title */
64 public $title;
66 /** @var Collation */
67 public $collation;
69 /** @var ImageGallery */
70 public $gallery;
72 /** @var Category Category object for this page. */
73 private $cat;
75 /** @var array The original query array, to be used in generating paging links. */
76 private $query;
78 /**
79 * @since 1.19 $context is a second, required parameter
80 * @param Title $title
81 * @param IContextSource $context
82 * @param array $from An array with keys page, subcat,
83 * and file for offset of results of each section (since 1.17)
84 * @param array $until An array with 3 keys for until of each section (since 1.17)
85 * @param array $query
87 function __construct( $title, IContextSource $context, $from = array(),
88 $until = array(), $query = array()
89 ) {
90 $this->title = $title;
91 $this->setContext( $context );
92 $this->from = $from;
93 $this->until = $until;
94 $this->limit = $context->getConfig()->get( 'CategoryPagingLimit' );
95 $this->cat = Category::newFromTitle( $title );
96 $this->query = $query;
97 $this->collation = Collation::singleton();
98 unset( $this->query['title'] );
102 * Format the category data list.
104 * @return string HTML output
106 public function getHTML() {
108 $this->showGallery = $this->getConfig()->get( 'CategoryMagicGallery' )
109 && !$this->getOutput()->mNoGallery;
111 $this->clearCategoryState();
112 $this->doCategoryQuery();
113 $this->finaliseCategoryState();
115 $r = $this->getSubcategorySection() .
116 $this->getPagesSection() .
117 $this->getImageSection();
119 if ( $r == '' ) {
120 // If there is no category content to display, only
121 // show the top part of the navigation links.
122 // @todo FIXME: Cannot be completely suppressed because it
123 // is unknown if 'until' or 'from' makes this
124 // give 0 results.
125 $r = $r . $this->getCategoryTop();
126 } else {
127 $r = $this->getCategoryTop() .
128 $r .
129 $this->getCategoryBottom();
132 // Give a proper message if category is empty
133 if ( $r == '' ) {
134 $r = $this->msg( 'category-empty' )->parseAsBlock();
137 $lang = $this->getLanguage();
138 $langAttribs = array( 'lang' => $lang->getHtmlCode(), 'dir' => $lang->getDir() );
139 # put a div around the headings which are in the user language
140 $r = Html::openElement( 'div', $langAttribs ) . $r . '</div>';
142 return $r;
145 function clearCategoryState() {
146 $this->articles = array();
147 $this->articles_start_char = array();
148 $this->children = array();
149 $this->children_start_char = array();
150 if ( $this->showGallery ) {
151 // Note that null for mode is taken to mean use default.
152 $mode = $this->getRequest()->getVal( 'gallerymode', null );
153 try {
154 $this->gallery = ImageGalleryBase::factory( $mode, $this->getContext() );
155 } catch ( MWException $e ) {
156 // User specified something invalid, fallback to default.
157 $this->gallery = ImageGalleryBase::factory( false, $this->getContext() );
160 $this->gallery->setHideBadImages();
161 } else {
162 $this->imgsNoGallery = array();
163 $this->imgsNoGallery_start_char = array();
168 * Add a subcategory to the internal lists, using a Category object
169 * @param Category $cat
170 * @param string $sortkey
171 * @param int $pageLength
173 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
174 // Subcategory; strip the 'Category' namespace from the link text.
175 $title = $cat->getTitle();
177 $link = Linker::link( $title, htmlspecialchars( $title->getText() ) );
178 if ( $title->isRedirect() ) {
179 // This didn't used to add redirect-in-category, but might
180 // as well be consistent with the rest of the sections
181 // on a category page.
182 $link = '<span class="redirect-in-category">' . $link . '</span>';
184 $this->children[] = $link;
186 $this->children_start_char[] =
187 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
191 * Get the character to be used for sorting subcategories.
192 * If there's a link from Category:A to Category:B, the sortkey of the resulting
193 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
194 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
195 * else use sortkey...
197 * @param Title $title
198 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
199 * @return string
201 function getSubcategorySortChar( $title, $sortkey ) {
202 global $wgContLang;
204 if ( $title->getPrefixedText() == $sortkey ) {
205 $word = $title->getDBkey();
206 } else {
207 $word = $sortkey;
210 $firstChar = $this->collation->getFirstLetter( $word );
212 return $wgContLang->convert( $firstChar );
216 * Add a page in the image namespace
217 * @param Title $title
218 * @param string $sortkey
219 * @param int $pageLength
220 * @param bool $isRedirect
222 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
223 global $wgContLang;
224 if ( $this->showGallery ) {
225 $flip = $this->flip['file'];
226 if ( $flip ) {
227 $this->gallery->insert( $title );
228 } else {
229 $this->gallery->add( $title );
231 } else {
232 $link = Linker::link( $title );
233 if ( $isRedirect ) {
234 // This seems kind of pointless given 'mw-redirect' class,
235 // but keeping for back-compatibility with user css.
236 $link = '<span class="redirect-in-category">' . $link . '</span>';
238 $this->imgsNoGallery[] = $link;
240 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
241 $this->collation->getFirstLetter( $sortkey ) );
246 * Add a miscellaneous page
247 * @param Title $title
248 * @param string $sortkey
249 * @param int $pageLength
250 * @param bool $isRedirect
252 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
253 global $wgContLang;
255 $link = Linker::link( $title );
256 if ( $isRedirect ) {
257 // This seems kind of pointless given 'mw-redirect' class,
258 // but keeping for back-compatibility with user css.
259 $link = '<span class="redirect-in-category">' . $link . '</span>';
261 $this->articles[] = $link;
263 $this->articles_start_char[] = $wgContLang->convert(
264 $this->collation->getFirstLetter( $sortkey ) );
267 function finaliseCategoryState() {
268 if ( $this->flip['subcat'] ) {
269 $this->children = array_reverse( $this->children );
270 $this->children_start_char = array_reverse( $this->children_start_char );
272 if ( $this->flip['page'] ) {
273 $this->articles = array_reverse( $this->articles );
274 $this->articles_start_char = array_reverse( $this->articles_start_char );
276 if ( !$this->showGallery && $this->flip['file'] ) {
277 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
278 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
282 function doCategoryQuery() {
283 $dbr = wfGetDB( DB_SLAVE, 'category' );
285 $this->nextPage = array(
286 'page' => null,
287 'subcat' => null,
288 'file' => null,
290 $this->prevPage = array(
291 'page' => null,
292 'subcat' => null,
293 'file' => null,
296 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
298 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
299 # Get the sortkeys for start/end, if applicable. Note that if
300 # the collation in the database differs from the one
301 # set in $wgCategoryCollation, pagination might go totally haywire.
302 $extraConds = array( 'cl_type' => $type );
303 if ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
304 $extraConds[] = 'cl_sortkey >= '
305 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
306 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
307 $extraConds[] = 'cl_sortkey < '
308 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
309 $this->flip[$type] = true;
312 $res = $dbr->select(
313 array( 'page', 'categorylinks', 'category' ),
314 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
315 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
316 'cat_subcats', 'cat_pages', 'cat_files',
317 'cl_sortkey_prefix', 'cl_collation' ),
318 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
319 __METHOD__,
320 array(
321 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
322 'LIMIT' => $this->limit + 1,
323 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
325 array(
326 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
327 'category' => array( 'LEFT JOIN', array(
328 'cat_title = page_title',
329 'page_namespace' => NS_CATEGORY
334 $count = 0;
335 foreach ( $res as $row ) {
336 $title = Title::newFromRow( $row );
337 if ( $row->cl_collation === '' ) {
338 // Hack to make sure that while updating from 1.16 schema
339 // and db is inconsistent, that the sky doesn't fall.
340 // See r83544. Could perhaps be removed in a couple decades...
341 $humanSortkey = $row->cl_sortkey;
342 } else {
343 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
346 if ( ++$count > $this->limit ) {
347 # We've reached the one extra which shows that there
348 # are additional pages to be had. Stop here...
349 $this->nextPage[$type] = $humanSortkey;
350 break;
352 if ( $count == $this->limit ) {
353 $this->prevPage[$type] = $humanSortkey;
356 if ( $title->getNamespace() == NS_CATEGORY ) {
357 $cat = Category::newFromRow( $row, $title );
358 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
359 } elseif ( $title->getNamespace() == NS_FILE ) {
360 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
361 } else {
362 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
369 * @return string
371 function getCategoryTop() {
372 $r = $this->getCategoryBottom();
373 return $r === ''
374 ? $r
375 : "<br style=\"clear:both;\"/>\n" . $r;
379 * @return string
381 function getSubcategorySection() {
382 # Don't show subcategories section if there are none.
383 $r = '';
384 $rescnt = count( $this->children );
385 $dbcnt = $this->cat->getSubcatCount();
386 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
388 if ( $rescnt > 0 ) {
389 # Showing subcategories
390 $r .= "<div id=\"mw-subcategories\">\n";
391 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
392 $r .= $countmsg;
393 $r .= $this->getSectionPagingLinks( 'subcat' );
394 $r .= $this->formatList( $this->children, $this->children_start_char );
395 $r .= $this->getSectionPagingLinks( 'subcat' );
396 $r .= "\n</div>";
398 return $r;
402 * @return string
404 function getPagesSection() {
405 $ti = wfEscapeWikiText( $this->title->getText() );
406 # Don't show articles section if there are none.
407 $r = '';
409 # @todo FIXME: Here and in the other two sections: we don't need to bother
410 # with this rigmarole if the entire category contents fit on one page
411 # and have already been retrieved. We can just use $rescnt in that
412 # case and save a query and some logic.
413 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
414 - $this->cat->getFileCount();
415 $rescnt = count( $this->articles );
416 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
418 if ( $rescnt > 0 ) {
419 $r = "<div id=\"mw-pages\">\n";
420 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
421 $r .= $countmsg;
422 $r .= $this->getSectionPagingLinks( 'page' );
423 $r .= $this->formatList( $this->articles, $this->articles_start_char );
424 $r .= $this->getSectionPagingLinks( 'page' );
425 $r .= "\n</div>";
427 return $r;
431 * @return string
433 function getImageSection() {
434 $r = '';
435 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
436 if ( $rescnt > 0 ) {
437 $dbcnt = $this->cat->getFileCount();
438 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
440 $r .= "<div id=\"mw-category-media\">\n";
441 $r .= '<h2>' .
442 $this->msg(
443 'category-media-header',
444 wfEscapeWikiText( $this->title->getText() )
445 )->text() .
446 "</h2>\n";
447 $r .= $countmsg;
448 $r .= $this->getSectionPagingLinks( 'file' );
449 if ( $this->showGallery ) {
450 $r .= $this->gallery->toHTML();
451 } else {
452 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
454 $r .= $this->getSectionPagingLinks( 'file' );
455 $r .= "\n</div>";
457 return $r;
461 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
462 * of the output.
464 * @param string $type 'page', 'subcat', or 'file'
465 * @return string HTML output, possibly empty if there are no other pages
467 private function getSectionPagingLinks( $type ) {
468 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
469 // The new value for the until parameter should be pointing to the first
470 // result displayed on the page which is the second last result retrieved
471 // from the database.The next link should have a from parameter pointing
472 // to the until parameter of the current page.
473 if ( $this->nextPage[$type] !== null ) {
474 return $this->pagingLinks( $this->prevPage[$type], $this->until[$type], $type );
475 } else {
476 // If the nextPage variable is null, it means that we have reached the first page
477 // and therefore the previous link should be disabled.
478 return $this->pagingLinks( null, $this->until[$type], $type );
480 } elseif ( $this->nextPage[$type] !== null
481 || ( isset( $this->from[$type] ) && $this->from[$type] !== null )
483 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
484 } else {
485 return '';
490 * @return string
492 function getCategoryBottom() {
493 return '';
497 * Format a list of articles chunked by letter, either as a
498 * bullet list or a columnar format, depending on the length.
500 * @param array $articles
501 * @param array $articles_start_char
502 * @param int $cutoff
503 * @return string
504 * @private
506 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
507 $list = '';
508 if ( count( $articles ) > $cutoff ) {
509 $list = self::columnList( $articles, $articles_start_char );
510 } elseif ( count( $articles ) > 0 ) {
511 // for short lists of articles in categories.
512 $list = self::shortList( $articles, $articles_start_char );
515 $pageLang = $this->title->getPageLanguage();
516 $attribs = array( 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
517 'class' => 'mw-content-' . $pageLang->getDir() );
518 $list = Html::rawElement( 'div', $attribs, $list );
520 return $list;
524 * Format a list of articles chunked by letter in a three-column
525 * list, ordered vertically.
527 * TODO: Take the headers into account when creating columns, so they're
528 * more visually equal.
530 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
531 * supports those.
533 * @param array $articles
534 * @param string[] $articles_start_char
535 * @return string
536 * @private
538 static function columnList( $articles, $articles_start_char ) {
539 $columns = array_combine( $articles, $articles_start_char );
540 # Split into three columns
541 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
543 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
544 $prevchar = null;
546 foreach ( $columns as $column ) {
547 $ret .= '<td style="width: 33.3%;">';
548 $colContents = array();
550 # Kind of like array_flip() here, but we keep duplicates in an
551 # array instead of dropping them.
552 foreach ( $column as $article => $char ) {
553 if ( !isset( $colContents[$char] ) ) {
554 $colContents[$char] = array();
556 $colContents[$char][] = $article;
559 $first = true;
560 foreach ( $colContents as $char => $articles ) {
561 # Change space to non-breaking space to keep headers aligned
562 $h3char = $char === ' ' ? '&#160;' : htmlspecialchars( $char );
564 $ret .= '<h3>' . $h3char;
565 if ( $first && $char === $prevchar ) {
566 # We're continuing a previous chunk at the top of a new
567 # column, so add " cont." after the letter.
568 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
570 $ret .= "</h3>\n";
572 $ret .= '<ul><li>';
573 $ret .= implode( "</li>\n<li>", $articles );
574 $ret .= '</li></ul>';
576 $first = false;
577 $prevchar = $char;
580 $ret .= "</td>\n";
583 $ret .= '</tr></table>';
584 return $ret;
588 * Format a list of articles chunked by letter in a bullet list.
589 * @param array $articles
590 * @param string[] $articles_start_char
591 * @return string
592 * @private
594 static function shortList( $articles, $articles_start_char ) {
595 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
596 $r .= '<ul><li>' . $articles[0] . '</li>';
597 $articleCount = count( $articles );
598 for ( $index = 1; $index < $articleCount; $index++ ) {
599 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
600 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
603 $r .= "<li>{$articles[$index]}</li>";
605 $r .= '</ul>';
606 return $r;
610 * Create paging links, as a helper method to getSectionPagingLinks().
612 * @param string $first The 'until' parameter for the generated URL
613 * @param string $last The 'from' parameter for the generated URL
614 * @param string $type A prefix for parameters, 'page' or 'subcat' or
615 * 'file'
616 * @return string HTML
618 private function pagingLinks( $first, $last, $type = '' ) {
619 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit )->escaped();
621 if ( $first != '' ) {
622 $prevQuery = $this->query;
623 $prevQuery["{$type}until"] = $first;
624 unset( $prevQuery["{$type}from"] );
625 $prevLink = Linker::linkKnown(
626 $this->addFragmentToTitle( $this->title, $type ),
627 $prevLink,
628 array(),
629 $prevQuery
633 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit )->escaped();
635 if ( $last != '' ) {
636 $lastQuery = $this->query;
637 $lastQuery["{$type}from"] = $last;
638 unset( $lastQuery["{$type}until"] );
639 $nextLink = Linker::linkKnown(
640 $this->addFragmentToTitle( $this->title, $type ),
641 $nextLink,
642 array(),
643 $lastQuery
647 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
651 * Takes a title, and adds the fragment identifier that
652 * corresponds to the correct segment of the category.
654 * @param Title $title The title (usually $this->title)
655 * @param string $section Which section
656 * @throws MWException
657 * @return Title
659 private function addFragmentToTitle( $title, $section ) {
660 switch ( $section ) {
661 case 'page':
662 $fragment = 'mw-pages';
663 break;
664 case 'subcat':
665 $fragment = 'mw-subcategories';
666 break;
667 case 'file':
668 $fragment = 'mw-category-media';
669 break;
670 default:
671 throw new MWException( __METHOD__ .
672 " Invalid section $section." );
675 return Title::makeTitle( $title->getNamespace(),
676 $title->getDBkey(), $fragment );
680 * What to do if the category table conflicts with the number of results
681 * returned? This function says what. Each type is considered independently
682 * of the other types.
684 * @param int $rescnt The number of items returned by our database query.
685 * @param int $dbcnt The number of items according to the category table.
686 * @param string $type 'subcat', 'article', or 'file'
687 * @return string A message giving the number of items, to output to HTML.
689 private function getCountMessage( $rescnt, $dbcnt, $type ) {
690 // There are three cases:
691 // 1) The category table figure seems sane. It might be wrong, but
692 // we can't do anything about it if we don't recalculate it on ev-
693 // ery category view.
694 // 2) The category table figure isn't sane, like it's smaller than the
695 // number of actual results, *but* the number of results is less
696 // than $this->limit and there's no offset. In this case we still
697 // know the right figure.
698 // 3) We have no idea.
700 // Check if there's a "from" or "until" for anything
702 // This is a little ugly, but we seem to use different names
703 // for the paging types then for the messages.
704 if ( $type === 'article' ) {
705 $pagingType = 'page';
706 } else {
707 $pagingType = $type;
710 $fromOrUntil = false;
711 if ( ( isset( $this->from[$pagingType] ) && $this->from[$pagingType] !== null ) ||
712 ( isset( $this->until[$pagingType] ) && $this->until[$pagingType] !== null )
714 $fromOrUntil = true;
717 if ( $dbcnt == $rescnt ||
718 ( ( $rescnt == $this->limit || $fromOrUntil ) && $dbcnt > $rescnt )
720 // Case 1: seems sane.
721 $totalcnt = $dbcnt;
722 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
723 // Case 2: not sane, but salvageable. Use the number of results.
724 // Since there are fewer than 200, we can also take this opportunity
725 // to refresh the incorrect category table entry -- which should be
726 // quick due to the small number of entries.
727 $totalcnt = $rescnt;
728 $category = $this->cat;
729 wfGetDB( DB_MASTER )->onTransactionIdle( function () use ( $category ) {
730 $category->refreshCounts();
731 } );
732 } else {
733 // Case 3: hopeless. Don't give a total count at all.
734 // Messages: category-subcat-count-limited, category-article-count-limited,
735 // category-file-count-limited
736 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
738 // Messages: category-subcat-count, category-article-count, category-file-count
739 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();