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 $from = $until = array();
73 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
74 $from[$type] = $wgRequest->getVal( "{$type}from", $oldFrom );
75 $until[$type] = $wgRequest->getVal( "{$type}until", $oldUntil );
78 $viewer = new $this->mCategoryViewerClass( $this->mTitle
, $from, $until, $wgRequest->getValues() );
79 $wgOut->addHTML( $viewer->getHTML() );
83 class CategoryViewer
{
84 var $limit, $from, $until,
85 $articles, $articles_start_char,
86 $children, $children_start_char,
87 $showGallery, $imgsNoGalley,
88 $imgsNoGallery_start_char,
117 * Category object for this page
123 * The original query array, to be used in generating paging links.
128 function __construct( $title, $from = '', $until = '', $query = array() ) {
129 global $wgCategoryPagingLimit;
130 $this->title
= $title;
132 $this->until
= $until;
133 $this->limit
= $wgCategoryPagingLimit;
134 $this->cat
= Category
::newFromTitle( $title );
135 $this->query
= $query;
136 $this->collation
= Collation
::singleton();
137 unset( $this->query
['title'] );
141 * Format the category data list.
143 * @return string HTML output
145 public function getHTML() {
146 global $wgOut, $wgCategoryMagicGallery, $wgContLang;
147 wfProfileIn( __METHOD__
);
149 $this->showGallery
= $wgCategoryMagicGallery && !$wgOut->mNoGallery
;
151 $this->clearCategoryState();
152 $this->doCategoryQuery();
153 $this->finaliseCategoryState();
155 $r = $this->getSubcategorySection() .
156 $this->getPagesSection() .
157 $this->getImageSection();
160 // If there is no category content to display, only
161 // show the top part of the navigation links.
162 // @todo FIXME: Cannot be completely suppressed because it
163 // is unknown if 'until' or 'from' makes this
165 $r = $r . $this->getCategoryTop();
167 $r = $this->getCategoryTop() .
169 $this->getCategoryBottom();
172 // Give a proper message if category is empty
174 $r = wfMsgExt( 'category-empty', array( 'parse' ) );
176 $pageLang = $this->title
->getPageLanguage();
177 $langAttribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir() );
178 # close the previous div, show the headings in user language,
179 # then open a new div with the page content language again
180 $r = '</div>' . $r . Html
::openElement( 'div', $langAttribs );
183 wfProfileOut( __METHOD__
);
187 function clearCategoryState() {
188 $this->articles
= array();
189 $this->articles_start_char
= array();
190 $this->children
= array();
191 $this->children_start_char
= array();
192 if ( $this->showGallery
) {
193 $this->gallery
= new ImageGallery();
194 $this->gallery
->setHideBadImages();
196 $this->imgsNoGallery
= array();
197 $this->imgsNoGallery_start_char
= array();
202 * Add a subcategory to the internal lists, using a Category object
204 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
205 // Subcategory; strip the 'Category' namespace from the link text.
206 $title = $cat->getTitle();
208 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
209 if ( $title->isRedirect() ) {
210 // This didn't used to add redirect-in-category, but might
211 // as well be consistent with the rest of the sections
212 // on a category page.
213 $link = '<span class="redirect-in-category">' . $link . '</span>';
215 $this->children
[] = $link;
217 $this->children_start_char
[] =
218 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
222 * Add a subcategory to the internal lists, using a title object
223 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
225 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
226 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
230 * Get the character to be used for sorting subcategories.
231 * If there's a link from Category:A to Category:B, the sortkey of the resulting
232 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
233 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
234 * else use sortkey...
236 * @param Title $title
237 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
239 function getSubcategorySortChar( $title, $sortkey ) {
242 if ( $title->getPrefixedText() == $sortkey ) {
243 $word = $title->getDBkey();
248 $firstChar = $this->collation
->getFirstLetter( $word );
250 return $wgContLang->convert( $firstChar );
254 * Add a page in the image namespace
256 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
258 if ( $this->showGallery
) {
259 $flip = $this->flip
['file'];
261 $this->gallery
->insert( $title );
263 $this->gallery
->add( $title );
266 $link = Linker
::link( $title );
268 // This seems kind of pointless given 'mw-redirect' class,
269 // but keeping for back-compatibility with user css.
270 $link = '<span class="redirect-in-category">' . $link . '</span>';
272 $this->imgsNoGallery
[] = $link;
274 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
275 $this->collation
->getFirstLetter( $sortkey ) );
280 * Add a miscellaneous page
282 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
285 $link = Linker
::link( $title );
287 // This seems kind of pointless given 'mw-redirect' class,
288 // but keeping for back-compatiability with user css.
289 $link = '<span class="redirect-in-category">' . $link . '</span>';
291 $this->articles
[] = $link;
293 $this->articles_start_char
[] = $wgContLang->convert(
294 $this->collation
->getFirstLetter( $sortkey ) );
297 function finaliseCategoryState() {
298 if ( $this->flip
['subcat'] ) {
299 $this->children
= array_reverse( $this->children
);
300 $this->children_start_char
= array_reverse( $this->children_start_char
);
302 if ( $this->flip
['page'] ) {
303 $this->articles
= array_reverse( $this->articles
);
304 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
306 if ( !$this->showGallery
&& $this->flip
['file'] ) {
307 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
308 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
312 function doCategoryQuery() {
313 $dbr = wfGetDB( DB_SLAVE
, 'category' );
315 $this->nextPage
= array(
320 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
322 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
323 # Get the sortkeys for start/end, if applicable. Note that if
324 # the collation in the database differs from the one
325 # set in $wgCategoryCollation, pagination might go totally haywire.
326 $extraConds = array( 'cl_type' => $type );
327 if ( $this->from
[$type] !== null ) {
328 $extraConds[] = 'cl_sortkey >= '
329 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
330 } elseif ( $this->until
[$type] !== null ) {
331 $extraConds[] = 'cl_sortkey < '
332 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
333 $this->flip
[$type] = true;
337 array( 'page', 'categorylinks', 'category' ),
338 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
339 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
340 'cat_subcats', 'cat_pages', 'cat_files',
341 'cl_sortkey_prefix', 'cl_collation' ),
342 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
345 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
346 'LIMIT' => $this->limit +
1,
347 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
350 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
351 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY
)
356 foreach ( $res as $row ) {
357 $title = Title
::newFromRow( $row );
358 if ( $row->cl_collation
=== '' ) {
359 // Hack to make sure that while updating from 1.16 schema
360 // and db is inconsistent, that the sky doesn't fall.
361 // See r83544. Could perhaps be removed in a couple decades...
362 $humanSortkey = $row->cl_sortkey
;
364 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
367 if ( ++
$count > $this->limit
) {
368 # We've reached the one extra which shows that there
369 # are additional pages to be had. Stop here...
370 $this->nextPage
[$type] = $humanSortkey;
374 if ( $title->getNamespace() == NS_CATEGORY
) {
375 $cat = Category
::newFromRow( $row, $title );
376 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
377 } elseif ( $title->getNamespace() == NS_FILE
) {
378 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
380 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
386 function getCategoryTop() {
387 $r = $this->getCategoryBottom();
390 : "<br style=\"clear:both;\"/>\n" . $r;
393 function getSubcategorySection() {
394 # Don't show subcategories section if there are none.
396 $rescnt = count( $this->children
);
397 $dbcnt = $this->cat
->getSubcatCount();
398 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
401 # Showing subcategories
402 $r .= "<div id=\"mw-subcategories\">\n";
403 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
405 $r .= $this->getSectionPagingLinks( 'subcat' );
406 $r .= $this->formatList( $this->children
, $this->children_start_char
);
407 $r .= $this->getSectionPagingLinks( 'subcat' );
413 function getPagesSection() {
414 $ti = htmlspecialchars( $this->title
->getText() );
415 # Don't show articles section if there are none.
418 # @todo FIXME: Here and in the other two sections: we don't need to bother
419 # with this rigamarole if the entire category contents fit on one page
420 # and have already been retrieved. We can just use $rescnt in that
421 # case and save a query and some logic.
422 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
423 - $this->cat
->getFileCount();
424 $rescnt = count( $this->articles
);
425 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
428 $r = "<div id=\"mw-pages\">\n";
429 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
431 $r .= $this->getSectionPagingLinks( 'page' );
432 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
433 $r .= $this->getSectionPagingLinks( 'page' );
439 function getImageSection() {
441 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
443 $dbcnt = $this->cat
->getFileCount();
444 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
446 $r .= "<div id=\"mw-category-media\">\n";
447 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title
->getText() ) ) . "</h2>\n";
449 $r .= $this->getSectionPagingLinks( 'file' );
450 if ( $this->showGallery
) {
451 $r .= $this->gallery
->toHTML();
453 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
455 $r .= $this->getSectionPagingLinks( 'file' );
462 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
465 * @param $type String: 'page', 'subcat', or 'file'
466 * @return String: HTML output, possibly empty if there are no other pages
468 private function getSectionPagingLinks( $type ) {
469 if ( $this->until
[$type] !== null ) {
470 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
471 } elseif ( $this->nextPage
[$type] !== null ||
$this->from
[$type] !== null ) {
472 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
478 function getCategoryBottom() {
483 * Format a list of articles chunked by letter, either as a
484 * bullet list or a columnar format, depending on the length.
486 * @param $articles Array
487 * @param $articles_start_char Array
492 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
494 if ( count ( $articles ) > $cutoff ) {
495 $list = self
::columnList( $articles, $articles_start_char );
496 } elseif ( count( $articles ) > 0 ) {
497 // for short lists of articles in categories.
498 $list = self
::shortList( $articles, $articles_start_char );
501 $pageLang = $this->title
->getPageLanguage();
502 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
503 'class' => 'mw-content-'.$pageLang->getDir() );
504 $list = Html
::rawElement( 'div', $attribs, $list );
510 * Format a list of articles chunked by letter in a three-column
511 * list, ordered vertically.
513 * TODO: Take the headers into account when creating columns, so they're
514 * more visually equal.
516 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
519 * @param $articles Array
520 * @param $articles_start_char Array
524 static function columnList( $articles, $articles_start_char ) {
525 $columns = array_combine( $articles, $articles_start_char );
526 # Split into three columns
527 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
529 $ret = '<table width="100%"><tr valign="top"><td>';
532 foreach ( $columns as $column ) {
533 $colContents = array();
535 # Kind of like array_flip() here, but we keep duplicates in an
536 # array instead of dropping them.
537 foreach ( $column as $article => $char ) {
538 if ( !isset( $colContents[$char] ) ) {
539 $colContents[$char] = array();
541 $colContents[$char][] = $article;
545 foreach ( $colContents as $char => $articles ) {
546 $ret .= '<h3>' . htmlspecialchars( $char );
547 if ( $first && $char === $prevchar ) {
548 # We're continuing a previous chunk at the top of a new
549 # column, so add " cont." after the letter.
550 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
555 $ret .= implode( "</li>\n<li>", $articles );
556 $ret .= '</li></ul>';
562 $ret .= "</td>\n<td>";
565 $ret .= '</td></tr></table>';
570 * Format a list of articles chunked by letter in a bullet list.
571 * @param $articles Array
572 * @param $articles_start_char Array
576 static function shortList( $articles, $articles_start_char ) {
577 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
578 $r .= '<ul><li>' . $articles[0] . '</li>';
579 for ( $index = 1; $index < count( $articles ); $index++
) {
580 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
581 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
584 $r .= "<li>{$articles[$index]}</li>";
591 * Create paging links, as a helper method to getSectionPagingLinks().
593 * @param $first String The 'until' parameter for the generated URL
594 * @param $last String The 'from' parameter for the genererated URL
595 * @param $type String A prefix for parameters, 'page' or 'subcat' or
597 * @return String HTML
599 private function pagingLinks( $first, $last, $type = '' ) {
602 $limitText = $wgLang->formatNum( $this->limit
);
604 $prevLink = wfMsgExt( 'prevn', array( 'escape', 'parsemag' ), $limitText );
606 if ( $first != '' ) {
607 $prevQuery = $this->query
;
608 $prevQuery["{$type}until"] = $first;
609 unset( $prevQuery["{$type}from"] );
610 $prevLink = Linker
::linkKnown(
611 $this->addFragmentToTitle( $this->title
, $type ),
618 $nextLink = wfMsgExt( 'nextn', array( 'escape', 'parsemag' ), $limitText );
621 $lastQuery = $this->query
;
622 $lastQuery["{$type}from"] = $last;
623 unset( $lastQuery["{$type}until"] );
624 $nextLink = Linker
::linkKnown(
625 $this->addFragmentToTitle( $this->title
, $type ),
632 return "($prevLink) ($nextLink)";
636 * Takes a title, and adds the fragment identifier that
637 * corresponds to the correct segment of the category.
639 * @param Title $title: The title (usually $this->title)
640 * @param String $section: Which section
642 private function addFragmentToTitle( $title, $section ) {
643 switch ( $section ) {
645 $fragment = 'mw-pages';
648 $fragment = 'mw-subcategories';
651 $fragment = 'mw-category-media';
654 throw new MWException( __METHOD__
.
655 " Invalid section $section." );
658 return Title
::makeTitle( $title->getNamespace(),
659 $title->getDBkey(), $fragment );
662 * What to do if the category table conflicts with the number of results
663 * returned? This function says what. Each type is considered independently
664 * of the other types.
666 * Note for grepping: uses the messages category-article-count,
667 * category-article-count-limited, category-subcat-count,
668 * category-subcat-count-limited, category-file-count,
669 * category-file-count-limited.
671 * @param $rescnt Int: The number of items returned by our database query.
672 * @param $dbcnt Int: The number of items according to the category table.
673 * @param $type String: 'subcat', 'article', or 'file'
674 * @return String: A message giving the number of items, to output to HTML.
676 private function getCountMessage( $rescnt, $dbcnt, $type ) {
678 # There are three cases:
679 # 1) The category table figure seems sane. It might be wrong, but
680 # we can't do anything about it if we don't recalculate it on ev-
682 # 2) The category table figure isn't sane, like it's smaller than the
683 # number of actual results, *but* the number of results is less
684 # than $this->limit and there's no offset. In this case we still
685 # know the right figure.
686 # 3) We have no idea.
688 # Check if there's a "from" or "until" for anything
690 // This is a little ugly, but we seem to use different names
691 // for the paging types then for the messages.
692 if ( $type === 'article' ) {
693 $pagingType = 'page';
698 $fromOrUntil = false;
699 if ( $this->from
[$pagingType] !== null ||
$this->until
[$pagingType] !== null ) {
703 if ( $dbcnt == $rescnt ||
( ( $rescnt == $this->limit ||
$fromOrUntil )
704 && $dbcnt > $rescnt ) ) {
705 # Case 1: seems sane.
707 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
708 # Case 2: not sane, but salvageable. Use the number of results.
709 # Since there are fewer than 200, we can also take this opportunity
710 # to refresh the incorrect category table entry -- which should be
711 # quick due to the small number of entries.
713 $this->cat
->refreshCounts();
715 # Case 3: hopeless. Don't give a total count at all.
716 return wfMsgExt( "category-$type-count-limited", 'parse',
717 $wgLang->formatNum( $rescnt ) );
720 "category-$type-count",
722 $wgLang->formatNum( $rescnt ),
723 $wgLang->formatNum( $totalcnt )