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 ImageGalleryBase */
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 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
201 if ( $html !== null ) {
202 $html = new HtmlArmor( $html );
204 $link = $linkRenderer->makeLink( $title, $html );
207 $link = '<span class="redirect-in-category">' . $link . '</span>';
214 * Get the character to be used for sorting subcategories.
215 * If there's a link from Category:A to Category:B, the sortkey of the resulting
216 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
217 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
218 * else use sortkey...
220 * @param Title $title
221 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
224 function getSubcategorySortChar( $title, $sortkey ) {
227 if ( $title->getPrefixedText() == $sortkey ) {
228 $word = $title->getDBkey();
233 $firstChar = $this->collation
->getFirstLetter( $word );
235 return $wgContLang->convert( $firstChar );
239 * Add a page in the image namespace
240 * @param Title $title
241 * @param string $sortkey
242 * @param int $pageLength
243 * @param bool $isRedirect
245 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
247 if ( $this->showGallery
) {
248 $flip = $this->flip
['file'];
250 $this->gallery
->insert( $title );
252 $this->gallery
->add( $title );
255 $this->imgsNoGallery
[] = $this->generateLink( 'image', $title, $isRedirect );
257 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
258 $this->collation
->getFirstLetter( $sortkey ) );
263 * Add a miscellaneous page
264 * @param Title $title
265 * @param string $sortkey
266 * @param int $pageLength
267 * @param bool $isRedirect
269 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
272 $this->articles
[] = $this->generateLink( 'page', $title, $isRedirect );
274 $this->articles_start_char
[] = $wgContLang->convert(
275 $this->collation
->getFirstLetter( $sortkey ) );
278 function finaliseCategoryState() {
279 if ( $this->flip
['subcat'] ) {
280 $this->children
= array_reverse( $this->children
);
281 $this->children_start_char
= array_reverse( $this->children_start_char
);
283 if ( $this->flip
['page'] ) {
284 $this->articles
= array_reverse( $this->articles
);
285 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
287 if ( !$this->showGallery
&& $this->flip
['file'] ) {
288 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
289 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
293 function doCategoryQuery() {
294 $dbr = wfGetDB( DB_REPLICA
, 'category' );
307 $this->flip
= [ 'page' => false, 'subcat' => false, 'file' => false ];
309 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
310 # Get the sortkeys for start/end, if applicable. Note that if
311 # the collation in the database differs from the one
312 # set in $wgCategoryCollation, pagination might go totally haywire.
313 $extraConds = [ 'cl_type' => $type ];
314 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
315 $extraConds[] = 'cl_sortkey >= '
316 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
317 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
318 $extraConds[] = 'cl_sortkey < '
319 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
320 $this->flip
[$type] = true;
324 [ 'page', 'categorylinks', 'category' ],
326 LinkCache
::getSelectFields(),
340 array_merge( [ 'cl_to' => $this->title
->getDBkey() ], $extraConds ),
343 'USE INDEX' => [ 'categorylinks' => 'cl_sortkey' ],
344 'LIMIT' => $this->limit +
1,
345 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
348 'categorylinks' => [ 'INNER JOIN', 'cl_from = page_id' ],
349 'category' => [ 'LEFT JOIN', [
350 'cat_title = page_title',
351 'page_namespace' => NS_CATEGORY
356 Hooks
::run( 'CategoryViewer::doCategoryQuery', [ $type, $res ] );
357 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
360 foreach ( $res as $row ) {
361 $title = Title
::newFromRow( $row );
362 $linkCache->addGoodLinkObjFromRow( $title, $row );
364 if ( $row->cl_collation
=== '' ) {
365 // Hack to make sure that while updating from 1.16 schema
366 // and db is inconsistent, that the sky doesn't fall.
367 // See r83544. Could perhaps be removed in a couple decades...
368 $humanSortkey = $row->cl_sortkey
;
370 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
373 if ( ++
$count > $this->limit
) {
374 # We've reached the one extra which shows that there
375 # are additional pages to be had. Stop here...
376 $this->nextPage
[$type] = $humanSortkey;
379 if ( $count == $this->limit
) {
380 $this->prevPage
[$type] = $humanSortkey;
383 if ( $title->getNamespace() == NS_CATEGORY
) {
384 $cat = Category
::newFromRow( $row, $title );
385 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
386 } elseif ( $title->getNamespace() == NS_FILE
) {
387 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
389 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
398 function getCategoryTop() {
399 $r = $this->getCategoryBottom();
402 : "<br style=\"clear:both;\"/>\n" . $r;
408 function getSubcategorySection() {
409 # Don't show subcategories section if there are none.
411 $rescnt = count( $this->children
);
412 $dbcnt = $this->cat
->getSubcatCount();
413 // This function should be called even if the result isn't used, it has side-effects
414 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
417 # Showing subcategories
418 $r .= "<div id=\"mw-subcategories\">\n";
419 $r .= '<h2>' . $this->msg( 'subcategories' )->parse() . "</h2>\n";
421 $r .= $this->getSectionPagingLinks( 'subcat' );
422 $r .= $this->formatList( $this->children
, $this->children_start_char
);
423 $r .= $this->getSectionPagingLinks( 'subcat' );
432 function getPagesSection() {
433 $ti = wfEscapeWikiText( $this->title
->getText() );
434 # Don't show articles section if there are none.
437 # @todo FIXME: Here and in the other two sections: we don't need to bother
438 # with this rigmarole if the entire category contents fit on one page
439 # and have already been retrieved. We can just use $rescnt in that
440 # case and save a query and some logic.
441 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
442 - $this->cat
->getFileCount();
443 $rescnt = count( $this->articles
);
444 // This function should be called even if the result isn't used, it has side-effects
445 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
448 $r = "<div id=\"mw-pages\">\n";
449 $r .= '<h2>' . $this->msg( 'category_header', $ti )->parse() . "</h2>\n";
451 $r .= $this->getSectionPagingLinks( 'page' );
452 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
453 $r .= $this->getSectionPagingLinks( 'page' );
462 function getImageSection() {
464 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
465 $dbcnt = $this->cat
->getFileCount();
466 // This function should be called even if the result isn't used, it has side-effects
467 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
470 $r .= "<div id=\"mw-category-media\">\n";
473 'category-media-header',
474 wfEscapeWikiText( $this->title
->getText() )
478 $r .= $this->getSectionPagingLinks( 'file' );
479 if ( $this->showGallery
) {
480 $r .= $this->gallery
->toHTML();
482 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
484 $r .= $this->getSectionPagingLinks( 'file' );
491 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
494 * @param string $type 'page', 'subcat', or 'file'
495 * @return string HTML output, possibly empty if there are no other pages
497 private function getSectionPagingLinks( $type ) {
498 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
499 // The new value for the until parameter should be pointing to the first
500 // result displayed on the page which is the second last result retrieved
501 // from the database.The next link should have a from parameter pointing
502 // to the until parameter of the current page.
503 if ( $this->nextPage
[$type] !== null ) {
504 return $this->pagingLinks( $this->prevPage
[$type], $this->until
[$type], $type );
506 // If the nextPage variable is null, it means that we have reached the first page
507 // and therefore the previous link should be disabled.
508 return $this->pagingLinks( null, $this->until
[$type], $type );
510 } elseif ( $this->nextPage
[$type] !== null
511 ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null )
513 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
522 function getCategoryBottom() {
527 * Format a list of articles chunked by letter, either as a
528 * bullet list or a columnar format, depending on the length.
530 * @param array $articles
531 * @param array $articles_start_char
536 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
538 if ( count( $articles ) > $cutoff ) {
539 $list = self
::columnList( $articles, $articles_start_char );
540 } elseif ( count( $articles ) > 0 ) {
541 // for short lists of articles in categories.
542 $list = self
::shortList( $articles, $articles_start_char );
545 $pageLang = $this->title
->getPageLanguage();
546 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
547 'class' => 'mw-content-' . $pageLang->getDir() ];
548 $list = Html
::rawElement( 'div', $attribs, $list );
554 * Format a list of articles chunked by letter in a three-column list, ordered
555 * vertically. This is used for categories with a significant number of pages.
557 * TODO: Take the headers into account when creating columns, so they're
558 * more visually equal.
560 * TODO: shortList and columnList are similar, need merging
562 * @param string[] $articles HTML links to each article
563 * @param string[] $articles_start_char The header characters for each article
564 * @return string HTML to output
567 static function columnList( $articles, $articles_start_char ) {
568 $columns = array_combine( $articles, $articles_start_char );
570 $ret = Html
::openElement( 'div', [ 'class' => 'mw-category' ] );
574 # Kind of like array_flip() here, but we keep duplicates in an
575 # array instead of dropping them.
576 foreach ( $columns as $article => $char ) {
577 if ( !isset( $colContents[$char] ) ) {
578 $colContents[$char] = [];
580 $colContents[$char][] = $article;
583 foreach ( $colContents as $char => $articles ) {
584 # Change space to non-breaking space to keep headers aligned
585 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
587 $ret .= '<div class="mw-category-group"><h3>' . $h3char;
591 $ret .= implode( "</li>\n<li>", $articles );
592 $ret .= '</li></ul></div>';
596 $ret .= Html
::closeElement( 'div' );
601 * Format a list of articles chunked by letter in a bullet list. This is used
602 * for categories with a small number of pages (when columns aren't needed).
603 * @param string[] $articles HTML links to each article
604 * @param string[] $articles_start_char The header characters for each article
605 * @return string HTML to output
608 static function shortList( $articles, $articles_start_char ) {
609 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
610 $r .= '<ul><li>' . $articles[0] . '</li>';
611 $articleCount = count( $articles );
612 for ( $index = 1; $index < $articleCount; $index++
) {
613 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
614 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
617 $r .= "<li>{$articles[$index]}</li>";
624 * Create paging links, as a helper method to getSectionPagingLinks().
626 * @param string $first The 'until' parameter for the generated URL
627 * @param string $last The 'from' parameter for the generated URL
628 * @param string $type A prefix for parameters, 'page' or 'subcat' or
630 * @return string HTML
632 private function pagingLinks( $first, $last, $type = '' ) {
633 $prevLink = $this->msg( 'prev-page' )->text();
635 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
636 if ( $first != '' ) {
637 $prevQuery = $this->query
;
638 $prevQuery["{$type}until"] = $first;
639 unset( $prevQuery["{$type}from"] );
640 $prevLink = $linkRenderer->makeKnownLink(
641 $this->addFragmentToTitle( $this->title
, $type ),
648 $nextLink = $this->msg( 'next-page' )->text();
651 $lastQuery = $this->query
;
652 $lastQuery["{$type}from"] = $last;
653 unset( $lastQuery["{$type}until"] );
654 $nextLink = $linkRenderer->makeKnownLink(
655 $this->addFragmentToTitle( $this->title
, $type ),
662 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
666 * Takes a title, and adds the fragment identifier that
667 * corresponds to the correct segment of the category.
669 * @param Title $title The title (usually $this->title)
670 * @param string $section Which section
671 * @throws MWException
674 private function addFragmentToTitle( $title, $section ) {
675 switch ( $section ) {
677 $fragment = 'mw-pages';
680 $fragment = 'mw-subcategories';
683 $fragment = 'mw-category-media';
686 throw new MWException( __METHOD__
.
687 " Invalid section $section." );
690 return Title
::makeTitle( $title->getNamespace(),
691 $title->getDBkey(), $fragment );
695 * What to do if the category table conflicts with the number of results
696 * returned? This function says what. Each type is considered independently
697 * of the other types.
699 * @param int $rescnt The number of items returned by our database query.
700 * @param int $dbcnt The number of items according to the category table.
701 * @param string $type 'subcat', 'article', or 'file'
702 * @return string A message giving the number of items, to output to HTML.
704 private function getCountMessage( $rescnt, $dbcnt, $type ) {
705 // There are three cases:
706 // 1) The category table figure seems sane. It might be wrong, but
707 // we can't do anything about it if we don't recalculate it on ev-
708 // ery category view.
709 // 2) The category table figure isn't sane, like it's smaller than the
710 // number of actual results, *but* the number of results is less
711 // than $this->limit and there's no offset. In this case we still
712 // know the right figure.
713 // 3) We have no idea.
715 // Check if there's a "from" or "until" for anything
717 // This is a little ugly, but we seem to use different names
718 // for the paging types then for the messages.
719 if ( $type === 'article' ) {
720 $pagingType = 'page';
725 $fromOrUntil = false;
726 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
727 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
732 if ( $dbcnt == $rescnt ||
733 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
735 // Case 1: seems sane.
737 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
738 // Case 2: not sane, but salvageable. Use the number of results.
739 // Since there are fewer than 200, we can also take this opportunity
740 // to refresh the incorrect category table entry -- which should be
741 // quick due to the small number of entries.
743 $category = $this->cat
;
744 DeferredUpdates
::addCallableUpdate( function () use ( $category ) {
745 $category->refreshCounts();
748 // Case 3: hopeless. Don't give a total count at all.
749 // Messages: category-subcat-count-limited, category-article-count-limited,
750 // category-file-count-limited
751 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
753 // Messages: category-subcat-count, category-article-count, category-file-count
754 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();