3 * Class for viewing MediaWiki category description pages.
4 * Modelled after ImagePage.php.
9 if ( !defined( 'MEDIAWIKI' ) )
13 * Special handling for category description pages, showing pages,
14 * subcategories and file that belong to the category
16 class CategoryPage
extends Article
{
17 # Subclasses can change this to override the viewer class.
18 protected $mCategoryViewerClass = 'CategoryViewer';
20 protected function newPage( Title
$title ) {
21 // Overload mPage with a category-specific page
22 return new WikiCategoryPage( $title );
26 * Constructor from a page id
27 * @param $id Int article ID to load
29 public static function newFromID( $id ) {
30 $t = Title
::newFromID( $id );
31 # @todo FIXME: Doesn't inherit right
32 return $t == null ?
null : new self( $t );
33 # return $t == null ? null : new static( $t ); // PHP 5.3
37 global $wgRequest, $wgUser;
39 $diff = $wgRequest->getVal( 'diff' );
40 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
42 if ( isset( $diff ) && $diffOnly ) {
43 return parent
::view();
46 if ( !wfRunHooks( 'CategoryPageView', array( &$this ) ) ) {
50 if ( NS_CATEGORY
== $this->mTitle
->getNamespace() ) {
51 $this->openShowCategory();
56 if ( NS_CATEGORY
== $this->mTitle
->getNamespace() ) {
57 $this->closeShowCategory();
61 function openShowCategory() {
65 function closeShowCategory() {
66 global $wgOut, $wgRequest;
68 // Use these as defaults for back compat --catrope
69 $oldFrom = $wgRequest->getVal( 'from' );
70 $oldUntil = $wgRequest->getVal( 'until' );
72 $reqArray = $wgRequest->getValues();
74 $from = $until = array();
75 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
76 $from[$type] = $wgRequest->getVal( "{$type}from", $oldFrom );
77 $until[$type] = $wgRequest->getVal( "{$type}until", $oldUntil );
79 // Do not want old-style from/until propagating in nav links.
80 if ( !isset( $reqArray["{$type}from"] ) && isset( $reqArray["from"] ) ) {
81 $reqArray["{$type}from"] = $reqArray["from"];
83 if ( !isset( $reqArray["{$type}to"] ) && isset( $reqArray["to"] ) ) {
84 $reqArray["{$type}to"] = $reqArray["to"];
88 unset( $reqArray["from"] );
89 unset( $reqArray["to"] );
91 $viewer = new $this->mCategoryViewerClass( $this->mTitle
, $from, $until, $reqArray );
92 $wgOut->addHTML( $viewer->getHTML() );
96 class CategoryViewer
{
97 var $limit, $from, $until,
98 $articles, $articles_start_char,
99 $children, $children_start_char,
100 $showGallery, $imgsNoGalley,
101 $imgsNoGallery_start_char,
130 * Category object for this page
136 * The original query array, to be used in generating paging links.
141 function __construct( $title, $from = '', $until = '', $query = array() ) {
142 global $wgCategoryPagingLimit;
143 $this->title
= $title;
145 $this->until
= $until;
146 $this->limit
= $wgCategoryPagingLimit;
147 $this->cat
= Category
::newFromTitle( $title );
148 $this->query
= $query;
149 $this->collation
= Collation
::singleton();
150 unset( $this->query
['title'] );
154 * Format the category data list.
156 * @return string HTML output
158 public function getHTML() {
159 global $wgOut, $wgCategoryMagicGallery, $wgLang;
160 wfProfileIn( __METHOD__
);
162 $this->showGallery
= $wgCategoryMagicGallery && !$wgOut->mNoGallery
;
164 $this->clearCategoryState();
165 $this->doCategoryQuery();
166 $this->finaliseCategoryState();
168 $r = $this->getSubcategorySection() .
169 $this->getPagesSection() .
170 $this->getImageSection();
173 // If there is no category content to display, only
174 // show the top part of the navigation links.
175 // @todo FIXME: Cannot be completely suppressed because it
176 // is unknown if 'until' or 'from' makes this
178 $r = $r . $this->getCategoryTop();
180 $r = $this->getCategoryTop() .
182 $this->getCategoryBottom();
185 // Give a proper message if category is empty
187 $r = wfMsgExt( 'category-empty', array( 'parse' ) );
190 $langAttribs = array( 'lang' => $wgLang->getCode(), 'dir' => $wgLang->getDir() );
191 # put a div around the headings which are in the user language
192 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
194 wfProfileOut( __METHOD__
);
198 function clearCategoryState() {
199 $this->articles
= array();
200 $this->articles_start_char
= array();
201 $this->children
= array();
202 $this->children_start_char
= array();
203 if ( $this->showGallery
) {
204 $this->gallery
= new ImageGallery();
205 $this->gallery
->setHideBadImages();
207 $this->imgsNoGallery
= array();
208 $this->imgsNoGallery_start_char
= array();
213 * Add a subcategory to the internal lists, using a Category object
215 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
216 // Subcategory; strip the 'Category' namespace from the link text.
217 $title = $cat->getTitle();
219 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
220 if ( $title->isRedirect() ) {
221 // This didn't used to add redirect-in-category, but might
222 // as well be consistent with the rest of the sections
223 // on a category page.
224 $link = '<span class="redirect-in-category">' . $link . '</span>';
226 $this->children
[] = $link;
228 $this->children_start_char
[] =
229 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
233 * Add a subcategory to the internal lists, using a title object
234 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
236 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
237 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
241 * Get the character to be used for sorting subcategories.
242 * If there's a link from Category:A to Category:B, the sortkey of the resulting
243 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
244 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
245 * else use sortkey...
247 * @param Title $title
248 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
250 function getSubcategorySortChar( $title, $sortkey ) {
253 if ( $title->getPrefixedText() == $sortkey ) {
254 $word = $title->getDBkey();
259 $firstChar = $this->collation
->getFirstLetter( $word );
261 return $wgContLang->convert( $firstChar );
265 * Add a page in the image namespace
267 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
269 if ( $this->showGallery
) {
270 $flip = $this->flip
['file'];
272 $this->gallery
->insert( $title );
274 $this->gallery
->add( $title );
277 $link = Linker
::link( $title );
279 // This seems kind of pointless given 'mw-redirect' class,
280 // but keeping for back-compatibility with user css.
281 $link = '<span class="redirect-in-category">' . $link . '</span>';
283 $this->imgsNoGallery
[] = $link;
285 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
286 $this->collation
->getFirstLetter( $sortkey ) );
291 * Add a miscellaneous page
293 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
296 $link = Linker
::link( $title );
298 // This seems kind of pointless given 'mw-redirect' class,
299 // but keeping for back-compatiability with user css.
300 $link = '<span class="redirect-in-category">' . $link . '</span>';
302 $this->articles
[] = $link;
304 $this->articles_start_char
[] = $wgContLang->convert(
305 $this->collation
->getFirstLetter( $sortkey ) );
308 function finaliseCategoryState() {
309 if ( $this->flip
['subcat'] ) {
310 $this->children
= array_reverse( $this->children
);
311 $this->children_start_char
= array_reverse( $this->children_start_char
);
313 if ( $this->flip
['page'] ) {
314 $this->articles
= array_reverse( $this->articles
);
315 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
317 if ( !$this->showGallery
&& $this->flip
['file'] ) {
318 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
319 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
323 function doCategoryQuery() {
324 $dbr = wfGetDB( DB_SLAVE
, 'category' );
326 $this->nextPage
= array(
331 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
333 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
334 # Get the sortkeys for start/end, if applicable. Note that if
335 # the collation in the database differs from the one
336 # set in $wgCategoryCollation, pagination might go totally haywire.
337 $extraConds = array( 'cl_type' => $type );
338 if ( $this->from
[$type] !== null ) {
339 $extraConds[] = 'cl_sortkey >= '
340 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
341 } elseif ( $this->until
[$type] !== null ) {
342 $extraConds[] = 'cl_sortkey < '
343 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
344 $this->flip
[$type] = true;
348 array( 'page', 'categorylinks', 'category' ),
349 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
350 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
351 'cat_subcats', 'cat_pages', 'cat_files',
352 'cl_sortkey_prefix', 'cl_collation' ),
353 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
356 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
357 'LIMIT' => $this->limit +
1,
358 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
361 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
362 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY
)
367 foreach ( $res as $row ) {
368 $title = Title
::newFromRow( $row );
369 if ( $row->cl_collation
=== '' ) {
370 // Hack to make sure that while updating from 1.16 schema
371 // and db is inconsistent, that the sky doesn't fall.
372 // See r83544. Could perhaps be removed in a couple decades...
373 $humanSortkey = $row->cl_sortkey
;
375 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
378 if ( ++
$count > $this->limit
) {
379 # We've reached the one extra which shows that there
380 # are additional pages to be had. Stop here...
381 $this->nextPage
[$type] = $humanSortkey;
385 if ( $title->getNamespace() == NS_CATEGORY
) {
386 $cat = Category
::newFromRow( $row, $title );
387 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
388 } elseif ( $title->getNamespace() == NS_FILE
) {
389 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
391 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
397 function getCategoryTop() {
398 $r = $this->getCategoryBottom();
401 : "<br style=\"clear:both;\"/>\n" . $r;
404 function getSubcategorySection() {
405 # Don't show subcategories section if there are none.
407 $rescnt = count( $this->children
);
408 $dbcnt = $this->cat
->getSubcatCount();
409 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
412 # Showing subcategories
413 $r .= "<div id=\"mw-subcategories\">\n";
414 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
416 $r .= $this->getSectionPagingLinks( 'subcat' );
417 $r .= $this->formatList( $this->children
, $this->children_start_char
);
418 $r .= $this->getSectionPagingLinks( 'subcat' );
424 function getPagesSection() {
425 $ti = htmlspecialchars( $this->title
->getText() );
426 # Don't show articles section if there are none.
429 # @todo FIXME: Here and in the other two sections: we don't need to bother
430 # with this rigamarole if the entire category contents fit on one page
431 # and have already been retrieved. We can just use $rescnt in that
432 # case and save a query and some logic.
433 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
434 - $this->cat
->getFileCount();
435 $rescnt = count( $this->articles
);
436 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
439 $r = "<div id=\"mw-pages\">\n";
440 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
442 $r .= $this->getSectionPagingLinks( 'page' );
443 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
444 $r .= $this->getSectionPagingLinks( 'page' );
450 function getImageSection() {
452 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
454 $dbcnt = $this->cat
->getFileCount();
455 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
457 $r .= "<div id=\"mw-category-media\">\n";
458 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title
->getText() ) ) . "</h2>\n";
460 $r .= $this->getSectionPagingLinks( 'file' );
461 if ( $this->showGallery
) {
462 $r .= $this->gallery
->toHTML();
464 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
466 $r .= $this->getSectionPagingLinks( 'file' );
473 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
476 * @param $type String: 'page', 'subcat', or 'file'
477 * @return String: HTML output, possibly empty if there are no other pages
479 private function getSectionPagingLinks( $type ) {
480 if ( $this->until
[$type] !== null ) {
481 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
482 } elseif ( $this->nextPage
[$type] !== null ||
$this->from
[$type] !== null ) {
483 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
489 function getCategoryBottom() {
494 * Format a list of articles chunked by letter, either as a
495 * bullet list or a columnar format, depending on the length.
497 * @param $articles Array
498 * @param $articles_start_char Array
503 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
505 if ( count ( $articles ) > $cutoff ) {
506 $list = self
::columnList( $articles, $articles_start_char );
507 } elseif ( count( $articles ) > 0 ) {
508 // for short lists of articles in categories.
509 $list = self
::shortList( $articles, $articles_start_char );
512 $pageLang = $this->title
->getPageLanguage();
513 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
514 'class' => 'mw-content-'.$pageLang->getDir() );
515 $list = Html
::rawElement( 'div', $attribs, $list );
521 * Format a list of articles chunked by letter in a three-column
522 * list, ordered vertically.
524 * TODO: Take the headers into account when creating columns, so they're
525 * more visually equal.
527 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
530 * @param $articles Array
531 * @param $articles_start_char Array
535 static function columnList( $articles, $articles_start_char ) {
536 $columns = array_combine( $articles, $articles_start_char );
537 # Split into three columns
538 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
540 $ret = '<table width="100%"><tr valign="top"><td>';
543 foreach ( $columns as $column ) {
544 $colContents = array();
546 # Kind of like array_flip() here, but we keep duplicates in an
547 # array instead of dropping them.
548 foreach ( $column as $article => $char ) {
549 if ( !isset( $colContents[$char] ) ) {
550 $colContents[$char] = array();
552 $colContents[$char][] = $article;
556 foreach ( $colContents as $char => $articles ) {
557 $ret .= '<h3>' . htmlspecialchars( $char );
558 if ( $first && $char === $prevchar ) {
559 # We're continuing a previous chunk at the top of a new
560 # column, so add " cont." after the letter.
561 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
566 $ret .= implode( "</li>\n<li>", $articles );
567 $ret .= '</li></ul>';
573 $ret .= "</td>\n<td>";
576 $ret .= '</td></tr></table>';
581 * Format a list of articles chunked by letter in a bullet list.
582 * @param $articles Array
583 * @param $articles_start_char Array
587 static function shortList( $articles, $articles_start_char ) {
588 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
589 $r .= '<ul><li>' . $articles[0] . '</li>';
590 for ( $index = 1; $index < count( $articles ); $index++
) {
591 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
592 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
595 $r .= "<li>{$articles[$index]}</li>";
602 * Create paging links, as a helper method to getSectionPagingLinks().
604 * @param $first String The 'until' parameter for the generated URL
605 * @param $last String The 'from' parameter for the genererated URL
606 * @param $type String A prefix for parameters, 'page' or 'subcat' or
608 * @return String HTML
610 private function pagingLinks( $first, $last, $type = '' ) {
613 $limitText = $wgLang->formatNum( $this->limit
);
615 $prevLink = wfMsgExt( 'prevn', array( 'escape', 'parsemag' ), $limitText );
617 if ( $first != '' ) {
618 $prevQuery = $this->query
;
619 $prevQuery["{$type}until"] = $first;
620 unset( $prevQuery["{$type}from"] );
621 $prevLink = Linker
::linkKnown(
622 $this->addFragmentToTitle( $this->title
, $type ),
629 $nextLink = wfMsgExt( 'nextn', array( 'escape', 'parsemag' ), $limitText );
632 $lastQuery = $this->query
;
633 $lastQuery["{$type}from"] = $last;
634 unset( $lastQuery["{$type}until"] );
635 $nextLink = Linker
::linkKnown(
636 $this->addFragmentToTitle( $this->title
, $type ),
643 return "($prevLink) ($nextLink)";
647 * Takes a title, and adds the fragment identifier that
648 * corresponds to the correct segment of the category.
650 * @param Title $title: The title (usually $this->title)
651 * @param String $section: Which section
653 private function addFragmentToTitle( $title, $section ) {
654 switch ( $section ) {
656 $fragment = 'mw-pages';
659 $fragment = 'mw-subcategories';
662 $fragment = 'mw-category-media';
665 throw new MWException( __METHOD__
.
666 " Invalid section $section." );
669 return Title
::makeTitle( $title->getNamespace(),
670 $title->getDBkey(), $fragment );
673 * What to do if the category table conflicts with the number of results
674 * returned? This function says what. Each type is considered independently
675 * of the other types.
677 * Note for grepping: uses the messages category-article-count,
678 * category-article-count-limited, category-subcat-count,
679 * category-subcat-count-limited, category-file-count,
680 * category-file-count-limited.
682 * @param $rescnt Int: The number of items returned by our database query.
683 * @param $dbcnt Int: The number of items according to the category table.
684 * @param $type String: 'subcat', 'article', or 'file'
685 * @return String: A message giving the number of items, to output to HTML.
687 private function getCountMessage( $rescnt, $dbcnt, $type ) {
689 # There are three cases:
690 # 1) The category table figure seems sane. It might be wrong, but
691 # we can't do anything about it if we don't recalculate it on ev-
693 # 2) The category table figure isn't sane, like it's smaller than the
694 # number of actual results, *but* the number of results is less
695 # than $this->limit and there's no offset. In this case we still
696 # know the right figure.
697 # 3) We have no idea.
699 # Check if there's a "from" or "until" for anything
701 // This is a little ugly, but we seem to use different names
702 // for the paging types then for the messages.
703 if ( $type === 'article' ) {
704 $pagingType = 'page';
709 $fromOrUntil = false;
710 if ( $this->from
[$pagingType] !== null ||
$this->until
[$pagingType] !== null ) {
714 if ( $dbcnt == $rescnt ||
( ( $rescnt == $this->limit ||
$fromOrUntil )
715 && $dbcnt > $rescnt ) ) {
716 # Case 1: seems sane.
718 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
719 # Case 2: not sane, but salvageable. Use the number of results.
720 # Since there are fewer than 200, we can also take this opportunity
721 # to refresh the incorrect category table entry -- which should be
722 # quick due to the small number of entries.
724 $this->cat
->refreshCounts();
726 # Case 3: hopeless. Don't give a total count at all.
727 return wfMsgExt( "category-$type-count-limited", 'parse',
728 $wgLang->formatNum( $rescnt ) );
731 "category-$type-count",
733 $wgLang->formatNum( $rescnt ),
734 $wgLang->formatNum( $totalcnt )