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 protected $children_start_char;
46 protected $showGallery;
49 protected $imgsNoGallery_start_char;
52 protected $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 = array(),
88 $until = array(), $query = array()
90 global $wgCategoryPagingLimit;
91 $this->title
= $title;
92 $this->setContext( $context );
94 $this->until
= $until;
95 $this->limit
= $wgCategoryPagingLimit;
96 $this->cat
= Category
::newFromTitle( $title );
97 $this->query
= $query;
98 $this->collation
= Collation
::singleton();
99 unset( $this->query
['title'] );
103 * Format the category data list.
105 * @return string HTML output
107 public function getHTML() {
108 global $wgCategoryMagicGallery;
109 wfProfileIn( __METHOD__
);
111 $this->showGallery
= $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery
;
113 $this->clearCategoryState();
114 $this->doCategoryQuery();
115 $this->finaliseCategoryState();
117 $r = $this->getSubcategorySection() .
118 $this->getPagesSection() .
119 $this->getImageSection();
122 // If there is no category content to display, only
123 // show the top part of the navigation links.
124 // @todo FIXME: Cannot be completely suppressed because it
125 // is unknown if 'until' or 'from' makes this
127 $r = $r . $this->getCategoryTop();
129 $r = $this->getCategoryTop() .
131 $this->getCategoryBottom();
134 // Give a proper message if category is empty
136 $r = $this->msg( 'category-empty' )->parseAsBlock();
139 $lang = $this->getLanguage();
140 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
141 # put a div around the headings which are in the user language
142 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
144 wfProfileOut( __METHOD__
);
148 function clearCategoryState() {
149 $this->articles
= array();
150 $this->articles_start_char
= array();
151 $this->children
= array();
152 $this->children_start_char
= array();
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 ( MWException
$e ) {
159 // User specified something invalid, fallback to default.
160 $this->gallery
= ImageGalleryBase
::factory( false, $this->getContext() );
163 $this->gallery
->setHideBadImages();
165 $this->imgsNoGallery
= array();
166 $this->imgsNoGallery_start_char
= array();
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 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
181 if ( $title->isRedirect() ) {
182 // This didn't used to add redirect-in-category, but might
183 // as well be consistent with the rest of the sections
184 // on a category page.
185 $link = '<span class="redirect-in-category">' . $link . '</span>';
187 $this->children
[] = $link;
189 $this->children_start_char
[] =
190 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
194 * Get the character to be used for sorting subcategories.
195 * If there's a link from Category:A to Category:B, the sortkey of the resulting
196 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
197 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
198 * else use sortkey...
200 * @param Title $title
201 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
204 function getSubcategorySortChar( $title, $sortkey ) {
207 if ( $title->getPrefixedText() == $sortkey ) {
208 $word = $title->getDBkey();
213 $firstChar = $this->collation
->getFirstLetter( $word );
215 return $wgContLang->convert( $firstChar );
219 * Add a page in the image namespace
220 * @param Title $title
221 * @param string $sortkey
222 * @param int $pageLength
223 * @param bool $isRedirect
225 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
227 if ( $this->showGallery
) {
228 $flip = $this->flip
['file'];
230 $this->gallery
->insert( $title );
232 $this->gallery
->add( $title );
235 $link = Linker
::link( $title );
237 // This seems kind of pointless given 'mw-redirect' class,
238 // but keeping for back-compatibility with user css.
239 $link = '<span class="redirect-in-category">' . $link . '</span>';
241 $this->imgsNoGallery
[] = $link;
243 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
244 $this->collation
->getFirstLetter( $sortkey ) );
249 * Add a miscellaneous page
250 * @param Title $title
251 * @param string $sortkey
252 * @param int $pageLength
253 * @param bool $isRedirect
255 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
258 $link = Linker
::link( $title );
260 // This seems kind of pointless given 'mw-redirect' class,
261 // but keeping for back-compatibility with user css.
262 $link = '<span class="redirect-in-category">' . $link . '</span>';
264 $this->articles
[] = $link;
266 $this->articles_start_char
[] = $wgContLang->convert(
267 $this->collation
->getFirstLetter( $sortkey ) );
270 function finaliseCategoryState() {
271 if ( $this->flip
['subcat'] ) {
272 $this->children
= array_reverse( $this->children
);
273 $this->children_start_char
= array_reverse( $this->children_start_char
);
275 if ( $this->flip
['page'] ) {
276 $this->articles
= array_reverse( $this->articles
);
277 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
279 if ( !$this->showGallery
&& $this->flip
['file'] ) {
280 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
281 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
285 function doCategoryQuery() {
286 $dbr = wfGetDB( DB_SLAVE
, 'category' );
288 $this->nextPage
= array(
293 $this->prevPage
= array(
299 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
301 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
302 # Get the sortkeys for start/end, if applicable. Note that if
303 # the collation in the database differs from the one
304 # set in $wgCategoryCollation, pagination might go totally haywire.
305 $extraConds = array( 'cl_type' => $type );
306 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
307 $extraConds[] = 'cl_sortkey >= '
308 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
309 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
310 $extraConds[] = 'cl_sortkey < '
311 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
312 $this->flip
[$type] = true;
316 array( 'page', 'categorylinks', 'category' ),
317 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
318 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
319 'cat_subcats', 'cat_pages', 'cat_files',
320 'cl_sortkey_prefix', 'cl_collation' ),
321 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
324 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
325 'LIMIT' => $this->limit +
1,
326 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
329 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
330 'category' => array( 'LEFT JOIN', array(
331 'cat_title = page_title',
332 'page_namespace' => NS_CATEGORY
338 foreach ( $res as $row ) {
339 $title = Title
::newFromRow( $row );
340 if ( $row->cl_collation
=== '' ) {
341 // Hack to make sure that while updating from 1.16 schema
342 // and db is inconsistent, that the sky doesn't fall.
343 // See r83544. Could perhaps be removed in a couple decades...
344 $humanSortkey = $row->cl_sortkey
;
346 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
349 if ( ++
$count > $this->limit
) {
350 # We've reached the one extra which shows that there
351 # are additional pages to be had. Stop here...
352 $this->nextPage
[$type] = $humanSortkey;
355 if ( $count == $this->limit
) {
356 $this->prevPage
[$type] = $humanSortkey;
359 if ( $title->getNamespace() == NS_CATEGORY
) {
360 $cat = Category
::newFromRow( $row, $title );
361 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
362 } elseif ( $title->getNamespace() == NS_FILE
) {
363 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
365 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
374 function getCategoryTop() {
375 $r = $this->getCategoryBottom();
378 : "<br style=\"clear:both;\"/>\n" . $r;
384 function getSubcategorySection() {
385 # Don't show subcategories section if there are none.
387 $rescnt = count( $this->children
);
388 $dbcnt = $this->cat
->getSubcatCount();
389 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
392 # Showing subcategories
393 $r .= "<div id=\"mw-subcategories\">\n";
394 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
396 $r .= $this->getSectionPagingLinks( 'subcat' );
397 $r .= $this->formatList( $this->children
, $this->children_start_char
);
398 $r .= $this->getSectionPagingLinks( 'subcat' );
407 function getPagesSection() {
408 $ti = wfEscapeWikiText( $this->title
->getText() );
409 # Don't show articles section if there are none.
412 # @todo FIXME: Here and in the other two sections: we don't need to bother
413 # with this rigmarole if the entire category contents fit on one page
414 # and have already been retrieved. We can just use $rescnt in that
415 # case and save a query and some logic.
416 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
417 - $this->cat
->getFileCount();
418 $rescnt = count( $this->articles
);
419 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
422 $r = "<div id=\"mw-pages\">\n";
423 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
425 $r .= $this->getSectionPagingLinks( 'page' );
426 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
427 $r .= $this->getSectionPagingLinks( 'page' );
436 function getImageSection() {
438 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
440 $dbcnt = $this->cat
->getFileCount();
441 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
443 $r .= "<div id=\"mw-category-media\">\n";
446 'category-media-header',
447 wfEscapeWikiText( $this->title
->getText() )
451 $r .= $this->getSectionPagingLinks( 'file' );
452 if ( $this->showGallery
) {
453 $r .= $this->gallery
->toHTML();
455 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
457 $r .= $this->getSectionPagingLinks( 'file' );
464 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
467 * @param string $type 'page', 'subcat', or 'file'
468 * @return string HTML output, possibly empty if there are no other pages
470 private function getSectionPagingLinks( $type ) {
471 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
472 // The new value for the until parameter should be pointing to the first
473 // result displayed on the page which is the second last result retrieved
474 // from the database.The next link should have a from parameter pointing
475 // to the until parameter of the current page.
476 if ( $this->nextPage
[$type] !== null ) {
477 return $this->pagingLinks( $this->prevPage
[$type], $this->until
[$type], $type );
479 // If the nextPage variable is null, it means that we have reached the first page
480 // and therefore the previous link should be disabled.
481 return $this->pagingLinks( null, $this->until
[$type], $type );
483 } elseif ( $this->nextPage
[$type] !== null
484 ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null )
486 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
495 function getCategoryBottom() {
500 * Format a list of articles chunked by letter, either as a
501 * bullet list or a columnar format, depending on the length.
503 * @param array $articles
504 * @param array $articles_start_char
509 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
511 if ( count( $articles ) > $cutoff ) {
512 $list = self
::columnList( $articles, $articles_start_char );
513 } elseif ( count( $articles ) > 0 ) {
514 // for short lists of articles in categories.
515 $list = self
::shortList( $articles, $articles_start_char );
518 $pageLang = $this->title
->getPageLanguage();
519 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
520 'class' => 'mw-content-' . $pageLang->getDir() );
521 $list = Html
::rawElement( 'div', $attribs, $list );
527 * Format a list of articles chunked by letter in a three-column
528 * list, ordered vertically.
530 * TODO: Take the headers into account when creating columns, so they're
531 * more visually equal.
533 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
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 );
543 # Split into three columns
544 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
546 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
549 foreach ( $columns as $column ) {
550 $ret .= '<td style="width: 33.3%;">';
551 $colContents = array();
553 # Kind of like array_flip() here, but we keep duplicates in an
554 # array instead of dropping them.
555 foreach ( $column as $article => $char ) {
556 if ( !isset( $colContents[$char] ) ) {
557 $colContents[$char] = array();
559 $colContents[$char][] = $article;
563 foreach ( $colContents as $char => $articles ) {
564 # Change space to non-breaking space to keep headers aligned
565 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
567 $ret .= '<h3>' . $h3char;
568 if ( $first && $char === $prevchar ) {
569 # We're continuing a previous chunk at the top of a new
570 # column, so add " cont." after the letter.
571 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
576 $ret .= implode( "</li>\n<li>", $articles );
577 $ret .= '</li></ul>';
586 $ret .= '</tr></table>';
591 * Format a list of articles chunked by letter in a bullet list.
592 * @param array $articles
593 * @param string[] $articles_start_char
597 static function shortList( $articles, $articles_start_char ) {
598 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
599 $r .= '<ul><li>' . $articles[0] . '</li>';
600 $articleCount = count( $articles );
601 for ( $index = 1; $index < $articleCount; $index++
) {
602 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
603 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
606 $r .= "<li>{$articles[$index]}</li>";
613 * Create paging links, as a helper method to getSectionPagingLinks().
615 * @param string $first The 'until' parameter for the generated URL
616 * @param string $last The 'from' parameter for the generated URL
617 * @param string $type A prefix for parameters, 'page' or 'subcat' or
619 * @return string HTML
621 private function pagingLinks( $first, $last, $type = '' ) {
622 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit
)->escaped();
624 if ( $first != '' ) {
625 $prevQuery = $this->query
;
626 $prevQuery["{$type}until"] = $first;
627 unset( $prevQuery["{$type}from"] );
628 $prevLink = Linker
::linkKnown(
629 $this->addFragmentToTitle( $this->title
, $type ),
636 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit
)->escaped();
639 $lastQuery = $this->query
;
640 $lastQuery["{$type}from"] = $last;
641 unset( $lastQuery["{$type}until"] );
642 $nextLink = Linker
::linkKnown(
643 $this->addFragmentToTitle( $this->title
, $type ),
650 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
654 * Takes a title, and adds the fragment identifier that
655 * corresponds to the correct segment of the category.
657 * @param Title $title The title (usually $this->title)
658 * @param string $section Which section
659 * @throws MWException
662 private function addFragmentToTitle( $title, $section ) {
663 switch ( $section ) {
665 $fragment = 'mw-pages';
668 $fragment = 'mw-subcategories';
671 $fragment = 'mw-category-media';
674 throw new MWException( __METHOD__
.
675 " Invalid section $section." );
678 return Title
::makeTitle( $title->getNamespace(),
679 $title->getDBkey(), $fragment );
683 * What to do if the category table conflicts with the number of results
684 * returned? This function says what. Each type is considered independently
685 * of the other types.
687 * @param int $rescnt The number of items returned by our database query.
688 * @param int $dbcnt The number of items according to the category table.
689 * @param string $type 'subcat', 'article', or 'file'
690 * @return string A message giving the number of items, to output to HTML.
692 private function getCountMessage( $rescnt, $dbcnt, $type ) {
693 // There are three cases:
694 // 1) The category table figure seems sane. It might be wrong, but
695 // we can't do anything about it if we don't recalculate it on ev-
696 // ery category view.
697 // 2) The category table figure isn't sane, like it's smaller than the
698 // number of actual results, *but* the number of results is less
699 // than $this->limit and there's no offset. In this case we still
700 // know the right figure.
701 // 3) We have no idea.
703 // Check if there's a "from" or "until" for anything
705 // This is a little ugly, but we seem to use different names
706 // for the paging types then for the messages.
707 if ( $type === 'article' ) {
708 $pagingType = 'page';
713 $fromOrUntil = false;
714 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
715 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
720 if ( $dbcnt == $rescnt ||
721 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
723 // Case 1: seems sane.
725 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
726 // Case 2: not sane, but salvageable. Use the number of results.
727 // Since there are fewer than 200, we can also take this opportunity
728 // to refresh the incorrect category table entry -- which should be
729 // quick due to the small number of entries.
731 $category = $this->cat
;
732 wfGetDB( DB_MASTER
)->onTransactionIdle( function () use ( $category ) {
733 $category->refreshCounts();
736 // Case 3: hopeless. Don't give a total count at all.
737 // Messages: category-subcat-count-limited, category-article-count-limited,
738 // category-file-count-limited
739 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
741 // Messages: category-subcat-count, category-article-count, category-file-count
742 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();