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
22 use MediaWiki\MediaWikiServices
;
24 class CategoryViewer
extends ContextSource
{
38 public $articles_start_char;
44 public $children_start_char;
50 public $imgsNoGallery_start_char;
53 public $imgsNoGallery;
70 /** @var ImageGallery */
73 /** @var Category Category object for this page. */
76 /** @var array The original query array, to be used in generating paging links. */
80 * @since 1.19 $context is a second, required parameter
82 * @param IContextSource $context
83 * @param array $from An array with keys page, subcat,
84 * and file for offset of results of each section (since 1.17)
85 * @param array $until An array with 3 keys for until of each section (since 1.17)
88 function __construct( $title, IContextSource
$context, $from = [],
89 $until = [], $query = []
91 $this->title
= $title;
92 $this->setContext( $context );
93 $this->getOutput()->addModuleStyles( [
94 'mediawiki.action.view.categoryPage.styles'
97 $this->until
= $until;
98 $this->limit
= $context->getConfig()->get( 'CategoryPagingLimit' );
99 $this->cat
= Category
::newFromTitle( $title );
100 $this->query
= $query;
101 $this->collation
= Collation
::singleton();
102 unset( $this->query
['title'] );
106 * Format the category data list.
108 * @return string HTML output
110 public function getHTML() {
112 $this->showGallery
= $this->getConfig()->get( 'CategoryMagicGallery' )
113 && !$this->getOutput()->mNoGallery
;
115 $this->clearCategoryState();
116 $this->doCategoryQuery();
117 $this->finaliseCategoryState();
119 $r = $this->getSubcategorySection() .
120 $this->getPagesSection() .
121 $this->getImageSection();
124 // If there is no category content to display, only
125 // show the top part of the navigation links.
126 // @todo FIXME: Cannot be completely suppressed because it
127 // is unknown if 'until' or 'from' makes this
129 $r = $r . $this->getCategoryTop();
131 $r = $this->getCategoryTop() .
133 $this->getCategoryBottom();
136 // Give a proper message if category is empty
138 $r = $this->msg( 'category-empty' )->parseAsBlock();
141 $lang = $this->getLanguage();
143 'class' => 'mw-category-generated',
144 'lang' => $lang->getHtmlCode(),
145 'dir' => $lang->getDir()
147 # put a div around the headings which are in the user language
148 $r = Html
::openElement( 'div', $attribs ) . $r . '</div>';
153 function clearCategoryState() {
154 $this->articles
= [];
155 $this->articles_start_char
= [];
156 $this->children
= [];
157 $this->children_start_char
= [];
158 if ( $this->showGallery
) {
159 // Note that null for mode is taken to mean use default.
160 $mode = $this->getRequest()->getVal( 'gallerymode', null );
162 $this->gallery
= ImageGalleryBase
::factory( $mode, $this->getContext() );
163 } catch ( Exception
$e ) {
164 // User specified something invalid, fallback to default.
165 $this->gallery
= ImageGalleryBase
::factory( false, $this->getContext() );
168 $this->gallery
->setHideBadImages();
170 $this->imgsNoGallery
= [];
171 $this->imgsNoGallery_start_char
= [];
176 * Add a subcategory to the internal lists, using a Category object
177 * @param Category $cat
178 * @param string $sortkey
179 * @param int $pageLength
181 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
182 // Subcategory; strip the 'Category' namespace from the link text.
183 $title = $cat->getTitle();
185 $this->children
[] = $this->generateLink(
188 $title->isRedirect(),
189 htmlspecialchars( $title->getText() )
192 $this->children_start_char
[] =
193 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
196 function generateLink( $type, Title
$title, $isRedirect, $html = null ) {
198 Hooks
::run( 'CategoryViewer::generateLink', [ $type, $title, $html, &$link ] );
199 if ( $link === null ) {
200 $link = Linker
::link( $title, $html );
203 $link = '<span class="redirect-in-category">' . $link . '</span>';
210 * Get the character to be used for sorting subcategories.
211 * If there's a link from Category:A to Category:B, the sortkey of the resulting
212 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
213 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
214 * else use sortkey...
216 * @param Title $title
217 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
220 function getSubcategorySortChar( $title, $sortkey ) {
223 if ( $title->getPrefixedText() == $sortkey ) {
224 $word = $title->getDBkey();
229 $firstChar = $this->collation
->getFirstLetter( $word );
231 return $wgContLang->convert( $firstChar );
235 * Add a page in the image namespace
236 * @param Title $title
237 * @param string $sortkey
238 * @param int $pageLength
239 * @param bool $isRedirect
241 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
243 if ( $this->showGallery
) {
244 $flip = $this->flip
['file'];
246 $this->gallery
->insert( $title );
248 $this->gallery
->add( $title );
251 $this->imgsNoGallery
[] = $this->generateLink( 'image', $title, $isRedirect );
253 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
254 $this->collation
->getFirstLetter( $sortkey ) );
259 * Add a miscellaneous page
260 * @param Title $title
261 * @param string $sortkey
262 * @param int $pageLength
263 * @param bool $isRedirect
265 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
268 $this->articles
[] = $this->generateLink( 'page', $title, $isRedirect );
270 $this->articles_start_char
[] = $wgContLang->convert(
271 $this->collation
->getFirstLetter( $sortkey ) );
274 function finaliseCategoryState() {
275 if ( $this->flip
['subcat'] ) {
276 $this->children
= array_reverse( $this->children
);
277 $this->children_start_char
= array_reverse( $this->children_start_char
);
279 if ( $this->flip
['page'] ) {
280 $this->articles
= array_reverse( $this->articles
);
281 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
283 if ( !$this->showGallery
&& $this->flip
['file'] ) {
284 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
285 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
289 function doCategoryQuery() {
290 $dbr = wfGetDB( DB_REPLICA
, 'category' );
303 $this->flip
= [ 'page' => false, 'subcat' => false, 'file' => false ];
305 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
306 # Get the sortkeys for start/end, if applicable. Note that if
307 # the collation in the database differs from the one
308 # set in $wgCategoryCollation, pagination might go totally haywire.
309 $extraConds = [ 'cl_type' => $type ];
310 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
311 $extraConds[] = 'cl_sortkey >= '
312 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
313 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
314 $extraConds[] = 'cl_sortkey < '
315 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
316 $this->flip
[$type] = true;
320 [ 'page', 'categorylinks', 'category' ],
322 LinkCache
::getSelectFields(),
334 array_merge( [ 'cl_to' => $this->title
->getDBkey() ], $extraConds ),
337 'USE INDEX' => [ 'categorylinks' => 'cl_sortkey' ],
338 'LIMIT' => $this->limit +
1,
339 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
342 'categorylinks' => [ 'INNER JOIN', 'cl_from = page_id' ],
343 'category' => [ 'LEFT JOIN', [
344 'cat_title = page_title',
345 'page_namespace' => NS_CATEGORY
350 Hooks
::run( 'CategoryViewer::doCategoryQuery', [ $type, $res ] );
351 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
354 foreach ( $res as $row ) {
355 $title = Title
::newFromRow( $row );
356 $linkCache->addGoodLinkObjFromRow( $title, $row );
358 if ( $row->cl_collation
=== '' ) {
359 // Hack to make sure that while updating from 1.16 schema
360 // and db is inconsistent, that the sky doesn't fall.
361 // See r83544. Could perhaps be removed in a couple decades...
362 $humanSortkey = $row->cl_sortkey
;
364 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
367 if ( ++
$count > $this->limit
) {
368 # We've reached the one extra which shows that there
369 # are additional pages to be had. Stop here...
370 $this->nextPage
[$type] = $humanSortkey;
373 if ( $count == $this->limit
) {
374 $this->prevPage
[$type] = $humanSortkey;
377 if ( $title->getNamespace() == NS_CATEGORY
) {
378 $cat = Category
::newFromRow( $row, $title );
379 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
380 } elseif ( $title->getNamespace() == NS_FILE
) {
381 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
383 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
392 function getCategoryTop() {
393 $r = $this->getCategoryBottom();
396 : "<br style=\"clear:both;\"/>\n" . $r;
402 function getSubcategorySection() {
403 # Don't show subcategories section if there are none.
405 $rescnt = count( $this->children
);
406 $dbcnt = $this->cat
->getSubcatCount();
407 // This function should be called even if the result isn't used, it has side-effects
408 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
411 # Showing subcategories
412 $r .= "<div id=\"mw-subcategories\">\n";
413 $r .= '<h2>' . $this->msg( 'subcategories' )->parse() . "</h2>\n";
415 $r .= $this->getSectionPagingLinks( 'subcat' );
416 $r .= $this->formatList( $this->children
, $this->children_start_char
);
417 $r .= $this->getSectionPagingLinks( 'subcat' );
424 * Return pretty name which is display name if given and different from prefix text or
425 * the unprefixed page name.
427 * @return string HTML safe name.
429 function getPrettyPageNameHtml() {
430 $displayTitle = $this->getOutput()->getPageTitle();
431 if ( $displayTitle === $this->getTitle()->getPrefixedText() ) {
432 return htmlspecialchars( $this->getTitle()->getText() );
434 return $displayTitle;
441 function getPagesSection() {
442 $name = $this->getPrettyPageNameHtml();
443 # Don't show articles section if there are none.
446 # @todo FIXME: Here and in the other two sections: we don't need to bother
447 # with this rigmarole if the entire category contents fit on one page
448 # and have already been retrieved. We can just use $rescnt in that
449 # case and save a query and some logic.
450 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
451 - $this->cat
->getFileCount();
452 $rescnt = count( $this->articles
);
453 // This function should be called even if the result isn't used, it has side-effects
454 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
457 $r = "<div id=\"mw-pages\">\n";
458 $r .= '<h2>' . $this->msg( 'category_header' )->rawParams( $name )->parse() . "</h2>\n";
460 $r .= $this->getSectionPagingLinks( 'page' );
461 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
462 $r .= $this->getSectionPagingLinks( 'page' );
471 function getImageSection() {
472 $name = $this->getPrettyPageNameHtml();
474 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
475 $dbcnt = $this->cat
->getFileCount();
476 // This function should be called even if the result isn't used, it has side-effects
477 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
480 $r .= "<div id=\"mw-category-media\">\n";
482 $this->msg( 'category-media-header' )->rawParams( $name )->parse() .
485 $r .= $this->getSectionPagingLinks( 'file' );
486 if ( $this->showGallery
) {
487 $r .= $this->gallery
->toHTML();
489 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
491 $r .= $this->getSectionPagingLinks( 'file' );
498 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
501 * @param string $type 'page', 'subcat', or 'file'
502 * @return string HTML output, possibly empty if there are no other pages
504 private function getSectionPagingLinks( $type ) {
505 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
506 // The new value for the until parameter should be pointing to the first
507 // result displayed on the page which is the second last result retrieved
508 // from the database.The next link should have a from parameter pointing
509 // to the until parameter of the current page.
510 if ( $this->nextPage
[$type] !== null ) {
511 return $this->pagingLinks( $this->prevPage
[$type], $this->until
[$type], $type );
513 // If the nextPage variable is null, it means that we have reached the first page
514 // and therefore the previous link should be disabled.
515 return $this->pagingLinks( null, $this->until
[$type], $type );
517 } elseif ( $this->nextPage
[$type] !== null
518 ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null )
520 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
529 function getCategoryBottom() {
534 * Format a list of articles chunked by letter, either as a
535 * bullet list or a columnar format, depending on the length.
537 * @param array $articles
538 * @param array $articles_start_char
543 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
545 if ( count( $articles ) > $cutoff ) {
546 $list = self
::columnList( $articles, $articles_start_char );
547 } elseif ( count( $articles ) > 0 ) {
548 // for short lists of articles in categories.
549 $list = self
::shortList( $articles, $articles_start_char );
552 $pageLang = $this->title
->getPageLanguage();
553 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
554 'class' => 'mw-content-' . $pageLang->getDir() ];
555 $list = Html
::rawElement( 'div', $attribs, $list );
561 * Format a list of articles chunked by letter in a three-column list, ordered
562 * vertically. This is used for categories with a significant number of pages.
564 * TODO: Take the headers into account when creating columns, so they're
565 * more visually equal.
567 * TODO: shortList and columnList are similar, need merging
569 * @param string[] $articles HTML links to each article
570 * @param string[] $articles_start_char The header characters for each article
571 * @return string HTML to output
574 static function columnList( $articles, $articles_start_char ) {
575 $columns = array_combine( $articles, $articles_start_char );
577 $ret = Html
::openElement( 'div', [ 'class' => 'mw-category' ] );
581 # Kind of like array_flip() here, but we keep duplicates in an
582 # array instead of dropping them.
583 foreach ( $columns as $article => $char ) {
584 if ( !isset( $colContents[$char] ) ) {
585 $colContents[$char] = [];
587 $colContents[$char][] = $article;
590 foreach ( $colContents as $char => $articles ) {
591 # Change space to non-breaking space to keep headers aligned
592 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
594 $ret .= '<div class="mw-category-group"><h3>' . $h3char;
598 $ret .= implode( "</li>\n<li>", $articles );
599 $ret .= '</li></ul></div>';
603 $ret .= Html
::closeElement( 'div' );
608 * Format a list of articles chunked by letter in a bullet list. This is used
609 * for categories with a small number of pages (when columns aren't needed).
610 * @param string[] $articles HTML links to each article
611 * @param string[] $articles_start_char The header characters for each article
612 * @return string HTML to output
615 static function shortList( $articles, $articles_start_char ) {
616 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
617 $r .= '<ul><li>' . $articles[0] . '</li>';
618 $articleCount = count( $articles );
619 for ( $index = 1; $index < $articleCount; $index++
) {
620 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
621 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
624 $r .= "<li>{$articles[$index]}</li>";
631 * Create paging links, as a helper method to getSectionPagingLinks().
633 * @param string $first The 'until' parameter for the generated URL
634 * @param string $last The 'from' parameter for the generated URL
635 * @param string $type A prefix for parameters, 'page' or 'subcat' or
637 * @return string HTML
639 private function pagingLinks( $first, $last, $type = '' ) {
640 $prevLink = $this->msg( 'prev-page' )->text();
642 if ( $first != '' ) {
643 $prevQuery = $this->query
;
644 $prevQuery["{$type}until"] = $first;
645 unset( $prevQuery["{$type}from"] );
646 $prevLink = Linker
::linkKnown(
647 $this->addFragmentToTitle( $this->title
, $type ),
654 $nextLink = $this->msg( 'next-page' )->text();
657 $lastQuery = $this->query
;
658 $lastQuery["{$type}from"] = $last;
659 unset( $lastQuery["{$type}until"] );
660 $nextLink = Linker
::linkKnown(
661 $this->addFragmentToTitle( $this->title
, $type ),
668 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
672 * Takes a title, and adds the fragment identifier that
673 * corresponds to the correct segment of the category.
675 * @param Title $title The title (usually $this->title)
676 * @param string $section Which section
677 * @throws MWException
680 private function addFragmentToTitle( $title, $section ) {
681 switch ( $section ) {
683 $fragment = 'mw-pages';
686 $fragment = 'mw-subcategories';
689 $fragment = 'mw-category-media';
692 throw new MWException( __METHOD__
.
693 " Invalid section $section." );
696 return Title
::makeTitle( $title->getNamespace(),
697 $title->getDBkey(), $fragment );
701 * What to do if the category table conflicts with the number of results
702 * returned? This function says what. Each type is considered independently
703 * of the other types.
705 * @param int $rescnt The number of items returned by our database query.
706 * @param int $dbcnt The number of items according to the category table.
707 * @param string $type 'subcat', 'article', or 'file'
708 * @return string A message giving the number of items, to output to HTML.
710 private function getCountMessage( $rescnt, $dbcnt, $type ) {
711 // There are three cases:
712 // 1) The category table figure seems sane. It might be wrong, but
713 // we can't do anything about it if we don't recalculate it on ev-
714 // ery category view.
715 // 2) The category table figure isn't sane, like it's smaller than the
716 // number of actual results, *but* the number of results is less
717 // than $this->limit and there's no offset. In this case we still
718 // know the right figure.
719 // 3) We have no idea.
721 // Check if there's a "from" or "until" for anything
723 // This is a little ugly, but we seem to use different names
724 // for the paging types then for the messages.
725 if ( $type === 'article' ) {
726 $pagingType = 'page';
731 $fromOrUntil = false;
732 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
733 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
738 if ( $dbcnt == $rescnt ||
739 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
741 // Case 1: seems sane.
743 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
744 // Case 2: not sane, but salvageable. Use the number of results.
745 // Since there are fewer than 200, we can also take this opportunity
746 // to refresh the incorrect category table entry -- which should be
747 // quick due to the small number of entries.
749 $category = $this->cat
;
750 DeferredUpdates
::addCallableUpdate( function () use ( $category ) {
751 $category->refreshCounts();
754 // Case 3: hopeless. Don't give a total count at all.
755 // Messages: category-subcat-count-limited, category-article-count-limited,
756 // category-file-count-limited
757 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
759 // Messages: category-subcat-count, category-article-count, category-file-count
760 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();