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
23 namespace MediaWiki\Category
;
28 use ImageGalleryClassNotFoundException
;
29 use InvalidArgumentException
;
30 use MediaWiki\Cache\LinkCache
;
31 use MediaWiki\Context\ContextSource
;
32 use MediaWiki\Context\IContextSource
;
33 use MediaWiki\Debug\DeprecationHelper
;
34 use MediaWiki\HookContainer\ProtectedHookAccessorTrait
;
35 use MediaWiki\Html\Html
;
36 use MediaWiki\Language\ILanguageConverter
;
37 use MediaWiki\Linker\LinkTarget
;
38 use MediaWiki\MainConfigNames
;
39 use MediaWiki\MediaWikiServices
;
40 use MediaWiki\Page\PageIdentity
;
41 use MediaWiki\Page\PageReference
;
42 use MediaWiki\Title\Title
;
43 use MediaWiki\Title\TitleValue
;
44 use Wikimedia\Rdbms\SelectQueryBuilder
;
46 class CategoryViewer
extends ContextSource
{
47 use ProtectedHookAccessorTrait
;
48 use DeprecationHelper
;
63 public $articles_start_char;
69 public $children_start_char;
75 public $imgsNoGallery_start_char;
78 public $imgsNoGallery;
89 /** @var PageIdentity */
95 /** @var ImageGalleryBase */
98 /** @var Category Category object for this page. */
101 /** @var array The original query array, to be used in generating paging links. */
104 /** @var ILanguageConverter */
105 private $languageConverter;
108 * @since 1.19 $context is a second, required parameter
109 * @param PageIdentity $page
110 * @param IContextSource $context
111 * @param array $from An array with keys page, subcat,
112 * and file for offset of results of each section (since 1.17)
113 * @param array $until An array with 3 keys for until of each section (since 1.17)
114 * @param array $query
116 public function __construct( PageIdentity
$page, IContextSource
$context, array $from = [],
117 array $until = [], array $query = []
121 $this->deprecatePublicPropertyFallback(
125 return Title
::newFromPageIdentity( $this->page
);
127 function ( PageIdentity
$page ) {
132 $this->setContext( $context );
133 $this->getOutput()->addModuleStyles( [
134 'mediawiki.action.styles',
137 $this->until
= $until;
138 $this->limit
= $context->getConfig()->get( MainConfigNames
::CategoryPagingLimit
);
139 $this->cat
= Category
::newFromTitle( $page );
140 $this->query
= $query;
141 $this->collation
= MediaWikiServices
::getInstance()->getCollationFactory()->getCategoryCollation();
142 $this->languageConverter
= MediaWikiServices
::getInstance()
143 ->getLanguageConverterFactory()->getLanguageConverter();
144 unset( $this->query
['title'] );
148 * Format the category data list.
150 * @return string HTML output
152 public function getHTML() {
153 $this->showGallery
= $this->getConfig()->get( MainConfigNames
::CategoryMagicGallery
)
154 && !$this->getOutput()->getNoGallery();
156 $this->clearCategoryState();
157 $this->doCategoryQuery();
158 $this->finaliseCategoryState();
160 $r = $this->getSubcategorySection() .
161 $this->getPagesSection() .
162 $this->getImageSection();
165 // If there is no category content to display, only
166 // show the top part of the navigation links.
167 // @todo FIXME: Cannot be completely suppressed because it
168 // is unknown if 'until' or 'from' makes this
170 $r = $this->getCategoryTop();
172 $r = $this->getCategoryTop() .
174 $this->getCategoryBottom();
177 // Give a proper message if category is empty
179 $r = $this->msg( 'category-empty' )->parseAsBlock();
182 $lang = $this->getLanguage();
184 'class' => 'mw-category-generated',
185 'lang' => $lang->getHtmlCode(),
186 'dir' => $lang->getDir()
188 # put a div around the headings which are in the user language
189 $r = Html
::rawElement( 'div', $attribs, $r );
194 protected function clearCategoryState() {
195 $this->articles
= [];
196 $this->articles_start_char
= [];
197 $this->children
= [];
198 $this->children_start_char
= [];
199 if ( $this->showGallery
) {
200 // Note that null for mode is taken to mean use default.
201 $mode = $this->getRequest()->getVal( 'gallerymode', null );
203 $this->gallery
= ImageGalleryBase
::factory( $mode, $this->getContext() );
204 } catch ( ImageGalleryClassNotFoundException
$e ) {
205 // User specified something invalid, fallback to default.
206 $this->gallery
= ImageGalleryBase
::factory( false, $this->getContext() );
209 $this->gallery
->setHideBadImages();
211 $this->imgsNoGallery
= [];
212 $this->imgsNoGallery_start_char
= [];
217 * Add a subcategory to the internal lists, using a Category object
218 * @param Category $cat
219 * @param string $sortkey
220 * @param int $pageLength
222 public function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
223 $page = $cat->getPage();
228 // Subcategory; strip the 'Category' namespace from the link text.
229 $pageRecord = MediaWikiServices
::getInstance()->getPageStore()
230 ->getPageByReference( $page );
231 if ( !$pageRecord ) {
235 $this->children
[] = $this->generateLink(
238 $pageRecord->isRedirect(),
239 htmlspecialchars( str_replace( '_', ' ', $pageRecord->getDBkey() ) )
242 $this->children_start_char
[] =
243 $this->getSubcategorySortChar( $page, $sortkey );
247 * @param string $type
248 * @param PageReference $page
249 * @param bool $isRedirect
250 * @param string|null $html
252 * Annotations needed to tell taint about HtmlArmor,
253 * due to the use of the hook it is not possible to avoid raw html handling here
254 * @param-taint $html tainted
255 * @return-taint escaped
257 private function generateLink(
258 string $type, PageReference
$page, bool $isRedirect, ?
string $html = null
261 $legacyTitle = MediaWikiServices
::getInstance()->getTitleFactory()
262 ->newFromPageReference( $page );
263 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
264 $this->getHookRunner()->onCategoryViewer__generateLink( $type, $legacyTitle, $html, $link );
265 if ( $link === null ) {
266 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
267 if ( $html !== null ) {
268 $html = new HtmlArmor( $html );
270 $link = $linkRenderer->makeLink( $page, $html );
273 $link = Html
::rawElement(
275 [ 'class' => 'redirect-in-category' ],
284 * Get the character to be used for sorting subcategories.
285 * If there's a link from Category:A to Category:B, the sortkey of the resulting
286 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
287 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
288 * else use sortkey...
290 * @param PageIdentity $page
291 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
294 public function getSubcategorySortChar( PageIdentity
$page, string $sortkey ): string {
295 $titleText = MediaWikiServices
::getInstance()->getTitleFormatter()
296 ->getPrefixedText( $page );
297 if ( $titleText === $sortkey ) {
298 $word = $page->getDBkey();
303 $firstChar = $this->collation
->getFirstLetter( $word );
305 return $this->languageConverter
->convert( $firstChar );
309 * Add a page in the image namespace
310 * @param PageReference $page
311 * @param string $sortkey
312 * @param int $pageLength
313 * @param bool $isRedirect
315 public function addImage(
316 PageReference
$page, string $sortkey, int $pageLength, bool $isRedirect = false
318 $title = MediaWikiServices
::getInstance()->getTitleFactory()
319 ->newFromPageReference( $page );
320 if ( $this->showGallery
) {
321 $flip = $this->flip
['file'];
323 $this->gallery
->insert( $title, '', '', '', [], ImageGalleryBase
::LOADING_LAZY
);
325 $this->gallery
->add( $title, '', '', '', [], ImageGalleryBase
::LOADING_LAZY
);
328 $this->imgsNoGallery
[] = $this->generateLink( 'image', $page, $isRedirect );
330 $this->imgsNoGallery_start_char
[] =
331 $this->languageConverter
->convert( $this->collation
->getFirstLetter( $sortkey ) );
336 * Add a miscellaneous page
337 * @param PageReference $page
338 * @param string $sortkey
339 * @param int $pageLength
340 * @param bool $isRedirect
342 public function addPage(
346 bool $isRedirect = false
348 $this->articles
[] = $this->generateLink( 'page', $page, $isRedirect );
350 $this->articles_start_char
[] =
351 $this->languageConverter
->convert( $this->collation
->getFirstLetter( $sortkey ) );
354 protected function finaliseCategoryState() {
355 if ( $this->flip
['subcat'] ) {
356 $this->children
= array_reverse( $this->children
);
357 $this->children_start_char
= array_reverse( $this->children_start_char
);
359 if ( $this->flip
['page'] ) {
360 $this->articles
= array_reverse( $this->articles
);
361 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
363 if ( !$this->showGallery
&& $this->flip
['file'] ) {
364 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
365 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
369 protected function doCategoryQuery() {
370 $dbr = MediaWikiServices
::getInstance()->getConnectionProvider()->getReplicaDatabase();
383 $this->flip
= [ 'page' => false, 'subcat' => false, 'file' => false ];
385 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
386 # Get the sortkeys for start/end, if applicable. Note that if
387 # the collation in the database differs from the one
388 # set in $wgCategoryCollation, pagination might go totally haywire.
389 $extraConds = [ 'cl_type' => $type ];
390 if ( isset( $this->from
[$type] ) ) {
391 $extraConds[] = $dbr->expr(
394 $this->collation
->getSortKey( $this->from
[$type] )
396 } elseif ( isset( $this->until
[$type] ) ) {
397 $extraConds[] = $dbr->expr(
400 $this->collation
->getSortKey( $this->until
[$type] )
402 $this->flip
[$type] = true;
405 $queryBuilder = $dbr->newSelectQueryBuilder();
406 $queryBuilder->select( array_merge(
407 LinkCache
::getSelectFields(),
420 ->where( [ 'cl_to' => $this->page
->getDBkey() ] )
421 ->andWhere( $extraConds )
422 ->useIndex( [ 'categorylinks' => 'cl_sortkey' ] );
424 if ( $this->flip
[$type] ) {
425 $queryBuilder->orderBy( 'cl_sortkey', SelectQueryBuilder
::SORT_DESC
);
427 $queryBuilder->orderBy( 'cl_sortkey' );
431 ->join( 'categorylinks', null, [ 'cl_from = page_id' ] )
432 ->leftJoin( 'category', null, [
433 'cat_title = page_title',
434 'page_namespace' => NS_CATEGORY
436 ->limit( $this->limit +
1 )
437 ->caller( __METHOD__
);
439 $res = $queryBuilder->fetchResultSet();
441 $this->getHookRunner()->onCategoryViewer__doCategoryQuery( $type, $res );
442 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
445 foreach ( $res as $row ) {
446 $title = Title
::newFromRow( $row );
447 $linkCache->addGoodLinkObjFromRow( $title, $row );
449 if ( $row->cl_collation
=== '' ) {
450 // Hack to make sure that while updating from 1.16 schema
451 // and db is inconsistent, that the sky doesn't fall.
452 // See r83544. Could perhaps be removed in a couple decades...
453 $humanSortkey = $row->cl_sortkey
;
455 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
458 if ( ++
$count > $this->limit
) {
459 # We've reached the one extra which shows that there
460 # are additional pages to be had. Stop here...
461 $this->nextPage
[$type] = $humanSortkey;
464 if ( $count == $this->limit
) {
465 $this->prevPage
[$type] = $humanSortkey;
468 if ( $title->getNamespace() === NS_CATEGORY
) {
469 $cat = Category
::newFromRow( $row, $title );
470 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
471 } elseif ( $title->getNamespace() === NS_FILE
) {
472 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
474 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
483 protected function getCategoryTop() {
484 $r = $this->getCategoryBottom();
487 : "<br style=\"clear:both;\"/>\n" . $r;
493 protected function getSubcategorySection() {
494 # Don't show subcategories section if there are none.
496 $rescnt = count( $this->children
);
497 $dbcnt = $this->cat
->getSubcatCount();
498 // This function should be called even if the result isn't used, it has side-effects
499 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
502 # Showing subcategories
503 $r .= Html
::openElement( 'div', [ 'id' => 'mw-subcategories' ] ) . "\n";
504 $r .= Html
::rawElement( 'h2', [], $this->msg( 'subcategories' )->parse() ) . "\n";
506 $r .= $this->getSectionPagingLinks( 'subcat' );
507 $r .= $this->formatList( $this->children
, $this->children_start_char
);
508 $r .= $this->getSectionPagingLinks( 'subcat' );
509 $r .= "\n" . Html
::closeElement( 'div' );
517 protected function getPagesSection() {
518 $name = $this->getOutput()->getUnprefixedDisplayTitle();
519 # Don't show articles section if there are none.
522 # @todo FIXME: Here and in the other two sections: we don't need to bother
523 # with this rigmarole if the entire category contents fit on one page
524 # and have already been retrieved. We can just use $rescnt in that
525 # case and save a query and some logic.
526 $dbcnt = $this->cat
->getPageCount( Category
::COUNT_CONTENT_PAGES
);
527 $rescnt = count( $this->articles
);
528 // This function should be called even if the result isn't used, it has side-effects
529 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
532 $r .= Html
::openElement( 'div', [ 'id' => 'mw-pages' ] ) . "\n";
533 $r .= Html
::rawElement(
536 $this->msg( 'category_header' )->rawParams( $name )->parse()
539 $r .= $this->getSectionPagingLinks( 'page' );
540 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
541 $r .= $this->getSectionPagingLinks( 'page' );
542 $r .= "\n" . Html
::closeElement( 'div' );
550 protected function getImageSection() {
551 $name = $this->getOutput()->getUnprefixedDisplayTitle();
553 $rescnt = $this->showGallery ?
554 $this->gallery
->count() :
555 count( $this->imgsNoGallery ??
[] );
556 $dbcnt = $this->cat
->getFileCount();
557 // This function should be called even if the result isn't used, it has side-effects
558 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
561 $r .= Html
::openElement( 'div', [ 'id' => 'mw-category-media' ] ) . "\n";
562 $r .= Html
::rawElement(
565 $this->msg( 'category-media-header' )->rawParams( $name )->parse()
568 $r .= $this->getSectionPagingLinks( 'file' );
569 if ( $this->showGallery
) {
570 $r .= $this->gallery
->toHTML();
572 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
574 $r .= $this->getSectionPagingLinks( 'file' );
575 $r .= "\n" . Html
::closeElement( 'div' );
581 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
584 * @param string $type 'page', 'subcat', or 'file'
585 * @return string HTML output, possibly empty if there are no other pages
587 private function getSectionPagingLinks( $type ) {
588 if ( isset( $this->until
[$type] ) ) {
589 // The new value for the until parameter should be pointing to the first
590 // result displayed on the page which is the second last result retrieved
591 // from the database.The next link should have a from parameter pointing
592 // to the until parameter of the current page.
593 if ( $this->nextPage
[$type] !== null ) {
594 return $this->pagingLinks(
595 $this->prevPage
[$type] ??
'',
601 // If the nextPage variable is null, it means that we have reached the first page
602 // and therefore the previous link should be disabled.
603 return $this->pagingLinks(
608 } elseif ( $this->nextPage
[$type] !== null ||
isset( $this->from
[$type] ) ) {
609 return $this->pagingLinks(
610 $this->from
[$type] ??
'',
611 $this->nextPage
[$type],
622 protected function getCategoryBottom() {
627 * Format a list of articles chunked by letter, either as a
628 * bullet list or a columnar format, depending on the length.
630 * @param array $articles
631 * @param array $articles_start_char
636 private function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
638 if ( count( $articles ) > $cutoff ) {
639 $list = self
::columnList( $articles, $articles_start_char );
640 } elseif ( count( $articles ) > 0 ) {
641 // for short lists of articles in categories.
642 $list = self
::shortList( $articles, $articles_start_char );
645 $pageLang = MediaWikiServices
::getInstance()->getTitleFactory()
646 ->newFromPageIdentity( $this->page
)
648 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
649 'class' => 'mw-content-' . $pageLang->getDir() ];
650 $list = Html
::rawElement( 'div', $attribs, $list );
656 * Format a list of articles chunked by letter in a three-column list, ordered
657 * vertically. This is used for categories with a significant number of pages.
659 * @param string[] $articles HTML links to each article
660 * @param string[] $articles_start_char The header characters for each article
661 * @param string $cssClasses CSS classes for the wrapper element
662 * @return string HTML to output
665 public static function columnList(
667 $articles_start_char,
668 $cssClasses = 'mw-category mw-category-columns'
670 $columns = array_combine( $articles, $articles_start_char );
672 $ret = Html
::openElement( 'div', [ 'class' => $cssClasses ] );
676 # Kind of like array_flip() here, but we keep duplicates in an
677 # array instead of dropping them.
678 foreach ( $columns as $article => $char ) {
679 $colContents[$char][] = $article;
682 foreach ( $colContents as $char => $articles ) {
683 # Change space to non-breaking space to keep headers aligned
684 $h3char = $char === ' ' ?
"\u{00A0}" : htmlspecialchars( $char );
686 $ret .= Html
::openElement( 'div', [ 'class' => 'mw-category-group' ] );
687 $ret .= Html
::rawElement( 'h3', [], $h3char ) . "\n";
688 $ret .= Html
::openElement( 'ul' );
692 static function ( $article ) {
693 return Html
::rawElement( 'li', [], $article );
698 $ret .= Html
::closeElement( 'ul' ) . Html
::closeElement( 'div' );
702 $ret .= Html
::closeElement( 'div' );
707 * Format a list of articles chunked by letter in a bullet list. This is used
708 * for categories with a small number of pages (when columns aren't needed).
709 * @param string[] $articles HTML links to each article
710 * @param string[] $articles_start_char The header characters for each article
711 * @return string HTML to output
714 public static function shortList( $articles, $articles_start_char ) {
715 return self
::columnList( $articles, $articles_start_char, 'mw-category' );
719 * Create paging links, as a helper method to getSectionPagingLinks().
721 * @param string $first The 'until' parameter for the generated URL
722 * @param string $last The 'from' parameter for the generated URL
723 * @param string $type A prefix for parameters, 'page' or 'subcat' or
725 * @return string HTML
727 private function pagingLinks( $first, $last, $type = '' ) {
728 $prevLink = $this->msg( 'prev-page' )->escaped();
730 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
731 if ( $first != '' ) {
732 $prevQuery = $this->query
;
733 $prevQuery["{$type}until"] = $first;
734 unset( $prevQuery["{$type}from"] );
735 $prevLink = $linkRenderer->makeKnownLink(
736 $this->addFragmentToTitle( $this->page
, $type ),
737 new HtmlArmor( $prevLink ),
743 $nextLink = $this->msg( 'next-page' )->escaped();
746 $lastQuery = $this->query
;
747 $lastQuery["{$type}from"] = $last;
748 unset( $lastQuery["{$type}until"] );
749 $nextLink = $linkRenderer->makeKnownLink(
750 $this->addFragmentToTitle( $this->page
, $type ),
751 new HtmlArmor( $nextLink ),
757 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
761 * Takes a title, and adds the fragment identifier that
762 * corresponds to the correct segment of the category.
764 * @param PageReference $page The title (usually $this->title)
765 * @param string $section Which section
768 private function addFragmentToTitle( PageReference
$page, string $section ): LinkTarget
{
769 switch ( $section ) {
771 $fragment = 'mw-pages';
774 $fragment = 'mw-subcategories';
777 $fragment = 'mw-category-media';
780 throw new InvalidArgumentException( __METHOD__
.
781 " Invalid section $section." );
784 return new TitleValue( $page->getNamespace(),
785 $page->getDBkey(), $fragment );
789 * What to do if the category table conflicts with the number of results
790 * returned? This function says what. Each type is considered independently
791 * of the other types.
793 * @param int $rescnt The number of items returned by our database query.
794 * @param int $dbcnt The number of items according to the category table.
795 * @param string $type 'subcat', 'article', or 'file'
796 * @return string A message giving the number of items, to output to HTML.
798 private function getCountMessage( $rescnt, $dbcnt, $type ) {
799 // There are three cases:
800 // 1) The category table figure seems good. It might be wrong, but
801 // we can't do anything about it if we don't recalculate it on ev-
802 // ery category view.
803 // 2) The category table figure isn't good, like it's smaller than the
804 // number of actual results, *but* the number of results is less
805 // than $this->limit and there's no offset. In this case we still
806 // know the right figure.
807 // 3) We have no idea.
809 // Check if there's a "from" or "until" for anything
811 // This is a little ugly, but we seem to use different names
812 // for the paging types then for the messages.
813 if ( $type === 'article' ) {
814 $pagingType = 'page';
819 $fromOrUntil = false;
820 if ( isset( $this->from
[$pagingType] ) ||
isset( $this->until
[$pagingType] ) ) {
824 if ( $dbcnt == $rescnt ||
825 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
827 // Case 1: seems good.
829 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
830 // Case 2: not good, but salvageable. Use the number of results.
833 // Case 3: hopeless. Don't give a total count at all.
834 // Messages: category-subcat-count-limited, category-article-count-limited,
835 // category-file-count-limited
836 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
838 // Messages: category-subcat-count, category-article-count, category-file-count
839 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();
843 /** @deprecated class alias since 1.40 */
844 class_alias( CategoryViewer
::class, 'CategoryViewer' );