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 class CategoryViewer
extends ContextSource
{
37 public $articles_start_char;
43 public $children_start_char;
49 public $imgsNoGallery_start_char;
52 public $imgsNoGallery;
69 /** @var ImageGallery */
72 /** @var Category Category object for this page. */
75 /** @var array The original query array, to be used in generating paging links. */
79 * @since 1.19 $context is a second, required parameter
81 * @param IContextSource $context
82 * @param array $from An array with keys page, subcat,
83 * and file for offset of results of each section (since 1.17)
84 * @param array $until An array with 3 keys for until of each section (since 1.17)
87 function __construct( $title, IContextSource
$context, $from = [],
88 $until = [], $query = []
90 $this->title
= $title;
91 $this->setContext( $context );
92 $this->getOutput()->addModuleStyles( [
93 'mediawiki.action.view.categoryPage.styles'
96 $this->until
= $until;
97 $this->limit
= $context->getConfig()->get( 'CategoryPagingLimit' );
98 $this->cat
= Category
::newFromTitle( $title );
99 $this->query
= $query;
100 $this->collation
= Collation
::singleton();
101 unset( $this->query
['title'] );
105 * Format the category data list.
107 * @return string HTML output
109 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();
141 $langAttribs = [ 'lang' => $lang->getHtmlCode(), 'dir' => $lang->getDir() ];
142 # put a div around the headings which are in the user language
143 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
148 function clearCategoryState() {
149 $this->articles
= [];
150 $this->articles_start_char
= [];
151 $this->children
= [];
152 $this->children_start_char
= [];
153 if ( $this->showGallery
) {
154 // Note that null for mode is taken to mean use default.
155 $mode = $this->getRequest()->getVal( 'gallerymode', null );
157 $this->gallery
= ImageGalleryBase
::factory( $mode, $this->getContext() );
158 } catch ( Exception
$e ) {
159 // User specified something invalid, fallback to default.
160 $this->gallery
= ImageGalleryBase
::factory( false, $this->getContext() );
163 $this->gallery
->setHideBadImages();
165 $this->imgsNoGallery
= [];
166 $this->imgsNoGallery_start_char
= [];
171 * Add a subcategory to the internal lists, using a Category object
172 * @param Category $cat
173 * @param string $sortkey
174 * @param int $pageLength
176 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
177 // Subcategory; strip the 'Category' namespace from the link text.
178 $title = $cat->getTitle();
180 $this->children
[] = $this->generateLink(
183 $title->isRedirect(),
184 htmlspecialchars( $title->getText() )
187 $this->children_start_char
[] =
188 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
191 function generateLink( $type, Title
$title, $isRedirect, $html = null ) {
193 Hooks
::run( 'CategoryViewer::generateLink', [ $type, $title, $html, &$link ] );
194 if ( $link === null ) {
195 $link = Linker
::link( $title, $html );
198 $link = '<span class="redirect-in-category">' . $link . '</span>';
205 * Get the character to be used for sorting subcategories.
206 * If there's a link from Category:A to Category:B, the sortkey of the resulting
207 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
208 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
209 * else use sortkey...
211 * @param Title $title
212 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
215 function getSubcategorySortChar( $title, $sortkey ) {
218 if ( $title->getPrefixedText() == $sortkey ) {
219 $word = $title->getDBkey();
224 $firstChar = $this->collation
->getFirstLetter( $word );
226 return $wgContLang->convert( $firstChar );
230 * Add a page in the image namespace
231 * @param Title $title
232 * @param string $sortkey
233 * @param int $pageLength
234 * @param bool $isRedirect
236 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
238 if ( $this->showGallery
) {
239 $flip = $this->flip
['file'];
241 $this->gallery
->insert( $title );
243 $this->gallery
->add( $title );
246 $this->imgsNoGallery
[] = $this->generateLink( 'image', $title, $isRedirect );
248 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
249 $this->collation
->getFirstLetter( $sortkey ) );
254 * Add a miscellaneous page
255 * @param Title $title
256 * @param string $sortkey
257 * @param int $pageLength
258 * @param bool $isRedirect
260 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
263 $this->articles
[] = $this->generateLink( 'page', $title, $isRedirect );
265 $this->articles_start_char
[] = $wgContLang->convert(
266 $this->collation
->getFirstLetter( $sortkey ) );
269 function finaliseCategoryState() {
270 if ( $this->flip
['subcat'] ) {
271 $this->children
= array_reverse( $this->children
);
272 $this->children_start_char
= array_reverse( $this->children_start_char
);
274 if ( $this->flip
['page'] ) {
275 $this->articles
= array_reverse( $this->articles
);
276 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
278 if ( !$this->showGallery
&& $this->flip
['file'] ) {
279 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
280 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
284 function doCategoryQuery() {
285 $dbr = wfGetDB( DB_SLAVE
, 'category' );
298 $this->flip
= [ 'page' => false, 'subcat' => false, 'file' => false ];
300 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
301 # Get the sortkeys for start/end, if applicable. Note that if
302 # the collation in the database differs from the one
303 # set in $wgCategoryCollation, pagination might go totally haywire.
304 $extraConds = [ 'cl_type' => $type ];
305 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
306 $extraConds[] = 'cl_sortkey >= '
307 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
308 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
309 $extraConds[] = 'cl_sortkey < '
310 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
311 $this->flip
[$type] = true;
315 [ 'page', 'categorylinks', 'category' ],
316 [ 'page_id', 'page_title', 'page_namespace', 'page_len',
317 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
318 'cat_subcats', 'cat_pages', 'cat_files',
319 'cl_sortkey_prefix', 'cl_collation' ],
320 array_merge( [ 'cl_to' => $this->title
->getDBkey() ], $extraConds ),
323 'USE INDEX' => [ 'categorylinks' => 'cl_sortkey' ],
324 'LIMIT' => $this->limit +
1,
325 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
328 'categorylinks' => [ 'INNER JOIN', 'cl_from = page_id' ],
329 'category' => [ 'LEFT JOIN', [
330 'cat_title = page_title',
331 'page_namespace' => NS_CATEGORY
336 Hooks
::run( 'CategoryViewer::doCategoryQuery', [ $type, $res ] );
339 foreach ( $res as $row ) {
340 $title = Title
::newFromRow( $row );
341 if ( $row->cl_collation
=== '' ) {
342 // Hack to make sure that while updating from 1.16 schema
343 // and db is inconsistent, that the sky doesn't fall.
344 // See r83544. Could perhaps be removed in a couple decades...
345 $humanSortkey = $row->cl_sortkey
;
347 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
350 if ( ++
$count > $this->limit
) {
351 # We've reached the one extra which shows that there
352 # are additional pages to be had. Stop here...
353 $this->nextPage
[$type] = $humanSortkey;
356 if ( $count == $this->limit
) {
357 $this->prevPage
[$type] = $humanSortkey;
360 if ( $title->getNamespace() == NS_CATEGORY
) {
361 $cat = Category
::newFromRow( $row, $title );
362 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
363 } elseif ( $title->getNamespace() == NS_FILE
) {
364 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
366 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
375 function getCategoryTop() {
376 $r = $this->getCategoryBottom();
379 : "<br style=\"clear:both;\"/>\n" . $r;
385 function getSubcategorySection() {
386 # Don't show subcategories section if there are none.
388 $rescnt = count( $this->children
);
389 $dbcnt = $this->cat
->getSubcatCount();
390 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
393 # Showing subcategories
394 $r .= "<div id=\"mw-subcategories\">\n";
395 $r .= '<h2>' . $this->msg( 'subcategories' )->parse() . "</h2>\n";
397 $r .= $this->getSectionPagingLinks( 'subcat' );
398 $r .= $this->formatList( $this->children
, $this->children_start_char
);
399 $r .= $this->getSectionPagingLinks( 'subcat' );
408 function getPagesSection() {
409 $ti = wfEscapeWikiText( $this->title
->getText() );
410 # Don't show articles section if there are none.
413 # @todo FIXME: Here and in the other two sections: we don't need to bother
414 # with this rigmarole if the entire category contents fit on one page
415 # and have already been retrieved. We can just use $rescnt in that
416 # case and save a query and some logic.
417 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
418 - $this->cat
->getFileCount();
419 $rescnt = count( $this->articles
);
420 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
423 $r = "<div id=\"mw-pages\">\n";
424 $r .= '<h2>' . $this->msg( 'category_header', $ti )->parse() . "</h2>\n";
426 $r .= $this->getSectionPagingLinks( 'page' );
427 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
428 $r .= $this->getSectionPagingLinks( 'page' );
437 function getImageSection() {
439 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
441 $dbcnt = $this->cat
->getFileCount();
442 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
444 $r .= "<div id=\"mw-category-media\">\n";
447 'category-media-header',
448 wfEscapeWikiText( $this->title
->getText() )
452 $r .= $this->getSectionPagingLinks( 'file' );
453 if ( $this->showGallery
) {
454 $r .= $this->gallery
->toHTML();
456 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
458 $r .= $this->getSectionPagingLinks( 'file' );
465 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
468 * @param string $type 'page', 'subcat', or 'file'
469 * @return string HTML output, possibly empty if there are no other pages
471 private function getSectionPagingLinks( $type ) {
472 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
473 // The new value for the until parameter should be pointing to the first
474 // result displayed on the page which is the second last result retrieved
475 // from the database.The next link should have a from parameter pointing
476 // to the until parameter of the current page.
477 if ( $this->nextPage
[$type] !== null ) {
478 return $this->pagingLinks( $this->prevPage
[$type], $this->until
[$type], $type );
480 // If the nextPage variable is null, it means that we have reached the first page
481 // and therefore the previous link should be disabled.
482 return $this->pagingLinks( null, $this->until
[$type], $type );
484 } elseif ( $this->nextPage
[$type] !== null
485 ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null )
487 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
496 function getCategoryBottom() {
501 * Format a list of articles chunked by letter, either as a
502 * bullet list or a columnar format, depending on the length.
504 * @param array $articles
505 * @param array $articles_start_char
510 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
512 if ( count( $articles ) > $cutoff ) {
513 $list = self
::columnList( $articles, $articles_start_char );
514 } elseif ( count( $articles ) > 0 ) {
515 // for short lists of articles in categories.
516 $list = self
::shortList( $articles, $articles_start_char );
519 $pageLang = $this->title
->getPageLanguage();
520 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
521 'class' => 'mw-content-' . $pageLang->getDir() ];
522 $list = Html
::rawElement( 'div', $attribs, $list );
528 * Format a list of articles chunked by letter in a three-column
529 * list, ordered vertically.
531 * TODO: Take the headers into account when creating columns, so they're
532 * more visually equal.
534 * TODO: shortList and columnList are similar, need merging
536 * @param array $articles
537 * @param string[] $articles_start_char
541 static function columnList( $articles, $articles_start_char ) {
542 $columns = array_combine( $articles, $articles_start_char );
544 $ret = Html
::openElement( 'div', [ 'class' => 'mw-category' ] );
548 # Kind of like array_flip() here, but we keep duplicates in an
549 # array instead of dropping them.
550 foreach ( $columns as $article => $char ) {
551 if ( !isset( $colContents[$char] ) ) {
552 $colContents[$char] = [];
554 $colContents[$char][] = $article;
557 foreach ( $colContents as $char => $articles ) {
558 # Change space to non-breaking space to keep headers aligned
559 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
561 $ret .= '<div class="mw-category-group"><h3>' . $h3char;
565 $ret .= implode( "</li>\n<li>", $articles );
566 $ret .= '</li></ul></div>';
570 $ret .= Html
::closeElement( 'div' );
575 * Format a list of articles chunked by letter in a bullet list.
576 * @param array $articles
577 * @param string[] $articles_start_char
581 static function shortList( $articles, $articles_start_char ) {
582 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
583 $r .= '<ul><li>' . $articles[0] . '</li>';
584 $articleCount = count( $articles );
585 for ( $index = 1; $index < $articleCount; $index++
) {
586 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
587 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
590 $r .= "<li>{$articles[$index]}</li>";
597 * Create paging links, as a helper method to getSectionPagingLinks().
599 * @param string $first The 'until' parameter for the generated URL
600 * @param string $last The 'from' parameter for the generated URL
601 * @param string $type A prefix for parameters, 'page' or 'subcat' or
603 * @return string HTML
605 private function pagingLinks( $first, $last, $type = '' ) {
606 $prevLink = $this->msg( 'prev-page' )->text();
608 if ( $first != '' ) {
609 $prevQuery = $this->query
;
610 $prevQuery["{$type}until"] = $first;
611 unset( $prevQuery["{$type}from"] );
612 $prevLink = Linker
::linkKnown(
613 $this->addFragmentToTitle( $this->title
, $type ),
620 $nextLink = $this->msg( 'next-page' )->text();
623 $lastQuery = $this->query
;
624 $lastQuery["{$type}from"] = $last;
625 unset( $lastQuery["{$type}until"] );
626 $nextLink = Linker
::linkKnown(
627 $this->addFragmentToTitle( $this->title
, $type ),
634 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
638 * Takes a title, and adds the fragment identifier that
639 * corresponds to the correct segment of the category.
641 * @param Title $title The title (usually $this->title)
642 * @param string $section Which section
643 * @throws MWException
646 private function addFragmentToTitle( $title, $section ) {
647 switch ( $section ) {
649 $fragment = 'mw-pages';
652 $fragment = 'mw-subcategories';
655 $fragment = 'mw-category-media';
658 throw new MWException( __METHOD__
.
659 " Invalid section $section." );
662 return Title
::makeTitle( $title->getNamespace(),
663 $title->getDBkey(), $fragment );
667 * What to do if the category table conflicts with the number of results
668 * returned? This function says what. Each type is considered independently
669 * of the other types.
671 * @param int $rescnt The number of items returned by our database query.
672 * @param int $dbcnt The number of items according to the category table.
673 * @param string $type 'subcat', 'article', or 'file'
674 * @return string A message giving the number of items, to output to HTML.
676 private function getCountMessage( $rescnt, $dbcnt, $type ) {
677 // There are three cases:
678 // 1) The category table figure seems sane. It might be wrong, but
679 // we can't do anything about it if we don't recalculate it on ev-
680 // ery category view.
681 // 2) The category table figure isn't sane, like it's smaller than the
682 // number of actual results, *but* the number of results is less
683 // than $this->limit and there's no offset. In this case we still
684 // know the right figure.
685 // 3) We have no idea.
687 // Check if there's a "from" or "until" for anything
689 // This is a little ugly, but we seem to use different names
690 // for the paging types then for the messages.
691 if ( $type === 'article' ) {
692 $pagingType = 'page';
697 $fromOrUntil = false;
698 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
699 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
704 if ( $dbcnt == $rescnt ||
705 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
707 // Case 1: seems sane.
709 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
710 // Case 2: not sane, but salvageable. Use the number of results.
711 // Since there are fewer than 200, we can also take this opportunity
712 // to refresh the incorrect category table entry -- which should be
713 // quick due to the small number of entries.
715 $category = $this->cat
;
716 DeferredUpdates
::addCallableUpdate( function () use ( $category ) {
717 $category->refreshCounts();
720 // Case 3: hopeless. Don't give a total count at all.
721 // Messages: category-subcat-count-limited, category-article-count-limited,
722 // category-file-count-limited
723 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
725 // Messages: category-subcat-count, category-article-count, category-file-count
726 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();