11use InvalidArgumentException;
15use MediaWiki\Debug\DeprecationHelper;
19use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
36 use ProtectedHookAccessorTrait;
37 use DeprecationHelper;
80 public readonly array $from = [],
81 public readonly array $until = [],
82 private array $query = [],
84 $this->deprecatePublicPropertyFallback(
87 fn ():
Title => Title::newFromPageIdentity( $this->page ),
93 'mediawiki.action.styles',
99 $this->collation = $services->getCollationFactory()->getCategoryCollation();
100 $this->languageConverter = $services->getLanguageConverterFactory()->getLanguageConverter();
102 unset( $this->query[
'title'] );
112 && !$this->
getOutput()->getOutputFlag( ParserOutputFlags::NO_GALLERY );
122 if ( $html ===
'' ) {
123 $html = $this->
msg(
'category-empty' )->parseAsBlock();
126 # put a div around the headings which are in the user language
128 return Html::rawElement(
'div', [
129 'class' =>
'mw-category-generated',
130 'lang' => $lang->getHtmlCode(),
131 'dir' => $lang->getDir()
136 $this->articles = [];
137 $this->articles_start_char = [];
138 $this->children = [];
139 $this->children_start_char = [];
140 if ( $this->showGallery ) {
142 $mode = $this->
getRequest()->getVal(
'gallerymode',
null );
150 $this->gallery->setHideBadImages();
152 $this->imgsNoGallery = [];
153 $this->imgsNoGallery_start_char = [];
164 $page = $cat->getPage();
171 ->getPageByReference( $page );
172 if ( !$pageRecord ) {
176 $this->children[] = $this->generateLink(
179 $pageRecord->isRedirect(),
180 htmlspecialchars( str_replace(
'_',
' ', $pageRecord->getDBkey() ) )
183 $this->children_start_char[] =
184 $this->languageConverter->convert( $this->collation->getFirstLetter( $sortkey ) );
198 private function generateLink(
206 ->newFromPageReference( $page );
208 $this->getHookRunner()->onCategoryViewer__generateLink( $type, $legacyTitle, $html, $link );
209 if ( $link ===
null ) {
211 if ( $html !==
null ) {
212 $html =
new HtmlArmor( $html );
214 $link = $linkRenderer->makeLink( $page, $html );
217 $link = Html::rawElement(
219 [
'class' =>
'redirect-in-category' ],
237 $firstChar = $this->collation->getFirstLetter( $sortkey );
239 return $this->languageConverter->convert( $firstChar );
253 bool $isRedirect =
false
256 ->newFromPageReference( $page );
257 if ( $this->showGallery ) {
258 $flip = $this->flip[
'file'];
260 $this->gallery->insert( $title,
'',
'',
'', [], ImageGalleryBase::LOADING_LAZY );
262 $this->gallery->add( $title,
'',
'',
'', [], ImageGalleryBase::LOADING_LAZY );
265 $this->imgsNoGallery[] = $this->generateLink(
'image', $page, $isRedirect );
267 $this->imgsNoGallery_start_char[] =
268 $this->languageConverter->convert( $this->collation->getFirstLetter( $sortkey ) );
283 bool $isRedirect =
false
285 $this->articles[] = $this->generateLink(
'page', $page, $isRedirect );
287 $this->articles_start_char[] =
288 $this->languageConverter->convert( $this->collation->getFirstLetter( $sortkey ) );
292 if ( $this->flip[
'subcat'] ) {
293 $this->children = array_reverse( $this->children );
294 $this->children_start_char = array_reverse( $this->children_start_char );
296 if ( $this->flip[
'page'] ) {
297 $this->articles = array_reverse( $this->articles );
298 $this->articles_start_char = array_reverse( $this->articles_start_char );
300 if ( !$this->showGallery && $this->flip[
'file'] ) {
301 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
302 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
307 $connProvider = MediaWikiServices::getInstance()->getConnectionProvider();
308 $dbr = $connProvider->getReplicaDatabase();
309 $categoryLinksDbr = $connProvider->getReplicaDatabase( CategoryLinksTable::VIRTUAL_DOMAIN );
322 $this->flip = [
'page' =>
false,
'subcat' =>
false,
'file' => false ];
324 foreach ( [
'page',
'subcat',
'file' ] as $type ) {
325 # Get the sortkeys for start/end, if applicable. Note that if
326 # the collation in the database differs from the one
327 # set in $wgCategoryCollation, pagination might go totally haywire.
328 $extraConds = [
'cl_type' => $type ];
329 if ( isset( $this->from[$type] ) ) {
330 $extraConds[] = $categoryLinksDbr->expr(
334 $this->collation->getSortKey( $this->from[$type] )
336 } elseif ( isset( $this->until[$type] ) ) {
337 $extraConds[] = $categoryLinksDbr->expr(
341 $this->collation->getSortKey( $this->until[$type] )
343 $this->flip[$type] =
true;
346 $queryBuilder = $categoryLinksDbr->newSelectQueryBuilder();
347 $queryBuilder->select( array_merge(
348 LinkCache::getSelectFields(),
356 ->andWhere( $extraConds );
358 if ( $this->flip[$type] ) {
359 $queryBuilder->orderBy(
'cl_sortkey', SelectQueryBuilder::SORT_DESC );
361 $queryBuilder->orderBy(
'cl_sortkey' );
365 ->join(
'categorylinks',
null, [
'cl_from = page_id' ] )
366 ->join(
'linktarget',
null,
'cl_target_id = lt_id' )
367 ->straightJoin(
'collation',
null,
'cl_collation_id = collation_id' )
368 ->where( [
'lt_title' => $this->page->getDBkey(),
'lt_namespace' =>
NS_CATEGORY ] )
369 ->useIndex( [
'categorylinks' =>
'cl_sortkey_id' ] )
370 ->limit( $this->limit + 1 );
372 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
374 $categoryTitles = [];
377 foreach ( $res as $row ) {
380 $categoryTitles[] = $row->page_title;
384 $categoryFields = [
'cat_id',
'cat_title',
'cat_subcats',
'cat_pages',
'cat_files' ];
387 if ( $categoryTitles !== [] ) {
388 $categoryRes = $dbr->newSelectQueryBuilder()
389 ->select( $categoryFields )
391 ->where( [
'cat_title' => $categoryTitles ] )
392 ->caller( __METHOD__ )
395 foreach ( $categoryRes as $catRow ) {
396 $categoryData[$catRow->cat_title] = $catRow;
400 foreach ( $pageRows as $row ) {
402 $catRow = $categoryData[$row->page_title] ??
null;
403 foreach ( $categoryFields as $field ) {
404 $row->$field = $catRow->$field ??
null;
411 $this->getHookRunner()->onCategoryViewer__doCategoryQuery( $type, $res );
412 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
415 foreach ( $pageRows as $row ) {
416 $title = Title::newFromRow( $row );
417 $linkCache->addGoodLinkObjFromRow( $title, $row );
418 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
420 if ( ++$count > $this->limit ) {
421 # We've reached the one extra which shows that there
422 # are additional pages to be had. Stop here...
423 $this->nextPage[$type] = $humanSortkey;
426 if ( $count == $this->limit ) {
427 $this->prevPage[$type] = $humanSortkey;
431 $cat = Category::newFromRow( $row, $title );
432 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
433 } elseif ( $title->getNamespace() ===
NS_FILE ) {
434 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
436 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
446 # Don't show subcategories section if there are none.
448 $localCount = count( $this->children );
449 $databaseCount = $this->cat->getSubcatCount();
451 $countMessage = $this->getCountMessage( $localCount, $databaseCount,
'subcat' );
453 if ( $localCount > 0 ) {
454 $html .= Html::openElement(
'div', [
'id' =>
'mw-subcategories' ] ) .
"\n";
455 $html .= Html::rawElement(
'h2', [], $this->msg(
'subcategories' )->parse() ) .
"\n";
456 $html .= $countMessage;
457 $html .= $this->getSectionPagingLinks(
'subcat' );
458 $html .= $this->formatList( $this->children, $this->children_start_char );
459 $html .= $this->getSectionPagingLinks(
'subcat' );
460 $html .=
"\n" . Html::closeElement(
'div' );
469 $name = $this->getOutput()->getUnprefixedDisplayTitle();
470 # Don't show articles section if there are none.
473 # @todo FIXME: Here and in the other two sections: we don't need to bother
474 # with this rigmarole if the entire category contents fit on one page
475 # and have already been retrieved. We can just use $rescnt in that
476 # case and save a query and some logic.
477 $databaseCount = $this->cat->getPageCount( Category::COUNT_CONTENT_PAGES );
478 $localCount = count( $this->articles );
480 $countMessage = $this->getCountMessage( $localCount, $databaseCount,
'page' );
482 if ( $localCount > 0 ) {
483 $html .= Html::openElement(
'div', [
'id' =>
'mw-pages' ] ) .
"\n";
484 $html .= Html::rawElement(
487 $this->msg(
'category_header' )->rawParams( $name )->parse()
489 $html .= $countMessage;
490 $html .= $this->getSectionPagingLinks(
'page' );
491 $html .= $this->formatList( $this->articles, $this->articles_start_char );
492 $html .= $this->getSectionPagingLinks(
'page' );
493 $html .=
"\n" . Html::closeElement(
'div' );
502 $name = $this->getOutput()->getUnprefixedDisplayTitle();
504 $localCount = $this->showGallery ?
505 $this->gallery->count() :
506 count( $this->imgsNoGallery );
507 $databaseCount = $this->cat->getFileCount();
509 $countMessage = $this->getCountMessage( $localCount, $databaseCount,
'file' );
511 if ( $localCount > 0 ) {
512 $html .= Html::openElement(
'div', [
'id' =>
'mw-category-media' ] ) .
"\n";
513 $html .= Html::rawElement(
516 $this->msg(
'category-media-header' )->rawParams( $name )->parse()
518 $html .= $countMessage;
519 $html .= $this->getSectionPagingLinks(
'file' );
520 if ( $this->showGallery ) {
521 $html .= $this->gallery->toHTML();
523 $html .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
525 $html .= $this->getSectionPagingLinks(
'file' );
526 $html .=
"\n" . Html::closeElement(
'div' );
538 private function getSectionPagingLinks(
string $type ): string {
539 if ( isset( $this->until[$type] ) ) {
544 if ( $this->nextPage[$type] !==
null ) {
545 return $this->pagingLinks(
546 $this->prevPage[$type] ??
'',
555 return $this->pagingLinks(
561 } elseif ( $this->nextPage[$type] !==
null || isset( $this->from[$type] ) ) {
562 return $this->pagingLinks(
563 $this->from[$type] ??
'',
564 $this->nextPage[$type] ??
'',
582 private function formatList( array $articles, array $articles_start_char,
int $cutoff = 6 ): string {
584 if ( count( $articles ) > $cutoff ) {
585 $list = self::columnList( $articles, $articles_start_char );
586 } elseif ( count( $articles ) > 0 ) {
588 $list = self::shortList( $articles, $articles_start_char );
591 $pageLang = MediaWikiServices::getInstance()->getTitleFactory()
592 ->newFromPageIdentity( $this->page )
594 $attribs = [
'lang' => $pageLang->getHtmlCode(),
'dir' => $pageLang->getDir(),
595 'class' =>
'mw-content-' . $pageLang->getDir() ];
596 $list = Html::rawElement(
'div', $attribs, $list );
613 $articles_start_char,
614 $cssClasses =
'mw-category mw-category-columns'
616 $columns = array_combine( $articles, $articles_start_char );
618 $ret = Html::openElement(
'div', [
'class' => $cssClasses ] );
622 # Kind of like array_flip() here, but we keep duplicates in an
623 # array instead of dropping them.
624 foreach ( $columns as $article => $char ) {
625 $colContents[$char][] = $article;
628 foreach ( $colContents as $char => $articles ) {
629 # Change space to non-breaking space to keep headers aligned
630 $h3char = $char ===
' ' ?
"\u{00A0}" : htmlspecialchars( $char );
632 $ret .= Html::openElement(
'div', [
'class' =>
'mw-category-group' ] );
633 $ret .= Html::rawElement(
'h3', [], $h3char ) .
"\n";
634 $ret .= Html::openElement(
'ul' );
638 static fn ( $article ) => Html::rawElement(
'li', [], $article ),
642 $ret .= Html::closeElement(
'ul' ) . Html::closeElement(
'div' );
646 $ret .= Html::closeElement(
'div' );
658 public static function shortList( $articles, $articles_start_char ) {
659 return self::columnList( $articles, $articles_start_char,
'mw-category' );
670 private function pagingLinks(
string $first,
string $last,
string $type =
'' ): string {
671 $prevLink = $this->msg(
'prev-page' )->escaped();
673 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
674 if ( $first !=
'' ) {
675 $prevQuery = $this->query;
676 $prevQuery[
"{$type}until"] = $first;
677 unset( $prevQuery[
"{$type}from"] );
678 $prevLink = $linkRenderer->makeKnownLink(
679 $this->addFragmentToTitle( $this->page, $type ),
686 $nextLink = $this->msg(
'next-page' )->escaped();
689 $lastQuery = $this->query;
690 $lastQuery[
"{$type}from"] = $last;
691 unset( $lastQuery[
"{$type}until"] );
692 $nextLink = $linkRenderer->makeKnownLink(
693 $this->addFragmentToTitle( $this->page, $type ),
694 new HtmlArmor( $nextLink ),
700 return $this->msg(
'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
711 private function addFragmentToTitle( PageReference $page,
string $section ): LinkTarget {
712 $fragment = match ( $section ) {
713 'page' =>
'mw-pages',
714 'subcat' =>
'mw-subcategories',
715 'file' =>
'mw-category-media',
716 default =>
throw new InvalidArgumentException( __METHOD__ .
" Invalid section $section." )
731 private function getCountMessage(
int $localCount,
int $databaseCount,
string $type ): string {
746 $msgType = $type ===
'page' ?
'article' : $type;
748 $fromOrUntil =
false;
749 if ( isset( $this->from[$type] ) || isset( $this->until[$type] ) ) {
753 if ( $databaseCount == $localCount ||
754 ( ( $localCount == $this->limit || $fromOrUntil ) && $databaseCount > $localCount )
757 $totalCount = $databaseCount;
758 } elseif ( $localCount < $this->limit && !$fromOrUntil ) {
760 $totalCount = $localCount;
765 return $this->
msg(
"category-$msgType-count-limited" )->numParams( $localCount )->parseAsBlock();
768 return $this->
msg(
"category-$msgType-count" )->numParams( $localCount, $totalCount )->parseAsBlock();
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined('MW_SETUP_CALLBACK'))
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
setContext(IContextSource $context)
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
getContext()
Get the base IContextSource object.
A class containing constants representing the names of configuration variables.
const CategoryPagingLimit
Name constant for the CategoryPagingLimit setting, for use with Config::get()
const CategoryMagicGallery
Name constant for the CategoryMagicGallery setting, for use with Config::get()
Page existence and metadata cache.
Interface for objects which can provide a MediaWiki context on request.
getConfig()
Get the site configuration.
Interface for objects (potentially) representing an editable wiki page.