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 if ( !defined( 'MEDIAWIKI' ) )
26 class CategoryViewer
extends ContextSource
{
27 var $limit, $from, $until,
28 $articles, $articles_start_char,
29 $children, $children_start_char,
30 $showGallery, $imgsNoGalley,
31 $imgsNoGallery_start_char,
60 * Category object for this page
66 * The original query array, to be used in generating paging links.
74 * @since 1.19 $context is a second, required parameter
76 * @param $context IContextSource
78 * @param $until String
81 function __construct( $title, IContextSource
$context, $from = '', $until = '', $query = array() ) {
82 global $wgCategoryPagingLimit;
83 $this->title
= $title;
84 $this->setContext( $context );
86 $this->until
= $until;
87 $this->limit
= $wgCategoryPagingLimit;
88 $this->cat
= Category
::newFromTitle( $title );
89 $this->query
= $query;
90 $this->collation
= Collation
::singleton();
91 unset( $this->query
['title'] );
95 * Format the category data list.
97 * @return string HTML output
99 public function getHTML() {
100 global $wgCategoryMagicGallery;
101 wfProfileIn( __METHOD__
);
103 $this->showGallery
= $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery
;
105 $this->clearCategoryState();
106 $this->doCategoryQuery();
107 $this->finaliseCategoryState();
109 $r = $this->getSubcategorySection() .
110 $this->getPagesSection() .
111 $this->getImageSection();
114 // If there is no category content to display, only
115 // show the top part of the navigation links.
116 // @todo FIXME: Cannot be completely suppressed because it
117 // is unknown if 'until' or 'from' makes this
119 $r = $r . $this->getCategoryTop();
121 $r = $this->getCategoryTop() .
123 $this->getCategoryBottom();
126 // Give a proper message if category is empty
128 $r = wfMsgExt( 'category-empty', array( 'parse' ) );
131 $lang = $this->getLanguage();
132 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
133 # put a div around the headings which are in the user language
134 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
136 wfProfileOut( __METHOD__
);
140 function clearCategoryState() {
141 $this->articles
= array();
142 $this->articles_start_char
= array();
143 $this->children
= array();
144 $this->children_start_char
= array();
145 if ( $this->showGallery
) {
146 $this->gallery
= new ImageGallery();
147 $this->gallery
->setHideBadImages();
149 $this->imgsNoGallery
= array();
150 $this->imgsNoGallery_start_char
= array();
155 * Add a subcategory to the internal lists, using a Category object
156 * @param $cat Category
160 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
161 // Subcategory; strip the 'Category' namespace from the link text.
162 $title = $cat->getTitle();
164 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
165 if ( $title->isRedirect() ) {
166 // This didn't used to add redirect-in-category, but might
167 // as well be consistent with the rest of the sections
168 // on a category page.
169 $link = '<span class="redirect-in-category">' . $link . '</span>';
171 $this->children
[] = $link;
173 $this->children_start_char
[] =
174 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
178 * Add a subcategory to the internal lists, using a title object
179 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
181 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
182 wfDeprecated( __METHOD__
, '1.17' );
183 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
187 * Get the character to be used for sorting subcategories.
188 * If there's a link from Category:A to Category:B, the sortkey of the resulting
189 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
190 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
191 * else use sortkey...
193 * @param Title $title
194 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
197 function getSubcategorySortChar( $title, $sortkey ) {
200 if ( $title->getPrefixedText() == $sortkey ) {
201 $word = $title->getDBkey();
206 $firstChar = $this->collation
->getFirstLetter( $word );
208 return $wgContLang->convert( $firstChar );
212 * Add a page in the image namespace
213 * @param $title Title
216 * @param $isRedirect bool
218 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
220 if ( $this->showGallery
) {
221 $flip = $this->flip
['file'];
223 $this->gallery
->insert( $title );
225 $this->gallery
->add( $title );
228 $link = Linker
::link( $title );
230 // This seems kind of pointless given 'mw-redirect' class,
231 // but keeping for back-compatibility with user css.
232 $link = '<span class="redirect-in-category">' . $link . '</span>';
234 $this->imgsNoGallery
[] = $link;
236 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
237 $this->collation
->getFirstLetter( $sortkey ) );
242 * Add a miscellaneous page
246 * @param $isRedirect bool
248 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
251 $link = Linker
::link( $title );
253 // This seems kind of pointless given 'mw-redirect' class,
254 // but keeping for back-compatiability with user css.
255 $link = '<span class="redirect-in-category">' . $link . '</span>';
257 $this->articles
[] = $link;
259 $this->articles_start_char
[] = $wgContLang->convert(
260 $this->collation
->getFirstLetter( $sortkey ) );
263 function finaliseCategoryState() {
264 if ( $this->flip
['subcat'] ) {
265 $this->children
= array_reverse( $this->children
);
266 $this->children_start_char
= array_reverse( $this->children_start_char
);
268 if ( $this->flip
['page'] ) {
269 $this->articles
= array_reverse( $this->articles
);
270 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
272 if ( !$this->showGallery
&& $this->flip
['file'] ) {
273 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
274 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
278 function doCategoryQuery() {
279 $dbr = wfGetDB( DB_SLAVE
, 'category' );
281 $this->nextPage
= array(
286 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
288 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
289 # Get the sortkeys for start/end, if applicable. Note that if
290 # the collation in the database differs from the one
291 # set in $wgCategoryCollation, pagination might go totally haywire.
292 $extraConds = array( 'cl_type' => $type );
293 if ( $this->from
[$type] !== null ) {
294 $extraConds[] = 'cl_sortkey >= '
295 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
296 } elseif ( $this->until
[$type] !== null ) {
297 $extraConds[] = 'cl_sortkey < '
298 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
299 $this->flip
[$type] = true;
303 array( 'page', 'categorylinks', 'category' ),
304 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
305 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
306 'cat_subcats', 'cat_pages', 'cat_files',
307 'cl_sortkey_prefix', 'cl_collation' ),
308 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
311 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
312 'LIMIT' => $this->limit +
1,
313 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
316 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
317 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY
)
322 foreach ( $res as $row ) {
323 $title = Title
::newFromRow( $row );
324 if ( $row->cl_collation
=== '' ) {
325 // Hack to make sure that while updating from 1.16 schema
326 // and db is inconsistent, that the sky doesn't fall.
327 // See r83544. Could perhaps be removed in a couple decades...
328 $humanSortkey = $row->cl_sortkey
;
330 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
333 if ( ++
$count > $this->limit
) {
334 # We've reached the one extra which shows that there
335 # are additional pages to be had. Stop here...
336 $this->nextPage
[$type] = $humanSortkey;
340 if ( $title->getNamespace() == NS_CATEGORY
) {
341 $cat = Category
::newFromRow( $row, $title );
342 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
343 } elseif ( $title->getNamespace() == NS_FILE
) {
344 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
346 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
355 function getCategoryTop() {
356 $r = $this->getCategoryBottom();
359 : "<br style=\"clear:both;\"/>\n" . $r;
365 function getSubcategorySection() {
366 # Don't show subcategories section if there are none.
368 $rescnt = count( $this->children
);
369 $dbcnt = $this->cat
->getSubcatCount();
370 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
373 # Showing subcategories
374 $r .= "<div id=\"mw-subcategories\">\n";
375 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
377 $r .= $this->getSectionPagingLinks( 'subcat' );
378 $r .= $this->formatList( $this->children
, $this->children_start_char
);
379 $r .= $this->getSectionPagingLinks( 'subcat' );
388 function getPagesSection() {
389 $ti = htmlspecialchars( $this->title
->getText() );
390 # Don't show articles section if there are none.
393 # @todo FIXME: Here and in the other two sections: we don't need to bother
394 # with this rigamarole if the entire category contents fit on one page
395 # and have already been retrieved. We can just use $rescnt in that
396 # case and save a query and some logic.
397 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
398 - $this->cat
->getFileCount();
399 $rescnt = count( $this->articles
);
400 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
403 $r = "<div id=\"mw-pages\">\n";
404 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
406 $r .= $this->getSectionPagingLinks( 'page' );
407 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
408 $r .= $this->getSectionPagingLinks( 'page' );
417 function getImageSection() {
419 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
421 $dbcnt = $this->cat
->getFileCount();
422 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
424 $r .= "<div id=\"mw-category-media\">\n";
425 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title
->getText() ) ) . "</h2>\n";
427 $r .= $this->getSectionPagingLinks( 'file' );
428 if ( $this->showGallery
) {
429 $r .= $this->gallery
->toHTML();
431 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
433 $r .= $this->getSectionPagingLinks( 'file' );
440 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
443 * @param $type String: 'page', 'subcat', or 'file'
444 * @return String: HTML output, possibly empty if there are no other pages
446 private function getSectionPagingLinks( $type ) {
447 if ( $this->until
[$type] !== null ) {
448 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
449 } elseif ( $this->nextPage
[$type] !== null ||
$this->from
[$type] !== null ) {
450 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
459 function getCategoryBottom() {
464 * Format a list of articles chunked by letter, either as a
465 * bullet list or a columnar format, depending on the length.
467 * @param $articles Array
468 * @param $articles_start_char Array
473 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
475 if ( count ( $articles ) > $cutoff ) {
476 $list = self
::columnList( $articles, $articles_start_char );
477 } elseif ( count( $articles ) > 0 ) {
478 // for short lists of articles in categories.
479 $list = self
::shortList( $articles, $articles_start_char );
482 $pageLang = $this->title
->getPageLanguage();
483 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
484 'class' => 'mw-content-'.$pageLang->getDir() );
485 $list = Html
::rawElement( 'div', $attribs, $list );
491 * Format a list of articles chunked by letter in a three-column
492 * list, ordered vertically.
494 * TODO: Take the headers into account when creating columns, so they're
495 * more visually equal.
497 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
500 * @param $articles Array
501 * @param $articles_start_char Array
505 static function columnList( $articles, $articles_start_char ) {
506 $columns = array_combine( $articles, $articles_start_char );
507 # Split into three columns
508 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
510 $ret = '<table width="100%"><tr valign="top">';
513 foreach ( $columns as $column ) {
514 $ret .= '<td width="33.3%">';
515 $colContents = array();
517 # Kind of like array_flip() here, but we keep duplicates in an
518 # array instead of dropping them.
519 foreach ( $column as $article => $char ) {
520 if ( !isset( $colContents[$char] ) ) {
521 $colContents[$char] = array();
523 $colContents[$char][] = $article;
527 foreach ( $colContents as $char => $articles ) {
528 $ret .= '<h3>' . htmlspecialchars( $char );
529 if ( $first && $char === $prevchar ) {
530 # We're continuing a previous chunk at the top of a new
531 # column, so add " cont." after the letter.
532 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
537 $ret .= implode( "</li>\n<li>", $articles );
538 $ret .= '</li></ul>';
547 $ret .= '</tr></table>';
552 * Format a list of articles chunked by letter in a bullet list.
553 * @param $articles Array
554 * @param $articles_start_char Array
558 static function shortList( $articles, $articles_start_char ) {
559 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
560 $r .= '<ul><li>' . $articles[0] . '</li>';
561 for ( $index = 1; $index < count( $articles ); $index++
) {
562 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
563 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
566 $r .= "<li>{$articles[$index]}</li>";
573 * Create paging links, as a helper method to getSectionPagingLinks().
575 * @param $first String The 'until' parameter for the generated URL
576 * @param $last String The 'from' parameter for the genererated URL
577 * @param $type String A prefix for parameters, 'page' or 'subcat' or
579 * @return String HTML
581 private function pagingLinks( $first, $last, $type = '' ) {
582 $prevLink = wfMessage( 'prevn' )->numParams( $this->limit
)->escaped();
584 if ( $first != '' ) {
585 $prevQuery = $this->query
;
586 $prevQuery["{$type}until"] = $first;
587 unset( $prevQuery["{$type}from"] );
588 $prevLink = Linker
::linkKnown(
589 $this->addFragmentToTitle( $this->title
, $type ),
596 $nextLink = wfMessage( 'nextn' )->numParams( $this->limit
)->escaped();
599 $lastQuery = $this->query
;
600 $lastQuery["{$type}from"] = $last;
601 unset( $lastQuery["{$type}until"] );
602 $nextLink = Linker
::linkKnown(
603 $this->addFragmentToTitle( $this->title
, $type ),
610 return "($prevLink) ($nextLink)";
614 * Takes a title, and adds the fragment identifier that
615 * corresponds to the correct segment of the category.
617 * @param Title $title: The title (usually $this->title)
618 * @param String $section: Which section
621 private function addFragmentToTitle( $title, $section ) {
622 switch ( $section ) {
624 $fragment = 'mw-pages';
627 $fragment = 'mw-subcategories';
630 $fragment = 'mw-category-media';
633 throw new MWException( __METHOD__
.
634 " Invalid section $section." );
637 return Title
::makeTitle( $title->getNamespace(),
638 $title->getDBkey(), $fragment );
641 * What to do if the category table conflicts with the number of results
642 * returned? This function says what. Each type is considered independently
643 * of the other types.
645 * Note for grepping: uses the messages category-article-count,
646 * category-article-count-limited, category-subcat-count,
647 * category-subcat-count-limited, category-file-count,
648 * category-file-count-limited.
650 * @param $rescnt Int: The number of items returned by our database query.
651 * @param $dbcnt Int: The number of items according to the category table.
652 * @param $type String: 'subcat', 'article', or 'file'
653 * @return String: A message giving the number of items, to output to HTML.
655 private function getCountMessage( $rescnt, $dbcnt, $type ) {
656 # There are three cases:
657 # 1) The category table figure seems sane. It might be wrong, but
658 # we can't do anything about it if we don't recalculate it on ev-
660 # 2) The category table figure isn't sane, like it's smaller than the
661 # number of actual results, *but* the number of results is less
662 # than $this->limit and there's no offset. In this case we still
663 # know the right figure.
664 # 3) We have no idea.
666 # Check if there's a "from" or "until" for anything
668 // This is a little ugly, but we seem to use different names
669 // for the paging types then for the messages.
670 if ( $type === 'article' ) {
671 $pagingType = 'page';
676 $fromOrUntil = false;
677 if ( $this->from
[$pagingType] !== null ||
$this->until
[$pagingType] !== null ) {
681 if ( $dbcnt == $rescnt ||
( ( $rescnt == $this->limit ||
$fromOrUntil )
682 && $dbcnt > $rescnt ) ) {
683 # Case 1: seems sane.
685 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
686 # Case 2: not sane, but salvageable. Use the number of results.
687 # Since there are fewer than 200, we can also take this opportunity
688 # to refresh the incorrect category table entry -- which should be
689 # quick due to the small number of entries.
691 $this->cat
->refreshCounts();
693 # Case 3: hopeless. Don't give a total count at all.
694 return wfMessage( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
696 return wfMessage( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();