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
{
24 var $limit, $from, $until,
25 $articles, $articles_start_char,
26 $children, $children_start_char,
27 $showGallery, $imgsNoGalley,
28 $imgsNoGallery_start_char,
57 * Category object for this page
63 * The original query array, to be used in generating paging links.
71 * @since 1.19 $context is a second, required parameter
73 * @param $context IContextSource
74 * @param array $from An array with keys page, subcat,
75 * and file for offset of results of each section (since 1.17)
76 * @param array $until An array with 3 keys for until of each section (since 1.17)
79 function __construct( $title, IContextSource
$context, $from = array(), $until = array(), $query = array() ) {
80 global $wgCategoryPagingLimit;
81 $this->title
= $title;
82 $this->setContext( $context );
84 $this->until
= $until;
85 $this->limit
= $wgCategoryPagingLimit;
86 $this->cat
= Category
::newFromTitle( $title );
87 $this->query
= $query;
88 $this->collation
= Collation
::singleton();
89 unset( $this->query
['title'] );
93 * Format the category data list.
95 * @return string HTML output
97 public function getHTML() {
98 global $wgCategoryMagicGallery;
99 wfProfileIn( __METHOD__
);
101 $this->showGallery
= $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery
;
103 $this->clearCategoryState();
104 $this->doCategoryQuery();
105 $this->finaliseCategoryState();
107 $r = $this->getSubcategorySection() .
108 $this->getPagesSection() .
109 $this->getImageSection();
112 // If there is no category content to display, only
113 // show the top part of the navigation links.
114 // @todo FIXME: Cannot be completely suppressed because it
115 // is unknown if 'until' or 'from' makes this
117 $r = $r . $this->getCategoryTop();
119 $r = $this->getCategoryTop() .
121 $this->getCategoryBottom();
124 // Give a proper message if category is empty
126 $r = $this->msg( 'category-empty' )->parseAsBlock();
129 $lang = $this->getLanguage();
130 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
131 # put a div around the headings which are in the user language
132 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
134 wfProfileOut( __METHOD__
);
138 function clearCategoryState() {
139 $this->articles
= array();
140 $this->articles_start_char
= array();
141 $this->children
= array();
142 $this->children_start_char
= array();
143 if ( $this->showGallery
) {
144 $this->gallery
= ImageGalleryBase
::factory();
145 $this->gallery
->setHideBadImages();
146 $this->gallery
->setContext( $this->getContext() );
148 $this->imgsNoGallery
= array();
149 $this->imgsNoGallery_start_char
= array();
154 * Add a subcategory to the internal lists, using a Category object
155 * @param $cat Category
159 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
160 // Subcategory; strip the 'Category' namespace from the link text.
161 $title = $cat->getTitle();
163 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
164 if ( $title->isRedirect() ) {
165 // This didn't used to add redirect-in-category, but might
166 // as well be consistent with the rest of the sections
167 // on a category page.
168 $link = '<span class="redirect-in-category">' . $link . '</span>';
170 $this->children
[] = $link;
172 $this->children_start_char
[] =
173 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
177 * Add a subcategory to the internal lists, using a title object
178 * @deprecated since 1.17 kept for compatibility, use addSubcategoryObject instead
180 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
181 wfDeprecated( __METHOD__
, '1.17' );
182 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
186 * Get the character to be used for sorting subcategories.
187 * If there's a link from Category:A to Category:B, the sortkey of the resulting
188 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
189 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
190 * else use sortkey...
192 * @param Title $title
193 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
196 function getSubcategorySortChar( $title, $sortkey ) {
199 if ( $title->getPrefixedText() == $sortkey ) {
200 $word = $title->getDBkey();
205 $firstChar = $this->collation
->getFirstLetter( $word );
207 return $wgContLang->convert( $firstChar );
211 * Add a page in the image namespace
212 * @param $title Title
215 * @param $isRedirect bool
217 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
219 if ( $this->showGallery
) {
220 $flip = $this->flip
['file'];
222 $this->gallery
->insert( $title );
224 $this->gallery
->add( $title );
227 $link = Linker
::link( $title );
229 // This seems kind of pointless given 'mw-redirect' class,
230 // but keeping for back-compatibility with user css.
231 $link = '<span class="redirect-in-category">' . $link . '</span>';
233 $this->imgsNoGallery
[] = $link;
235 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
236 $this->collation
->getFirstLetter( $sortkey ) );
241 * Add a miscellaneous page
245 * @param $isRedirect bool
247 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
250 $link = Linker
::link( $title );
252 // This seems kind of pointless given 'mw-redirect' class,
253 // but keeping for back-compatibility with user css.
254 $link = '<span class="redirect-in-category">' . $link . '</span>';
256 $this->articles
[] = $link;
258 $this->articles_start_char
[] = $wgContLang->convert(
259 $this->collation
->getFirstLetter( $sortkey ) );
262 function finaliseCategoryState() {
263 if ( $this->flip
['subcat'] ) {
264 $this->children
= array_reverse( $this->children
);
265 $this->children_start_char
= array_reverse( $this->children_start_char
);
267 if ( $this->flip
['page'] ) {
268 $this->articles
= array_reverse( $this->articles
);
269 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
271 if ( !$this->showGallery
&& $this->flip
['file'] ) {
272 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
273 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
277 function doCategoryQuery() {
278 $dbr = wfGetDB( DB_SLAVE
, 'category' );
280 $this->nextPage
= array(
285 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
287 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
288 # Get the sortkeys for start/end, if applicable. Note that if
289 # the collation in the database differs from the one
290 # set in $wgCategoryCollation, pagination might go totally haywire.
291 $extraConds = array( 'cl_type' => $type );
292 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
293 $extraConds[] = 'cl_sortkey >= '
294 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
295 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
296 $extraConds[] = 'cl_sortkey < '
297 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
298 $this->flip
[$type] = true;
302 array( 'page', 'categorylinks', 'category' ),
303 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
304 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
305 'cat_subcats', 'cat_pages', 'cat_files',
306 'cl_sortkey_prefix', 'cl_collation' ),
307 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
310 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
311 'LIMIT' => $this->limit +
1,
312 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
315 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
316 'category' => array( 'LEFT JOIN', array(
317 'cat_title = page_title',
318 'page_namespace' => NS_CATEGORY
324 foreach ( $res as $row ) {
325 $title = Title
::newFromRow( $row );
326 if ( $row->cl_collation
=== '' ) {
327 // Hack to make sure that while updating from 1.16 schema
328 // and db is inconsistent, that the sky doesn't fall.
329 // See r83544. Could perhaps be removed in a couple decades...
330 $humanSortkey = $row->cl_sortkey
;
332 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
335 if ( ++
$count > $this->limit
) {
336 # We've reached the one extra which shows that there
337 # are additional pages to be had. Stop here...
338 $this->nextPage
[$type] = $humanSortkey;
342 if ( $title->getNamespace() == NS_CATEGORY
) {
343 $cat = Category
::newFromRow( $row, $title );
344 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
345 } elseif ( $title->getNamespace() == NS_FILE
) {
346 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
348 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
357 function getCategoryTop() {
358 $r = $this->getCategoryBottom();
361 : "<br style=\"clear:both;\"/>\n" . $r;
367 function getSubcategorySection() {
368 # Don't show subcategories section if there are none.
370 $rescnt = count( $this->children
);
371 $dbcnt = $this->cat
->getSubcatCount();
372 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
375 # Showing subcategories
376 $r .= "<div id=\"mw-subcategories\">\n";
377 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
379 $r .= $this->getSectionPagingLinks( 'subcat' );
380 $r .= $this->formatList( $this->children
, $this->children_start_char
);
381 $r .= $this->getSectionPagingLinks( 'subcat' );
390 function getPagesSection() {
391 $ti = wfEscapeWikiText( $this->title
->getText() );
392 # Don't show articles section if there are none.
395 # @todo FIXME: Here and in the other two sections: we don't need to bother
396 # with this rigmarole if the entire category contents fit on one page
397 # and have already been retrieved. We can just use $rescnt in that
398 # case and save a query and some logic.
399 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
400 - $this->cat
->getFileCount();
401 $rescnt = count( $this->articles
);
402 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
405 $r = "<div id=\"mw-pages\">\n";
406 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
408 $r .= $this->getSectionPagingLinks( 'page' );
409 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
410 $r .= $this->getSectionPagingLinks( 'page' );
419 function getImageSection() {
421 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
423 $dbcnt = $this->cat
->getFileCount();
424 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
426 $r .= "<div id=\"mw-category-media\">\n";
427 $r .= '<h2>' . $this->msg( 'category-media-header', wfEscapeWikiText( $this->title
->getText() ) )->text() . "</h2>\n";
429 $r .= $this->getSectionPagingLinks( 'file' );
430 if ( $this->showGallery
) {
431 $r .= $this->gallery
->toHTML();
433 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
435 $r .= $this->getSectionPagingLinks( 'file' );
442 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
445 * @param string $type 'page', 'subcat', or 'file'
446 * @return String: HTML output, possibly empty if there are no other pages
448 private function getSectionPagingLinks( $type ) {
449 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
450 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
451 } elseif ( $this->nextPage
[$type] !== null ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) ) {
452 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
461 function getCategoryBottom() {
466 * Format a list of articles chunked by letter, either as a
467 * bullet list or a columnar format, depending on the length.
469 * @param $articles Array
470 * @param $articles_start_char Array
475 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
477 if ( count( $articles ) > $cutoff ) {
478 $list = self
::columnList( $articles, $articles_start_char );
479 } elseif ( count( $articles ) > 0 ) {
480 // for short lists of articles in categories.
481 $list = self
::shortList( $articles, $articles_start_char );
484 $pageLang = $this->title
->getPageLanguage();
485 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
486 'class' => 'mw-content-' . $pageLang->getDir() );
487 $list = Html
::rawElement( 'div', $attribs, $list );
493 * Format a list of articles chunked by letter in a three-column
494 * list, ordered vertically.
496 * TODO: Take the headers into account when creating columns, so they're
497 * more visually equal.
499 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
502 * @param $articles Array
503 * @param $articles_start_char Array
507 static function columnList( $articles, $articles_start_char ) {
508 $columns = array_combine( $articles, $articles_start_char );
509 # Split into three columns
510 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
512 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
515 foreach ( $columns as $column ) {
516 $ret .= '<td style="width: 33.3%;">';
517 $colContents = array();
519 # Kind of like array_flip() here, but we keep duplicates in an
520 # array instead of dropping them.
521 foreach ( $column as $article => $char ) {
522 if ( !isset( $colContents[$char] ) ) {
523 $colContents[$char] = array();
525 $colContents[$char][] = $article;
529 foreach ( $colContents as $char => $articles ) {
530 # Change space to non-breaking space to keep headers aligned
531 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
533 $ret .= '<h3>' . $h3char;
534 if ( $first && $char === $prevchar ) {
535 # We're continuing a previous chunk at the top of a new
536 # column, so add " cont." after the letter.
537 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
542 $ret .= implode( "</li>\n<li>", $articles );
543 $ret .= '</li></ul>';
552 $ret .= '</tr></table>';
557 * Format a list of articles chunked by letter in a bullet list.
558 * @param $articles Array
559 * @param $articles_start_char Array
563 static function shortList( $articles, $articles_start_char ) {
564 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
565 $r .= '<ul><li>' . $articles[0] . '</li>';
566 for ( $index = 1; $index < count( $articles ); $index++
) {
567 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
568 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
571 $r .= "<li>{$articles[$index]}</li>";
578 * Create paging links, as a helper method to getSectionPagingLinks().
580 * @param string $first The 'until' parameter for the generated URL
581 * @param string $last The 'from' parameter for the generated URL
582 * @param string $type A prefix for parameters, 'page' or 'subcat' or
584 * @return String HTML
586 private function pagingLinks( $first, $last, $type = '' ) {
587 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit
)->escaped();
589 if ( $first != '' ) {
590 $prevQuery = $this->query
;
591 $prevQuery["{$type}until"] = $first;
592 unset( $prevQuery["{$type}from"] );
593 $prevLink = Linker
::linkKnown(
594 $this->addFragmentToTitle( $this->title
, $type ),
601 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit
)->escaped();
604 $lastQuery = $this->query
;
605 $lastQuery["{$type}from"] = $last;
606 unset( $lastQuery["{$type}until"] );
607 $nextLink = Linker
::linkKnown(
608 $this->addFragmentToTitle( $this->title
, $type ),
615 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
619 * Takes a title, and adds the fragment identifier that
620 * corresponds to the correct segment of the category.
622 * @param Title $title: The title (usually $this->title)
623 * @param string $section: Which section
624 * @throws MWException
627 private function addFragmentToTitle( $title, $section ) {
628 switch ( $section ) {
630 $fragment = 'mw-pages';
633 $fragment = 'mw-subcategories';
636 $fragment = 'mw-category-media';
639 throw new MWException( __METHOD__
.
640 " Invalid section $section." );
643 return Title
::makeTitle( $title->getNamespace(),
644 $title->getDBkey(), $fragment );
648 * What to do if the category table conflicts with the number of results
649 * returned? This function says what. Each type is considered independently
650 * of the other types.
652 * @param int $rescnt The number of items returned by our database query.
653 * @param int $dbcnt The number of items according to the category table.
654 * @param string $type 'subcat', 'article', or 'file'
655 * @return String: A message giving the number of items, to output to HTML.
657 private function getCountMessage( $rescnt, $dbcnt, $type ) {
658 # There are three cases:
659 # 1) The category table figure seems sane. It might be wrong, but
660 # we can't do anything about it if we don't recalculate it on ev-
662 # 2) The category table figure isn't sane, like it's smaller than the
663 # number of actual results, *but* the number of results is less
664 # than $this->limit and there's no offset. In this case we still
665 # know the right figure.
666 # 3) We have no idea.
668 # Check if there's a "from" or "until" for anything
670 // This is a little ugly, but we seem to use different names
671 // for the paging types then for the messages.
672 if ( $type === 'article' ) {
673 $pagingType = 'page';
678 $fromOrUntil = false;
679 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
680 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
685 if ( $dbcnt == $rescnt ||
686 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
688 # Case 1: seems sane.
690 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
691 # Case 2: not sane, but salvageable. Use the number of results.
692 # Since there are fewer than 200, we can also take this opportunity
693 # to refresh the incorrect category table entry -- which should be
694 # quick due to the small number of entries.
696 $this->cat
->refreshCounts();
698 # Case 3: hopeless. Don't give a total count at all.
699 # Give grep a chance to find the usages: category-subcat-count-limited,
700 # category-article-count-limited, category-file-count-limited
701 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
703 # Give grep a chance to find the usages:
704 # category-subcat-count, category-article-count, category-file-count
705 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();