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() {
111 $this->showGallery
= $this->getConfig()->get( 'CategoryMagicGallery' )
112 && !$this->getOutput()->mNoGallery
;
114 $this->clearCategoryState();
115 $this->doCategoryQuery();
116 $this->finaliseCategoryState();
118 $r = $this->getSubcategorySection() .
119 $this->getPagesSection() .
120 $this->getImageSection();
123 // If there is no category content to display, only
124 // show the top part of the navigation links.
125 // @todo FIXME: Cannot be completely suppressed because it
126 // is unknown if 'until' or 'from' makes this
128 $r = $r . $this->getCategoryTop();
130 $r = $this->getCategoryTop() .
132 $this->getCategoryBottom();
135 // Give a proper message if category is empty
137 $r = $this->msg( 'category-empty' )->parseAsBlock();
140 $lang = $this->getLanguage();
142 'class' => 'mw-category-generated',
143 'lang' => $lang->getHtmlCode(),
144 'dir' => $lang->getDir()
146 # put a div around the headings which are in the user language
147 $r = Html
::openElement( 'div', $attribs ) . $r . '</div>';
152 function clearCategoryState() {
153 $this->articles
= [];
154 $this->articles_start_char
= [];
155 $this->children
= [];
156 $this->children_start_char
= [];
157 if ( $this->showGallery
) {
158 // Note that null for mode is taken to mean use default.
159 $mode = $this->getRequest()->getVal( 'gallerymode', null );
161 $this->gallery
= ImageGalleryBase
::factory( $mode, $this->getContext() );
162 } catch ( Exception
$e ) {
163 // User specified something invalid, fallback to default.
164 $this->gallery
= ImageGalleryBase
::factory( false, $this->getContext() );
167 $this->gallery
->setHideBadImages();
169 $this->imgsNoGallery
= [];
170 $this->imgsNoGallery_start_char
= [];
175 * Add a subcategory to the internal lists, using a Category object
176 * @param Category $cat
177 * @param string $sortkey
178 * @param int $pageLength
180 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
181 // Subcategory; strip the 'Category' namespace from the link text.
182 $title = $cat->getTitle();
184 $this->children
[] = $this->generateLink(
187 $title->isRedirect(),
188 htmlspecialchars( $title->getText() )
191 $this->children_start_char
[] =
192 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
195 function generateLink( $type, Title
$title, $isRedirect, $html = null ) {
197 Hooks
::run( 'CategoryViewer::generateLink', [ $type, $title, $html, &$link ] );
198 if ( $link === null ) {
199 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
200 if ( $html !== null ) {
201 $html = new HtmlArmor( $html );
203 $link = $linkRenderer->makeLink( $title, $html );
206 $link = '<span class="redirect-in-category">' . $link . '</span>';
213 * Get the character to be used for sorting subcategories.
214 * If there's a link from Category:A to Category:B, the sortkey of the resulting
215 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
216 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
217 * else use sortkey...
219 * @param Title $title
220 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
223 function getSubcategorySortChar( $title, $sortkey ) {
224 if ( $title->getPrefixedText() == $sortkey ) {
225 $word = $title->getDBkey();
230 $firstChar = $this->collation
->getFirstLetter( $word );
232 return MediaWikiServices
::getInstance()->getContentLanguage()->convert( $firstChar );
236 * Add a page in the image namespace
237 * @param Title $title
238 * @param string $sortkey
239 * @param int $pageLength
240 * @param bool $isRedirect
242 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
[] = MediaWikiServices
::getInstance()->
254 getContentLanguage()->convert( $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 ) {
266 $this->articles
[] = $this->generateLink( 'page', $title, $isRedirect );
268 $this->articles_start_char
[] = MediaWikiServices
::getInstance()->
269 getContentLanguage()->convert( $this->collation
->getFirstLetter( $sortkey ) );
272 function finaliseCategoryState() {
273 if ( $this->flip
['subcat'] ) {
274 $this->children
= array_reverse( $this->children
);
275 $this->children_start_char
= array_reverse( $this->children_start_char
);
277 if ( $this->flip
['page'] ) {
278 $this->articles
= array_reverse( $this->articles
);
279 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
281 if ( !$this->showGallery
&& $this->flip
['file'] ) {
282 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
283 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
287 function doCategoryQuery() {
288 $dbr = wfGetDB( DB_REPLICA
, 'category' );
301 $this->flip
= [ 'page' => false, 'subcat' => false, 'file' => false ];
303 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
304 # Get the sortkeys for start/end, if applicable. Note that if
305 # the collation in the database differs from the one
306 # set in $wgCategoryCollation, pagination might go totally haywire.
307 $extraConds = [ 'cl_type' => $type ];
308 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
309 $extraConds[] = 'cl_sortkey >= '
310 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
311 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
312 $extraConds[] = 'cl_sortkey < '
313 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
314 $this->flip
[$type] = true;
318 [ 'page', 'categorylinks', 'category' ],
320 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' );
426 function getPagesSection() {
427 $ti = wfEscapeWikiText( $this->title
->getText() );
428 # Don't show articles section if there are none.
431 # @todo FIXME: Here and in the other two sections: we don't need to bother
432 # with this rigmarole if the entire category contents fit on one page
433 # and have already been retrieved. We can just use $rescnt in that
434 # case and save a query and some logic.
435 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
436 - $this->cat
->getFileCount();
437 $rescnt = count( $this->articles
);
438 // This function should be called even if the result isn't used, it has side-effects
439 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
442 $r = "<div id=\"mw-pages\">\n";
443 $r .= '<h2>' . $this->msg( 'category_header', $ti )->parse() . "</h2>\n";
445 $r .= $this->getSectionPagingLinks( 'page' );
446 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
447 $r .= $this->getSectionPagingLinks( 'page' );
456 function getImageSection() {
458 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
459 $dbcnt = $this->cat
->getFileCount();
460 // This function should be called even if the result isn't used, it has side-effects
461 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
464 $r .= "<div id=\"mw-category-media\">\n";
467 'category-media-header',
468 wfEscapeWikiText( $this->title
->getText() )
472 $r .= $this->getSectionPagingLinks( 'file' );
473 if ( $this->showGallery
) {
474 $r .= $this->gallery
->toHTML();
476 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
478 $r .= $this->getSectionPagingLinks( 'file' );
485 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
488 * @param string $type 'page', 'subcat', or 'file'
489 * @return string HTML output, possibly empty if there are no other pages
491 private function getSectionPagingLinks( $type ) {
492 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
493 // The new value for the until parameter should be pointing to the first
494 // result displayed on the page which is the second last result retrieved
495 // from the database.The next link should have a from parameter pointing
496 // to the until parameter of the current page.
497 if ( $this->nextPage
[$type] !== null ) {
498 return $this->pagingLinks( $this->prevPage
[$type], $this->until
[$type], $type );
500 // If the nextPage variable is null, it means that we have reached the first page
501 // and therefore the previous link should be disabled.
502 return $this->pagingLinks( null, $this->until
[$type], $type );
504 } elseif ( $this->nextPage
[$type] !== null
505 ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null )
507 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
516 function getCategoryBottom() {
521 * Format a list of articles chunked by letter, either as a
522 * bullet list or a columnar format, depending on the length.
524 * @param array $articles
525 * @param array $articles_start_char
530 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
532 if ( count( $articles ) > $cutoff ) {
533 $list = self
::columnList( $articles, $articles_start_char );
534 } elseif ( count( $articles ) > 0 ) {
535 // for short lists of articles in categories.
536 $list = self
::shortList( $articles, $articles_start_char );
539 $pageLang = $this->title
->getPageLanguage();
540 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
541 'class' => 'mw-content-' . $pageLang->getDir() ];
542 $list = Html
::rawElement( 'div', $attribs, $list );
548 * Format a list of articles chunked by letter in a three-column list, ordered
549 * vertically. This is used for categories with a significant number of pages.
551 * TODO: Take the headers into account when creating columns, so they're
552 * more visually equal.
554 * TODO: shortList and columnList are similar, need merging
556 * @param string[] $articles HTML links to each article
557 * @param string[] $articles_start_char The header characters for each article
558 * @return string HTML to output
561 static function columnList( $articles, $articles_start_char ) {
562 $columns = array_combine( $articles, $articles_start_char );
564 $ret = Html
::openElement( 'div', [ 'class' => 'mw-category' ] );
568 # Kind of like array_flip() here, but we keep duplicates in an
569 # array instead of dropping them.
570 foreach ( $columns as $article => $char ) {
571 if ( !isset( $colContents[$char] ) ) {
572 $colContents[$char] = [];
574 $colContents[$char][] = $article;
577 foreach ( $colContents as $char => $articles ) {
578 # Change space to non-breaking space to keep headers aligned
579 $h3char = $char === ' ' ?
"\u{00A0}" : htmlspecialchars( $char );
581 $ret .= '<div class="mw-category-group"><h3>' . $h3char;
585 $ret .= implode( "</li>\n<li>", $articles );
586 $ret .= '</li></ul></div>';
590 $ret .= Html
::closeElement( 'div' );
595 * Format a list of articles chunked by letter in a bullet list. This is used
596 * for categories with a small number of pages (when columns aren't needed).
597 * @param string[] $articles HTML links to each article
598 * @param string[] $articles_start_char The header characters for each article
599 * @return string HTML to output
602 static function shortList( $articles, $articles_start_char ) {
603 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
604 $r .= '<ul><li>' . $articles[0] . '</li>';
605 $articleCount = count( $articles );
606 for ( $index = 1; $index < $articleCount; $index++
) {
607 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
608 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
611 $r .= "<li>{$articles[$index]}</li>";
618 * Create paging links, as a helper method to getSectionPagingLinks().
620 * @param string $first The 'until' parameter for the generated URL
621 * @param string $last The 'from' parameter for the generated URL
622 * @param string $type A prefix for parameters, 'page' or 'subcat' or
624 * @return string HTML
626 private function pagingLinks( $first, $last, $type = '' ) {
627 $prevLink = $this->msg( 'prev-page' )->escaped();
629 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
630 if ( $first != '' ) {
631 $prevQuery = $this->query
;
632 $prevQuery["{$type}until"] = $first;
633 unset( $prevQuery["{$type}from"] );
634 $prevLink = $linkRenderer->makeKnownLink(
635 $this->addFragmentToTitle( $this->title
, $type ),
636 new HtmlArmor( $prevLink ),
642 $nextLink = $this->msg( 'next-page' )->escaped();
645 $lastQuery = $this->query
;
646 $lastQuery["{$type}from"] = $last;
647 unset( $lastQuery["{$type}until"] );
648 $nextLink = $linkRenderer->makeKnownLink(
649 $this->addFragmentToTitle( $this->title
, $type ),
650 new HtmlArmor( $nextLink ),
656 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
660 * Takes a title, and adds the fragment identifier that
661 * corresponds to the correct segment of the category.
663 * @param Title $title The title (usually $this->title)
664 * @param string $section Which section
665 * @throws MWException
668 private function addFragmentToTitle( $title, $section ) {
669 switch ( $section ) {
671 $fragment = 'mw-pages';
674 $fragment = 'mw-subcategories';
677 $fragment = 'mw-category-media';
680 throw new MWException( __METHOD__
.
681 " Invalid section $section." );
684 return Title
::makeTitle( $title->getNamespace(),
685 $title->getDBkey(), $fragment );
689 * What to do if the category table conflicts with the number of results
690 * returned? This function says what. Each type is considered independently
691 * of the other types.
693 * @param int $rescnt The number of items returned by our database query.
694 * @param int $dbcnt The number of items according to the category table.
695 * @param string $type 'subcat', 'article', or 'file'
696 * @return string A message giving the number of items, to output to HTML.
698 private function getCountMessage( $rescnt, $dbcnt, $type ) {
699 // There are three cases:
700 // 1) The category table figure seems sane. It might be wrong, but
701 // we can't do anything about it if we don't recalculate it on ev-
702 // ery category view.
703 // 2) The category table figure isn't sane, like it's smaller than the
704 // number of actual results, *but* the number of results is less
705 // than $this->limit and there's no offset. In this case we still
706 // know the right figure.
707 // 3) We have no idea.
709 // Check if there's a "from" or "until" for anything
711 // This is a little ugly, but we seem to use different names
712 // for the paging types then for the messages.
713 if ( $type === 'article' ) {
714 $pagingType = 'page';
719 $fromOrUntil = false;
720 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
721 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
726 if ( $dbcnt == $rescnt ||
727 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
729 // Case 1: seems sane.
731 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
732 // Case 2: not sane, but salvageable. Use the number of results.
735 // Case 3: hopeless. Don't give a total count at all.
736 // Messages: category-subcat-count-limited, category-article-count-limited,
737 // category-file-count-limited
738 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
740 // Messages: category-subcat-count, category-article-count, category-file-count
741 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();