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';
27 * @return WikiCategoryPage
29 protected function newPage( Title
$title ) {
30 // Overload mPage with a category-specific page
31 return new WikiCategoryPage( $title );
35 * Constructor from a page id
36 * @param $id Int article ID to load
38 public static function newFromID( $id ) {
39 $t = Title
::newFromID( $id );
40 # @todo FIXME: Doesn't inherit right
41 return $t == null ?
null : new self( $t );
42 # return $t == null ? null : new static( $t ); // PHP 5.3
46 $request = $this->getContext()->getRequest();
47 $diff = $request->getVal( 'diff' );
48 $diffOnly = $request->getBool( 'diffonly',
49 $this->getContext()->getUser()->getOption( 'diffonly' ) );
51 if ( isset( $diff ) && $diffOnly ) {
52 return parent
::view();
55 if ( !wfRunHooks( 'CategoryPageView', array( &$this ) ) ) {
59 if ( NS_CATEGORY
== $this->mTitle
->getNamespace() ) {
60 $this->openShowCategory();
65 if ( NS_CATEGORY
== $this->mTitle
->getNamespace() ) {
66 $this->closeShowCategory();
70 function openShowCategory() {
74 function closeShowCategory() {
75 // Use these as defaults for back compat --catrope
76 $request = $this->getContext()->getRequest();
77 $oldFrom = $request->getVal( 'from' );
78 $oldUntil = $request->getVal( 'until' );
80 $reqArray = $request->getValues();
82 $from = $until = array();
83 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
84 $from[$type] = $request->getVal( "{$type}from", $oldFrom );
85 $until[$type] = $request->getVal( "{$type}until", $oldUntil );
87 // Do not want old-style from/until propagating in nav links.
88 if ( !isset( $reqArray["{$type}from"] ) && isset( $reqArray["from"] ) ) {
89 $reqArray["{$type}from"] = $reqArray["from"];
91 if ( !isset( $reqArray["{$type}to"] ) && isset( $reqArray["to"] ) ) {
92 $reqArray["{$type}to"] = $reqArray["to"];
96 unset( $reqArray["from"] );
97 unset( $reqArray["to"] );
99 $viewer = new $this->mCategoryViewerClass( $this->mTitle
, $this->getContext(), $from, $until, $reqArray );
100 $this->getContext()->getOutput()->addHTML( $viewer->getHTML() );
104 class CategoryViewer
extends ContextSource
{
105 var $limit, $from, $until,
106 $articles, $articles_start_char,
107 $children, $children_start_char,
108 $showGallery, $imgsNoGalley,
109 $imgsNoGallery_start_char,
138 * Category object for this page
144 * The original query array, to be used in generating paging links.
152 * @since 1.19 $context is a second, required parameter
153 * @param $title Title
154 * @param $context IContextSource
155 * @param $from String
156 * @param $until String
157 * @param $query Array
159 function __construct( $title, IContextSource
$context, $from = '', $until = '', $query = array() ) {
160 global $wgCategoryPagingLimit;
161 $this->title
= $title;
162 $this->setContext( $context );
164 $this->until
= $until;
165 $this->limit
= $wgCategoryPagingLimit;
166 $this->cat
= Category
::newFromTitle( $title );
167 $this->query
= $query;
168 $this->collation
= Collation
::singleton();
169 unset( $this->query
['title'] );
173 * Format the category data list.
175 * @return string HTML output
177 public function getHTML() {
178 global $wgCategoryMagicGallery;
179 wfProfileIn( __METHOD__
);
181 $this->showGallery
= $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery
;
183 $this->clearCategoryState();
184 $this->doCategoryQuery();
185 $this->finaliseCategoryState();
187 $r = $this->getSubcategorySection() .
188 $this->getPagesSection() .
189 $this->getImageSection();
192 // If there is no category content to display, only
193 // show the top part of the navigation links.
194 // @todo FIXME: Cannot be completely suppressed because it
195 // is unknown if 'until' or 'from' makes this
197 $r = $r . $this->getCategoryTop();
199 $r = $this->getCategoryTop() .
201 $this->getCategoryBottom();
204 // Give a proper message if category is empty
206 $r = wfMsgExt( 'category-empty', array( 'parse' ) );
209 $lang = $this->getLang();
210 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
211 # put a div around the headings which are in the user language
212 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
214 wfProfileOut( __METHOD__
);
218 function clearCategoryState() {
219 $this->articles
= array();
220 $this->articles_start_char
= array();
221 $this->children
= array();
222 $this->children_start_char
= array();
223 if ( $this->showGallery
) {
224 $this->gallery
= new ImageGallery();
225 $this->gallery
->setHideBadImages();
227 $this->imgsNoGallery
= array();
228 $this->imgsNoGallery_start_char
= array();
233 * Add a subcategory to the internal lists, using a Category object
235 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
236 // Subcategory; strip the 'Category' namespace from the link text.
237 $title = $cat->getTitle();
239 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
240 if ( $title->isRedirect() ) {
241 // This didn't used to add redirect-in-category, but might
242 // as well be consistent with the rest of the sections
243 // on a category page.
244 $link = '<span class="redirect-in-category">' . $link . '</span>';
246 $this->children
[] = $link;
248 $this->children_start_char
[] =
249 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
253 * Add a subcategory to the internal lists, using a title object
254 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
256 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
257 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
261 * Get the character to be used for sorting subcategories.
262 * If there's a link from Category:A to Category:B, the sortkey of the resulting
263 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
264 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
265 * else use sortkey...
267 * @param Title $title
268 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
270 function getSubcategorySortChar( $title, $sortkey ) {
273 if ( $title->getPrefixedText() == $sortkey ) {
274 $word = $title->getDBkey();
279 $firstChar = $this->collation
->getFirstLetter( $word );
281 return $wgContLang->convert( $firstChar );
285 * Add a page in the image namespace
287 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
289 if ( $this->showGallery
) {
290 $flip = $this->flip
['file'];
292 $this->gallery
->insert( $title );
294 $this->gallery
->add( $title );
297 $link = Linker
::link( $title );
299 // This seems kind of pointless given 'mw-redirect' class,
300 // but keeping for back-compatibility with user css.
301 $link = '<span class="redirect-in-category">' . $link . '</span>';
303 $this->imgsNoGallery
[] = $link;
305 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
306 $this->collation
->getFirstLetter( $sortkey ) );
311 * Add a miscellaneous page
313 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
316 $link = Linker
::link( $title );
318 // This seems kind of pointless given 'mw-redirect' class,
319 // but keeping for back-compatiability with user css.
320 $link = '<span class="redirect-in-category">' . $link . '</span>';
322 $this->articles
[] = $link;
324 $this->articles_start_char
[] = $wgContLang->convert(
325 $this->collation
->getFirstLetter( $sortkey ) );
328 function finaliseCategoryState() {
329 if ( $this->flip
['subcat'] ) {
330 $this->children
= array_reverse( $this->children
);
331 $this->children_start_char
= array_reverse( $this->children_start_char
);
333 if ( $this->flip
['page'] ) {
334 $this->articles
= array_reverse( $this->articles
);
335 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
337 if ( !$this->showGallery
&& $this->flip
['file'] ) {
338 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
339 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
343 function doCategoryQuery() {
344 $dbr = wfGetDB( DB_SLAVE
, 'category' );
346 $this->nextPage
= array(
351 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
353 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
354 # Get the sortkeys for start/end, if applicable. Note that if
355 # the collation in the database differs from the one
356 # set in $wgCategoryCollation, pagination might go totally haywire.
357 $extraConds = array( 'cl_type' => $type );
358 if ( $this->from
[$type] !== null ) {
359 $extraConds[] = 'cl_sortkey >= '
360 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
361 } elseif ( $this->until
[$type] !== null ) {
362 $extraConds[] = 'cl_sortkey < '
363 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
364 $this->flip
[$type] = true;
368 array( 'page', 'categorylinks', 'category' ),
369 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
370 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
371 'cat_subcats', 'cat_pages', 'cat_files',
372 'cl_sortkey_prefix', 'cl_collation' ),
373 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
376 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
377 'LIMIT' => $this->limit +
1,
378 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
381 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
382 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY
)
387 foreach ( $res as $row ) {
388 $title = Title
::newFromRow( $row );
389 if ( $row->cl_collation
=== '' ) {
390 // Hack to make sure that while updating from 1.16 schema
391 // and db is inconsistent, that the sky doesn't fall.
392 // See r83544. Could perhaps be removed in a couple decades...
393 $humanSortkey = $row->cl_sortkey
;
395 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
398 if ( ++
$count > $this->limit
) {
399 # We've reached the one extra which shows that there
400 # are additional pages to be had. Stop here...
401 $this->nextPage
[$type] = $humanSortkey;
405 if ( $title->getNamespace() == NS_CATEGORY
) {
406 $cat = Category
::newFromRow( $row, $title );
407 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
408 } elseif ( $title->getNamespace() == NS_FILE
) {
409 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
411 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
417 function getCategoryTop() {
418 $r = $this->getCategoryBottom();
421 : "<br style=\"clear:both;\"/>\n" . $r;
424 function getSubcategorySection() {
425 # Don't show subcategories section if there are none.
427 $rescnt = count( $this->children
);
428 $dbcnt = $this->cat
->getSubcatCount();
429 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
432 # Showing subcategories
433 $r .= "<div id=\"mw-subcategories\">\n";
434 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
436 $r .= $this->getSectionPagingLinks( 'subcat' );
437 $r .= $this->formatList( $this->children
, $this->children_start_char
);
438 $r .= $this->getSectionPagingLinks( 'subcat' );
444 function getPagesSection() {
445 $ti = htmlspecialchars( $this->title
->getText() );
446 # Don't show articles section if there are none.
449 # @todo FIXME: Here and in the other two sections: we don't need to bother
450 # with this rigamarole if the entire category contents fit on one page
451 # and have already been retrieved. We can just use $rescnt in that
452 # case and save a query and some logic.
453 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
454 - $this->cat
->getFileCount();
455 $rescnt = count( $this->articles
);
456 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
459 $r = "<div id=\"mw-pages\">\n";
460 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
462 $r .= $this->getSectionPagingLinks( 'page' );
463 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
464 $r .= $this->getSectionPagingLinks( 'page' );
470 function getImageSection() {
472 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
474 $dbcnt = $this->cat
->getFileCount();
475 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
477 $r .= "<div id=\"mw-category-media\">\n";
478 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title
->getText() ) ) . "</h2>\n";
480 $r .= $this->getSectionPagingLinks( 'file' );
481 if ( $this->showGallery
) {
482 $r .= $this->gallery
->toHTML();
484 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
486 $r .= $this->getSectionPagingLinks( 'file' );
493 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
496 * @param $type String: 'page', 'subcat', or 'file'
497 * @return String: HTML output, possibly empty if there are no other pages
499 private function getSectionPagingLinks( $type ) {
500 if ( $this->until
[$type] !== null ) {
501 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
502 } elseif ( $this->nextPage
[$type] !== null ||
$this->from
[$type] !== null ) {
503 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
509 function getCategoryBottom() {
514 * Format a list of articles chunked by letter, either as a
515 * bullet list or a columnar format, depending on the length.
517 * @param $articles Array
518 * @param $articles_start_char Array
523 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
525 if ( count ( $articles ) > $cutoff ) {
526 $list = self
::columnList( $articles, $articles_start_char );
527 } elseif ( count( $articles ) > 0 ) {
528 // for short lists of articles in categories.
529 $list = self
::shortList( $articles, $articles_start_char );
532 $pageLang = $this->title
->getPageLanguage();
533 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
534 'class' => 'mw-content-'.$pageLang->getDir() );
535 $list = Html
::rawElement( 'div', $attribs, $list );
541 * Format a list of articles chunked by letter in a three-column
542 * list, ordered vertically.
544 * TODO: Take the headers into account when creating columns, so they're
545 * more visually equal.
547 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
550 * @param $articles Array
551 * @param $articles_start_char Array
555 static function columnList( $articles, $articles_start_char ) {
556 $columns = array_combine( $articles, $articles_start_char );
557 # Split into three columns
558 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
560 $ret = '<table width="100%"><tr valign="top"><td>';
563 foreach ( $columns as $column ) {
564 $colContents = array();
566 # Kind of like array_flip() here, but we keep duplicates in an
567 # array instead of dropping them.
568 foreach ( $column as $article => $char ) {
569 if ( !isset( $colContents[$char] ) ) {
570 $colContents[$char] = array();
572 $colContents[$char][] = $article;
576 foreach ( $colContents as $char => $articles ) {
577 $ret .= '<h3>' . htmlspecialchars( $char );
578 if ( $first && $char === $prevchar ) {
579 # We're continuing a previous chunk at the top of a new
580 # column, so add " cont." after the letter.
581 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
586 $ret .= implode( "</li>\n<li>", $articles );
587 $ret .= '</li></ul>';
593 $ret .= "</td>\n<td>";
596 $ret .= '</td></tr></table>';
601 * Format a list of articles chunked by letter in a bullet list.
602 * @param $articles Array
603 * @param $articles_start_char Array
607 static function shortList( $articles, $articles_start_char ) {
608 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
609 $r .= '<ul><li>' . $articles[0] . '</li>';
610 for ( $index = 1; $index < count( $articles ); $index++
) {
611 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
612 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
615 $r .= "<li>{$articles[$index]}</li>";
622 * Create paging links, as a helper method to getSectionPagingLinks().
624 * @param $first String The 'until' parameter for the generated URL
625 * @param $last String The 'from' parameter for the genererated URL
626 * @param $type String A prefix for parameters, 'page' or 'subcat' or
628 * @return String HTML
630 private function pagingLinks( $first, $last, $type = '' ) {
631 $prevLink = wfMessage( 'prevn' )->numParams( $this->limit
)->escaped();
633 if ( $first != '' ) {
634 $prevQuery = $this->query
;
635 $prevQuery["{$type}until"] = $first;
636 unset( $prevQuery["{$type}from"] );
637 $prevLink = Linker
::linkKnown(
638 $this->addFragmentToTitle( $this->title
, $type ),
645 $nextLink = wfMessage( 'nextn' )->numParams( $this->limit
)->escaped();
648 $lastQuery = $this->query
;
649 $lastQuery["{$type}from"] = $last;
650 unset( $lastQuery["{$type}until"] );
651 $nextLink = Linker
::linkKnown(
652 $this->addFragmentToTitle( $this->title
, $type ),
659 return "($prevLink) ($nextLink)";
663 * Takes a title, and adds the fragment identifier that
664 * corresponds to the correct segment of the category.
666 * @param Title $title: The title (usually $this->title)
667 * @param String $section: Which section
669 private function addFragmentToTitle( $title, $section ) {
670 switch ( $section ) {
672 $fragment = 'mw-pages';
675 $fragment = 'mw-subcategories';
678 $fragment = 'mw-category-media';
681 throw new MWException( __METHOD__
.
682 " Invalid section $section." );
685 return Title
::makeTitle( $title->getNamespace(),
686 $title->getDBkey(), $fragment );
689 * What to do if the category table conflicts with the number of results
690 * returned? This function says what. Each type is considered independently
691 * of the other types.
693 * Note for grepping: uses the messages category-article-count,
694 * category-article-count-limited, category-subcat-count,
695 * category-subcat-count-limited, category-file-count,
696 * category-file-count-limited.
698 * @param $rescnt Int: The number of items returned by our database query.
699 * @param $dbcnt Int: The number of items according to the category table.
700 * @param $type String: 'subcat', 'article', or 'file'
701 * @return String: A message giving the number of items, to output to HTML.
703 private function getCountMessage( $rescnt, $dbcnt, $type ) {
704 # There are three cases:
705 # 1) The category table figure seems sane. It might be wrong, but
706 # we can't do anything about it if we don't recalculate it on ev-
708 # 2) The category table figure isn't sane, like it's smaller than the
709 # number of actual results, *but* the number of results is less
710 # than $this->limit and there's no offset. In this case we still
711 # know the right figure.
712 # 3) We have no idea.
714 # Check if there's a "from" or "until" for anything
716 // This is a little ugly, but we seem to use different names
717 // for the paging types then for the messages.
718 if ( $type === 'article' ) {
719 $pagingType = 'page';
724 $fromOrUntil = false;
725 if ( $this->from
[$pagingType] !== null ||
$this->until
[$pagingType] !== null ) {
729 if ( $dbcnt == $rescnt ||
( ( $rescnt == $this->limit ||
$fromOrUntil )
730 && $dbcnt > $rescnt ) ) {
731 # Case 1: seems sane.
733 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
734 # Case 2: not sane, but salvageable. Use the number of results.
735 # Since there are fewer than 200, we can also take this opportunity
736 # to refresh the incorrect category table entry -- which should be
737 # quick due to the small number of entries.
739 $this->cat
->refreshCounts();
741 # Case 3: hopeless. Don't give a total count at all.
742 return wfMessage( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
744 return wfMessage( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();