(bug 32412) TOC links on [[Special:EditWatchlist]] now points to the fieldset
[mediawiki.git] / includes / CategoryViewer.php
blobcfebdd1f1e42918acaac2491a0e0f0a4d74fea68
1 <?php
3 if ( !defined( 'MEDIAWIKI' ) )
4 die( 1 );
6 class CategoryViewer extends ContextSource {
7 var $limit, $from, $until,
8 $articles, $articles_start_char,
9 $children, $children_start_char,
10 $showGallery, $imgsNoGalley,
11 $imgsNoGallery_start_char,
12 $imgsNoGallery;
14 /**
15 * @var
17 var $nextPage;
19 /**
20 * @var Array
22 var $flip;
24 /**
25 * @var Title
27 var $title;
29 /**
30 * @var Collation
32 var $collation;
34 /**
35 * @var ImageGallery
37 var $gallery;
39 /**
40 * Category object for this page
41 * @var Category
43 private $cat;
45 /**
46 * The original query array, to be used in generating paging links.
47 * @var array
49 private $query;
51 /**
52 * Constructor
54 * @since 1.19 $context is a second, required parameter
55 * @param $title Title
56 * @param $context IContextSource
57 * @param $from String
58 * @param $until String
59 * @param $query Array
61 function __construct( $title, IContextSource $context, $from = '', $until = '', $query = array() ) {
62 global $wgCategoryPagingLimit;
63 $this->title = $title;
64 $this->setContext( $context );
65 $this->from = $from;
66 $this->until = $until;
67 $this->limit = $wgCategoryPagingLimit;
68 $this->cat = Category::newFromTitle( $title );
69 $this->query = $query;
70 $this->collation = Collation::singleton();
71 unset( $this->query['title'] );
74 /**
75 * Format the category data list.
77 * @return string HTML output
79 public function getHTML() {
80 global $wgCategoryMagicGallery;
81 wfProfileIn( __METHOD__ );
83 $this->showGallery = $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery;
85 $this->clearCategoryState();
86 $this->doCategoryQuery();
87 $this->finaliseCategoryState();
89 $r = $this->getSubcategorySection() .
90 $this->getPagesSection() .
91 $this->getImageSection();
93 if ( $r == '' ) {
94 // If there is no category content to display, only
95 // show the top part of the navigation links.
96 // @todo FIXME: Cannot be completely suppressed because it
97 // is unknown if 'until' or 'from' makes this
98 // give 0 results.
99 $r = $r . $this->getCategoryTop();
100 } else {
101 $r = $this->getCategoryTop() .
102 $r .
103 $this->getCategoryBottom();
106 // Give a proper message if category is empty
107 if ( $r == '' ) {
108 $r = wfMsgExt( 'category-empty', array( 'parse' ) );
111 $lang = $this->getLanguage();
112 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
113 # put a div around the headings which are in the user language
114 $r = Html::openElement( 'div', $langAttribs ) . $r . '</div>';
116 wfProfileOut( __METHOD__ );
117 return $r;
120 function clearCategoryState() {
121 $this->articles = array();
122 $this->articles_start_char = array();
123 $this->children = array();
124 $this->children_start_char = array();
125 if ( $this->showGallery ) {
126 $this->gallery = new ImageGallery();
127 $this->gallery->setHideBadImages();
128 } else {
129 $this->imgsNoGallery = array();
130 $this->imgsNoGallery_start_char = array();
135 * Add a subcategory to the internal lists, using a Category object
136 * @param $cat Category
137 * @param $sortkey
138 * @param $pageLength
140 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
141 // Subcategory; strip the 'Category' namespace from the link text.
142 $title = $cat->getTitle();
144 $link = Linker::link( $title, htmlspecialchars( $title->getText() ) );
145 if ( $title->isRedirect() ) {
146 // This didn't used to add redirect-in-category, but might
147 // as well be consistent with the rest of the sections
148 // on a category page.
149 $link = '<span class="redirect-in-category">' . $link . '</span>';
151 $this->children[] = $link;
153 $this->children_start_char[] =
154 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
158 * Add a subcategory to the internal lists, using a title object
159 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
161 function addSubcategory( Title $title, $sortkey, $pageLength ) {
162 $this->addSubcategoryObject( Category::newFromTitle( $title ), $sortkey, $pageLength );
166 * Get the character to be used for sorting subcategories.
167 * If there's a link from Category:A to Category:B, the sortkey of the resulting
168 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
169 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
170 * else use sortkey...
172 * @param Title $title
173 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
175 function getSubcategorySortChar( $title, $sortkey ) {
176 global $wgContLang;
178 if ( $title->getPrefixedText() == $sortkey ) {
179 $word = $title->getDBkey();
180 } else {
181 $word = $sortkey;
184 $firstChar = $this->collation->getFirstLetter( $word );
186 return $wgContLang->convert( $firstChar );
190 * Add a page in the image namespace
191 * @param $title Title
192 * @param $sortkey
193 * @param $pageLength
194 * @param $isRedirect bool
196 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
197 global $wgContLang;
198 if ( $this->showGallery ) {
199 $flip = $this->flip['file'];
200 if ( $flip ) {
201 $this->gallery->insert( $title );
202 } else {
203 $this->gallery->add( $title );
205 } else {
206 $link = Linker::link( $title );
207 if ( $isRedirect ) {
208 // This seems kind of pointless given 'mw-redirect' class,
209 // but keeping for back-compatibility with user css.
210 $link = '<span class="redirect-in-category">' . $link . '</span>';
212 $this->imgsNoGallery[] = $link;
214 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
215 $this->collation->getFirstLetter( $sortkey ) );
220 * Add a miscellaneous page
221 * @param $title
222 * @param $sortkey
223 * @param $pageLength
224 * @param $isRedirect bool
226 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
227 global $wgContLang;
229 $link = Linker::link( $title );
230 if ( $isRedirect ) {
231 // This seems kind of pointless given 'mw-redirect' class,
232 // but keeping for back-compatiability with user css.
233 $link = '<span class="redirect-in-category">' . $link . '</span>';
235 $this->articles[] = $link;
237 $this->articles_start_char[] = $wgContLang->convert(
238 $this->collation->getFirstLetter( $sortkey ) );
241 function finaliseCategoryState() {
242 if ( $this->flip['subcat'] ) {
243 $this->children = array_reverse( $this->children );
244 $this->children_start_char = array_reverse( $this->children_start_char );
246 if ( $this->flip['page'] ) {
247 $this->articles = array_reverse( $this->articles );
248 $this->articles_start_char = array_reverse( $this->articles_start_char );
250 if ( !$this->showGallery && $this->flip['file'] ) {
251 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
252 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
256 function doCategoryQuery() {
257 $dbr = wfGetDB( DB_SLAVE, 'category' );
259 $this->nextPage = array(
260 'page' => null,
261 'subcat' => null,
262 'file' => null,
264 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
266 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
267 # Get the sortkeys for start/end, if applicable. Note that if
268 # the collation in the database differs from the one
269 # set in $wgCategoryCollation, pagination might go totally haywire.
270 $extraConds = array( 'cl_type' => $type );
271 if ( $this->from[$type] !== null ) {
272 $extraConds[] = 'cl_sortkey >= '
273 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
274 } elseif ( $this->until[$type] !== null ) {
275 $extraConds[] = 'cl_sortkey < '
276 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
277 $this->flip[$type] = true;
280 $res = $dbr->select(
281 array( 'page', 'categorylinks', 'category' ),
282 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
283 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
284 'cat_subcats', 'cat_pages', 'cat_files',
285 'cl_sortkey_prefix', 'cl_collation' ),
286 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
287 __METHOD__,
288 array(
289 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
290 'LIMIT' => $this->limit + 1,
291 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
293 array(
294 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
295 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY )
299 $count = 0;
300 foreach ( $res as $row ) {
301 $title = Title::newFromRow( $row );
302 if ( $row->cl_collation === '' ) {
303 // Hack to make sure that while updating from 1.16 schema
304 // and db is inconsistent, that the sky doesn't fall.
305 // See r83544. Could perhaps be removed in a couple decades...
306 $humanSortkey = $row->cl_sortkey;
307 } else {
308 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
311 if ( ++$count > $this->limit ) {
312 # We've reached the one extra which shows that there
313 # are additional pages to be had. Stop here...
314 $this->nextPage[$type] = $humanSortkey;
315 break;
318 if ( $title->getNamespace() == NS_CATEGORY ) {
319 $cat = Category::newFromRow( $row, $title );
320 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
321 } elseif ( $title->getNamespace() == NS_FILE ) {
322 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
323 } else {
324 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
331 * @return string
333 function getCategoryTop() {
334 $r = $this->getCategoryBottom();
335 return $r === ''
336 ? $r
337 : "<br style=\"clear:both;\"/>\n" . $r;
341 * @return string
343 function getSubcategorySection() {
344 # Don't show subcategories section if there are none.
345 $r = '';
346 $rescnt = count( $this->children );
347 $dbcnt = $this->cat->getSubcatCount();
348 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
350 if ( $rescnt > 0 ) {
351 # Showing subcategories
352 $r .= "<div id=\"mw-subcategories\">\n";
353 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
354 $r .= $countmsg;
355 $r .= $this->getSectionPagingLinks( 'subcat' );
356 $r .= $this->formatList( $this->children, $this->children_start_char );
357 $r .= $this->getSectionPagingLinks( 'subcat' );
358 $r .= "\n</div>";
360 return $r;
364 * @return string
366 function getPagesSection() {
367 $ti = htmlspecialchars( $this->title->getText() );
368 # Don't show articles section if there are none.
369 $r = '';
371 # @todo FIXME: Here and in the other two sections: we don't need to bother
372 # with this rigamarole if the entire category contents fit on one page
373 # and have already been retrieved. We can just use $rescnt in that
374 # case and save a query and some logic.
375 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
376 - $this->cat->getFileCount();
377 $rescnt = count( $this->articles );
378 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
380 if ( $rescnt > 0 ) {
381 $r = "<div id=\"mw-pages\">\n";
382 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
383 $r .= $countmsg;
384 $r .= $this->getSectionPagingLinks( 'page' );
385 $r .= $this->formatList( $this->articles, $this->articles_start_char );
386 $r .= $this->getSectionPagingLinks( 'page' );
387 $r .= "\n</div>";
389 return $r;
393 * @return string
395 function getImageSection() {
396 $r = '';
397 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
398 if ( $rescnt > 0 ) {
399 $dbcnt = $this->cat->getFileCount();
400 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
402 $r .= "<div id=\"mw-category-media\">\n";
403 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title->getText() ) ) . "</h2>\n";
404 $r .= $countmsg;
405 $r .= $this->getSectionPagingLinks( 'file' );
406 if ( $this->showGallery ) {
407 $r .= $this->gallery->toHTML();
408 } else {
409 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
411 $r .= $this->getSectionPagingLinks( 'file' );
412 $r .= "\n</div>";
414 return $r;
418 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
419 * of the output.
421 * @param $type String: 'page', 'subcat', or 'file'
422 * @return String: HTML output, possibly empty if there are no other pages
424 private function getSectionPagingLinks( $type ) {
425 if ( $this->until[$type] !== null ) {
426 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
427 } elseif ( $this->nextPage[$type] !== null || $this->from[$type] !== null ) {
428 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
429 } else {
430 return '';
435 * @return string
437 function getCategoryBottom() {
438 return '';
442 * Format a list of articles chunked by letter, either as a
443 * bullet list or a columnar format, depending on the length.
445 * @param $articles Array
446 * @param $articles_start_char Array
447 * @param $cutoff Int
448 * @return String
449 * @private
451 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
452 $list = '';
453 if ( count ( $articles ) > $cutoff ) {
454 $list = self::columnList( $articles, $articles_start_char );
455 } elseif ( count( $articles ) > 0 ) {
456 // for short lists of articles in categories.
457 $list = self::shortList( $articles, $articles_start_char );
460 $pageLang = $this->title->getPageLanguage();
461 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
462 'class' => 'mw-content-'.$pageLang->getDir() );
463 $list = Html::rawElement( 'div', $attribs, $list );
465 return $list;
469 * Format a list of articles chunked by letter in a three-column
470 * list, ordered vertically.
472 * TODO: Take the headers into account when creating columns, so they're
473 * more visually equal.
475 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
476 * supports those.
478 * @param $articles Array
479 * @param $articles_start_char Array
480 * @return String
481 * @private
483 static function columnList( $articles, $articles_start_char ) {
484 $columns = array_combine( $articles, $articles_start_char );
485 # Split into three columns
486 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
488 $ret = '<table width="100%"><tr valign="top"><td>';
489 $prevchar = null;
491 foreach ( $columns as $column ) {
492 $colContents = array();
494 # Kind of like array_flip() here, but we keep duplicates in an
495 # array instead of dropping them.
496 foreach ( $column as $article => $char ) {
497 if ( !isset( $colContents[$char] ) ) {
498 $colContents[$char] = array();
500 $colContents[$char][] = $article;
503 $first = true;
504 foreach ( $colContents as $char => $articles ) {
505 $ret .= '<h3>' . htmlspecialchars( $char );
506 if ( $first && $char === $prevchar ) {
507 # We're continuing a previous chunk at the top of a new
508 # column, so add " cont." after the letter.
509 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
511 $ret .= "</h3>\n";
513 $ret .= '<ul><li>';
514 $ret .= implode( "</li>\n<li>", $articles );
515 $ret .= '</li></ul>';
517 $first = false;
518 $prevchar = $char;
521 $ret .= "</td>\n<td>";
524 $ret .= '</td></tr></table>';
525 return $ret;
529 * Format a list of articles chunked by letter in a bullet list.
530 * @param $articles Array
531 * @param $articles_start_char Array
532 * @return String
533 * @private
535 static function shortList( $articles, $articles_start_char ) {
536 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
537 $r .= '<ul><li>' . $articles[0] . '</li>';
538 for ( $index = 1; $index < count( $articles ); $index++ ) {
539 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
540 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
543 $r .= "<li>{$articles[$index]}</li>";
545 $r .= '</ul>';
546 return $r;
550 * Create paging links, as a helper method to getSectionPagingLinks().
552 * @param $first String The 'until' parameter for the generated URL
553 * @param $last String The 'from' parameter for the genererated URL
554 * @param $type String A prefix for parameters, 'page' or 'subcat' or
555 * 'file'
556 * @return String HTML
558 private function pagingLinks( $first, $last, $type = '' ) {
559 $prevLink = wfMessage( 'prevn' )->numParams( $this->limit )->escaped();
561 if ( $first != '' ) {
562 $prevQuery = $this->query;
563 $prevQuery["{$type}until"] = $first;
564 unset( $prevQuery["{$type}from"] );
565 $prevLink = Linker::linkKnown(
566 $this->addFragmentToTitle( $this->title, $type ),
567 $prevLink,
568 array(),
569 $prevQuery
573 $nextLink = wfMessage( 'nextn' )->numParams( $this->limit )->escaped();
575 if ( $last != '' ) {
576 $lastQuery = $this->query;
577 $lastQuery["{$type}from"] = $last;
578 unset( $lastQuery["{$type}until"] );
579 $nextLink = Linker::linkKnown(
580 $this->addFragmentToTitle( $this->title, $type ),
581 $nextLink,
582 array(),
583 $lastQuery
587 return "($prevLink) ($nextLink)";
591 * Takes a title, and adds the fragment identifier that
592 * corresponds to the correct segment of the category.
594 * @param Title $title: The title (usually $this->title)
595 * @param String $section: Which section
596 * @return Title
598 private function addFragmentToTitle( $title, $section ) {
599 switch ( $section ) {
600 case 'page':
601 $fragment = 'mw-pages';
602 break;
603 case 'subcat':
604 $fragment = 'mw-subcategories';
605 break;
606 case 'file':
607 $fragment = 'mw-category-media';
608 break;
609 default:
610 throw new MWException( __METHOD__ .
611 " Invalid section $section." );
614 return Title::makeTitle( $title->getNamespace(),
615 $title->getDBkey(), $fragment );
618 * What to do if the category table conflicts with the number of results
619 * returned? This function says what. Each type is considered independently
620 * of the other types.
622 * Note for grepping: uses the messages category-article-count,
623 * category-article-count-limited, category-subcat-count,
624 * category-subcat-count-limited, category-file-count,
625 * category-file-count-limited.
627 * @param $rescnt Int: The number of items returned by our database query.
628 * @param $dbcnt Int: The number of items according to the category table.
629 * @param $type String: 'subcat', 'article', or 'file'
630 * @return String: A message giving the number of items, to output to HTML.
632 private function getCountMessage( $rescnt, $dbcnt, $type ) {
633 # There are three cases:
634 # 1) The category table figure seems sane. It might be wrong, but
635 # we can't do anything about it if we don't recalculate it on ev-
636 # ery category view.
637 # 2) The category table figure isn't sane, like it's smaller than the
638 # number of actual results, *but* the number of results is less
639 # than $this->limit and there's no offset. In this case we still
640 # know the right figure.
641 # 3) We have no idea.
643 # Check if there's a "from" or "until" for anything
645 // This is a little ugly, but we seem to use different names
646 // for the paging types then for the messages.
647 if ( $type === 'article' ) {
648 $pagingType = 'page';
649 } else {
650 $pagingType = $type;
653 $fromOrUntil = false;
654 if ( $this->from[$pagingType] !== null || $this->until[$pagingType] !== null ) {
655 $fromOrUntil = true;
658 if ( $dbcnt == $rescnt || ( ( $rescnt == $this->limit || $fromOrUntil )
659 && $dbcnt > $rescnt ) ) {
660 # Case 1: seems sane.
661 $totalcnt = $dbcnt;
662 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
663 # Case 2: not sane, but salvageable. Use the number of results.
664 # Since there are fewer than 200, we can also take this opportunity
665 # to refresh the incorrect category table entry -- which should be
666 # quick due to the small number of entries.
667 $totalcnt = $rescnt;
668 $this->cat->refreshCounts();
669 } else {
670 # Case 3: hopeless. Don't give a total count at all.
671 return wfMessage( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
673 return wfMessage( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();