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,
89 $skin, $imgsNoGallery;
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' ) );
177 global $wgBetterDirectionality, $wgTitle;
178 if( $wgBetterDirectionality ) {
179 $pageLang = $wgTitle->getPageLanguage();
180 $langAttribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir() );
181 # close the previous div, show the headings in user language,
182 # then open a new div with the page content language again
183 $r = '</div>' . $r . Html
::openElement( 'div', $langAttribs );
186 wfProfileOut( __METHOD__
);
187 return $wgContLang->convert( $r );
190 function clearCategoryState() {
191 $this->articles
= array();
192 $this->articles_start_char
= array();
193 $this->children
= array();
194 $this->children_start_char
= array();
195 if ( $this->showGallery
) {
196 $this->gallery
= new ImageGallery();
197 $this->gallery
->setHideBadImages();
199 $this->imgsNoGallery
= array();
200 $this->imgsNoGallery_start_char
= array();
208 if ( !$this->skin
) {
210 $this->skin
= $wgUser->getSkin();
216 * Add a subcategory to the internal lists, using a Category object
218 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
219 // Subcategory; strip the 'Category' namespace from the link text.
220 $title = $cat->getTitle();
222 $link = $this->getSkin()->link( $title, $title->getText() );
223 if ( $title->isRedirect() ) {
224 // This didn't used to add redirect-in-category, but might
225 // as well be consistent with the rest of the sections
226 // on a category page.
227 $link = '<span class="redirect-in-category">' . $link . '</span>';
229 $this->children
[] = $link;
231 $this->children_start_char
[] =
232 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
236 * Add a subcategory to the internal lists, using a title object
237 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
239 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
240 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
244 * Get the character to be used for sorting subcategories.
245 * If there's a link from Category:A to Category:B, the sortkey of the resulting
246 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
247 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
248 * else use sortkey...
250 * @param Title $title
251 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
253 function getSubcategorySortChar( $title, $sortkey ) {
256 if ( $title->getPrefixedText() == $sortkey ) {
257 $word = $title->getDBkey();
262 $firstChar = $this->collation
->getFirstLetter( $word );
264 return $wgContLang->convert( $firstChar );
268 * Add a page in the image namespace
270 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
272 if ( $this->showGallery
) {
273 $flip = $this->flip
['file'];
275 $this->gallery
->insert( $title );
277 $this->gallery
->add( $title );
280 $link = $this->getSkin()->link( $title );
282 // This seems kind of pointless given 'mw-redirect' class,
283 // but keeping for back-compatibility with user css.
284 $link = '<span class="redirect-in-category">' . $link . '</span>';
286 $this->imgsNoGallery
[] = $link;
288 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
289 $this->collation
->getFirstLetter( $sortkey ) );
294 * Add a miscellaneous page
296 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
299 $link = $this->getSkin()->link( $title );
301 // This seems kind of pointless given 'mw-redirect' class,
302 // but keeping for back-compatiability with user css.
303 $link = '<span class="redirect-in-category">' . $link . '</span>';
305 $this->articles
[] = $link;
307 $this->articles_start_char
[] = $wgContLang->convert(
308 $this->collation
->getFirstLetter( $sortkey ) );
311 function finaliseCategoryState() {
312 if ( $this->flip
['subcat'] ) {
313 $this->children
= array_reverse( $this->children
);
314 $this->children_start_char
= array_reverse( $this->children_start_char
);
316 if ( $this->flip
['page'] ) {
317 $this->articles
= array_reverse( $this->articles
);
318 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
320 if ( !$this->showGallery
&& $this->flip
['file'] ) {
321 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
322 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
326 function doCategoryQuery() {
327 $dbr = wfGetDB( DB_SLAVE
, 'category' );
329 $this->nextPage
= array(
334 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
336 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
337 # Get the sortkeys for start/end, if applicable. Note that if
338 # the collation in the database differs from the one
339 # set in $wgCategoryCollation, pagination might go totally haywire.
340 $extraConds = array( 'cl_type' => $type );
341 if ( $this->from
[$type] !== null ) {
342 $extraConds[] = 'cl_sortkey >= '
343 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
344 } elseif ( $this->until
[$type] !== null ) {
345 $extraConds[] = 'cl_sortkey < '
346 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
347 $this->flip
[$type] = true;
351 array( 'page', 'categorylinks', 'category' ),
352 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
353 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
354 'cat_subcats', 'cat_pages', 'cat_files',
355 'cl_sortkey_prefix', 'cl_collation' ),
356 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
359 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
360 'LIMIT' => $this->limit +
1,
361 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
364 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
365 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY
)
370 foreach ( $res as $row ) {
371 $title = Title
::newFromRow( $row );
372 if ( $row->cl_collation
=== '' ) {
373 // Hack to make sure that while updating from 1.16 schema
374 // and db is inconsistent, that the sky doesn't fall.
375 // See r83544. Could perhaps be removed in a couple decades...
376 $humanSortkey = $row->cl_sortkey
;
378 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
381 if ( ++
$count > $this->limit
) {
382 # We've reached the one extra which shows that there
383 # are additional pages to be had. Stop here...
384 $this->nextPage
[$type] = $humanSortkey;
388 if ( $title->getNamespace() == NS_CATEGORY
) {
389 $cat = Category
::newFromRow( $row, $title );
390 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
391 } elseif ( $title->getNamespace() == NS_FILE
) {
392 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
394 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
400 function getCategoryTop() {
401 $r = $this->getCategoryBottom();
404 : "<br style=\"clear:both;\"/>\n" . $r;
407 function getSubcategorySection() {
408 # Don't show subcategories section if there are none.
410 $rescnt = count( $this->children
);
411 $dbcnt = $this->cat
->getSubcatCount();
412 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
415 # Showing subcategories
416 $r .= "<div id=\"mw-subcategories\">\n";
417 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
419 $r .= $this->getSectionPagingLinks( 'subcat' );
420 $r .= $this->formatList( $this->children
, $this->children_start_char
);
421 $r .= $this->getSectionPagingLinks( 'subcat' );
427 function getPagesSection() {
428 $ti = htmlspecialchars( $this->title
->getText() );
429 # Don't show articles section if there are none.
432 # @todo FIXME: Here and in the other two sections: we don't need to bother
433 # with this rigamarole if the entire category contents fit on one page
434 # and have already been retrieved. We can just use $rescnt in that
435 # case and save a query and some logic.
436 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
437 - $this->cat
->getFileCount();
438 $rescnt = count( $this->articles
);
439 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
442 $r = "<div id=\"mw-pages\">\n";
443 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
445 $r .= $this->getSectionPagingLinks( 'page' );
446 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
447 $r .= $this->getSectionPagingLinks( 'page' );
453 function getImageSection() {
455 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
457 $dbcnt = $this->cat
->getFileCount();
458 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
460 $r .= "<div id=\"mw-category-media\">\n";
461 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title
->getText() ) ) . "</h2>\n";
463 $r .= $this->getSectionPagingLinks( 'file' );
464 if ( $this->showGallery
) {
465 $r .= $this->gallery
->toHTML();
467 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
469 $r .= $this->getSectionPagingLinks( 'file' );
476 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
479 * @param $type String: 'page', 'subcat', or 'file'
480 * @return String: HTML output, possibly empty if there are no other pages
482 private function getSectionPagingLinks( $type ) {
483 if ( $this->until
[$type] !== null ) {
484 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
485 } elseif ( $this->nextPage
[$type] !== null ||
$this->from
[$type] !== null ) {
486 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
492 function getCategoryBottom() {
497 * Format a list of articles chunked by letter, either as a
498 * bullet list or a columnar format, depending on the length.
500 * @param $articles Array
501 * @param $articles_start_char Array
506 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
508 if ( count ( $articles ) > $cutoff ) {
509 $list = self
::columnList( $articles, $articles_start_char );
510 } elseif ( count( $articles ) > 0 ) {
511 // for short lists of articles in categories.
512 $list = self
::shortList( $articles, $articles_start_char );
514 global $wgBetterDirectionality, $wgTitle;
515 if( $wgBetterDirectionality ) {
516 $pageLang = $wgTitle->getPageLanguage();
517 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
518 'class' => 'mw-content-'.$pageLang->getDir() );
519 $list = Html
::rawElement( 'div', $attribs, $list );
526 * Format a list of articles chunked by letter in a three-column
527 * list, ordered vertically.
529 * TODO: Take the headers into account when creating columns, so they're
530 * more visually equal.
532 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
535 * @param $articles Array
536 * @param $articles_start_char Array
540 static function columnList( $articles, $articles_start_char ) {
541 $columns = array_combine( $articles, $articles_start_char );
542 # Split into three columns
543 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
545 $ret = '<table width="100%"><tr valign="top"><td>';
548 foreach ( $columns as $column ) {
549 $colContents = array();
551 # Kind of like array_flip() here, but we keep duplicates in an
552 # array instead of dropping them.
553 foreach ( $column as $article => $char ) {
554 if ( !isset( $colContents[$char] ) ) {
555 $colContents[$char] = array();
557 $colContents[$char][] = $article;
561 foreach ( $colContents as $char => $articles ) {
562 $ret .= '<h3>' . htmlspecialchars( $char );
563 if ( $first && $char === $prevchar ) {
564 # We're continuing a previous chunk at the top of a new
565 # column, so add " cont." after the letter.
566 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
571 $ret .= implode( "</li>\n<li>", $articles );
572 $ret .= '</li></ul>';
578 $ret .= "</td>\n<td>";
581 $ret .= '</td></tr></table>';
586 * Format a list of articles chunked by letter in a bullet list.
587 * @param $articles Array
588 * @param $articles_start_char Array
592 static function shortList( $articles, $articles_start_char ) {
593 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
594 $r .= '<ul><li>' . $articles[0] . '</li>';
595 for ( $index = 1; $index < count( $articles ); $index++
) {
596 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
597 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
600 $r .= "<li>{$articles[$index]}</li>";
607 * Create paging links, as a helper method to getSectionPagingLinks().
609 * @param $first String The 'until' parameter for the generated URL
610 * @param $last String The 'from' parameter for the genererated URL
611 * @param $type String A prefix for parameters, 'page' or 'subcat' or
613 * @return String HTML
615 private function pagingLinks( $first, $last, $type = '' ) {
617 $sk = $this->getSkin();
618 $limitText = $wgLang->formatNum( $this->limit
);
620 $prevLink = wfMsgExt( 'prevn', array( 'escape', 'parsemag' ), $limitText );
622 if ( $first != '' ) {
623 $prevQuery = $this->query
;
624 $prevQuery["{$type}until"] = $first;
625 unset( $prevQuery["{$type}from"] );
626 $prevLink = $sk->linkKnown(
627 $this->addFragmentToTitle( $this->title
, $type ),
634 $nextLink = wfMsgExt( 'nextn', array( 'escape', 'parsemag' ), $limitText );
637 $lastQuery = $this->query
;
638 $lastQuery["{$type}from"] = $last;
639 unset( $lastQuery["{$type}until"] );
640 $nextLink = $sk->linkKnown(
641 $this->addFragmentToTitle( $this->title
, $type ),
648 return "($prevLink) ($nextLink)";
652 * Takes a title, and adds the fragment identifier that
653 * corresponds to the correct segment of the category.
655 * @param Title $title: The title (usually $this->title)
656 * @param String $section: Which section
658 private function addFragmentToTitle( $title, $section ) {
659 switch ( $section ) {
661 $fragment = 'mw-pages';
664 $fragment = 'mw-subcategories';
667 $fragment = 'mw-category-media';
670 throw new MWException( __METHOD__
.
671 " Invalid section $section." );
674 return Title
::makeTitle( $title->getNamespace(),
675 $title->getDBkey(), $fragment );
678 * What to do if the category table conflicts with the number of results
679 * returned? This function says what. Each type is considered independently
680 * of the other types.
682 * Note for grepping: uses the messages category-article-count,
683 * category-article-count-limited, category-subcat-count,
684 * category-subcat-count-limited, category-file-count,
685 * category-file-count-limited.
687 * @param $rescnt Int: The number of items returned by our database query.
688 * @param $dbcnt Int: The number of items according to the category table.
689 * @param $type String: 'subcat', 'article', or 'file'
690 * @return String: A message giving the number of items, to output to HTML.
692 private function getCountMessage( $rescnt, $dbcnt, $type ) {
694 # There are three cases:
695 # 1) The category table figure seems sane. It might be wrong, but
696 # we can't do anything about it if we don't recalculate it on ev-
698 # 2) The category table figure isn't sane, like it's smaller than the
699 # number of actual results, *but* the number of results is less
700 # than $this->limit and there's no offset. In this case we still
701 # know the right figure.
702 # 3) We have no idea.
704 # Check if there's a "from" or "until" for anything
706 // This is a little ugly, but we seem to use different names
707 // for the paging types then for the messages.
708 if ( $type === 'article' ) {
709 $pagingType = 'page';
714 $fromOrUntil = false;
715 if ( $this->from
[$pagingType] !== null ||
$this->until
[$pagingType] !== null ) {
719 if ( $dbcnt == $rescnt ||
( ( $rescnt == $this->limit ||
$fromOrUntil )
720 && $dbcnt > $rescnt ) ) {
721 # Case 1: seems sane.
723 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
724 # Case 2: not sane, but salvageable. Use the number of results.
725 # Since there are fewer than 200, we can also take this opportunity
726 # to refresh the incorrect category table entry -- which should be
727 # quick due to the small number of entries.
729 $this->cat
->refreshCounts();
731 # Case 3: hopeless. Don't give a total count at all.
732 return wfMsgExt( "category-$type-count-limited", 'parse',
733 $wgLang->formatNum( $rescnt ) );
736 "category-$type-count",
738 $wgLang->formatNum( $rescnt ),
739 $wgLang->formatNum( $totalcnt )