3 * List and paging of category members.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 class CategoryViewer
extends ContextSource
{
24 var $limit, $from, $until,
25 $articles, $articles_start_char,
26 $children, $children_start_char,
27 $showGallery, $imgsNoGalley,
28 $imgsNoGallery_start_char,
57 * Category object for this page
63 * The original query array, to be used in generating paging links.
71 * @since 1.19 $context is a second, required parameter
73 * @param $context IContextSource
74 * @param array $from An array with keys page, subcat,
75 * and file for offset of results of each section (since 1.17)
76 * @param array $until An array with 3 keys for until of each section (since 1.17)
79 function __construct( $title, IContextSource
$context, $from = array(), $until = array(), $query = array() ) {
80 global $wgCategoryPagingLimit;
81 $this->title
= $title;
82 $this->setContext( $context );
84 $this->until
= $until;
85 $this->limit
= $wgCategoryPagingLimit;
86 $this->cat
= Category
::newFromTitle( $title );
87 $this->query
= $query;
88 $this->collation
= Collation
::singleton();
89 unset( $this->query
['title'] );
93 * Format the category data list.
95 * @return string HTML output
97 public function getHTML() {
98 global $wgCategoryMagicGallery;
99 wfProfileIn( __METHOD__
);
101 $this->showGallery
= $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery
;
103 $this->clearCategoryState();
104 $this->doCategoryQuery();
105 $this->finaliseCategoryState();
107 $r = $this->getSubcategorySection() .
108 $this->getPagesSection() .
109 $this->getImageSection();
112 // If there is no category content to display, only
113 // show the top part of the navigation links.
114 // @todo FIXME: Cannot be completely suppressed because it
115 // is unknown if 'until' or 'from' makes this
117 $r = $r . $this->getCategoryTop();
119 $r = $this->getCategoryTop() .
121 $this->getCategoryBottom();
124 // Give a proper message if category is empty
126 $r = $this->msg( 'category-empty' )->parseAsBlock();
129 $lang = $this->getLanguage();
130 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
131 # put a div around the headings which are in the user language
132 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
134 wfProfileOut( __METHOD__
);
138 function clearCategoryState() {
139 $this->articles
= array();
140 $this->articles_start_char
= array();
141 $this->children
= array();
142 $this->children_start_char
= array();
143 if ( $this->showGallery
) {
144 $this->gallery
= new ImageGallery();
145 $this->gallery
->setHideBadImages();
147 $this->imgsNoGallery
= array();
148 $this->imgsNoGallery_start_char
= array();
153 * Add a subcategory to the internal lists, using a Category object
154 * @param $cat Category
158 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
159 // Subcategory; strip the 'Category' namespace from the link text.
160 $title = $cat->getTitle();
162 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
163 if ( $title->isRedirect() ) {
164 // This didn't used to add redirect-in-category, but might
165 // as well be consistent with the rest of the sections
166 // on a category page.
167 $link = '<span class="redirect-in-category">' . $link . '</span>';
169 $this->children
[] = $link;
171 $this->children_start_char
[] =
172 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
176 * Add a subcategory to the internal lists, using a title object
177 * @deprecated since 1.17 kept for compatibility, use addSubcategoryObject instead
179 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
180 wfDeprecated( __METHOD__
, '1.17' );
181 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
185 * Get the character to be used for sorting subcategories.
186 * If there's a link from Category:A to Category:B, the sortkey of the resulting
187 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
188 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
189 * else use sortkey...
191 * @param Title $title
192 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
195 function getSubcategorySortChar( $title, $sortkey ) {
198 if ( $title->getPrefixedText() == $sortkey ) {
199 $word = $title->getDBkey();
204 $firstChar = $this->collation
->getFirstLetter( $word );
206 return $wgContLang->convert( $firstChar );
210 * Add a page in the image namespace
211 * @param $title Title
214 * @param $isRedirect bool
216 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
218 if ( $this->showGallery
) {
219 $flip = $this->flip
['file'];
221 $this->gallery
->insert( $title );
223 $this->gallery
->add( $title );
226 $link = Linker
::link( $title );
228 // This seems kind of pointless given 'mw-redirect' class,
229 // but keeping for back-compatibility with user css.
230 $link = '<span class="redirect-in-category">' . $link . '</span>';
232 $this->imgsNoGallery
[] = $link;
234 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
235 $this->collation
->getFirstLetter( $sortkey ) );
240 * Add a miscellaneous page
244 * @param $isRedirect bool
246 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
249 $link = Linker
::link( $title );
251 // This seems kind of pointless given 'mw-redirect' class,
252 // but keeping for back-compatibility with user css.
253 $link = '<span class="redirect-in-category">' . $link . '</span>';
255 $this->articles
[] = $link;
257 $this->articles_start_char
[] = $wgContLang->convert(
258 $this->collation
->getFirstLetter( $sortkey ) );
261 function finaliseCategoryState() {
262 if ( $this->flip
['subcat'] ) {
263 $this->children
= array_reverse( $this->children
);
264 $this->children_start_char
= array_reverse( $this->children_start_char
);
266 if ( $this->flip
['page'] ) {
267 $this->articles
= array_reverse( $this->articles
);
268 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
270 if ( !$this->showGallery
&& $this->flip
['file'] ) {
271 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
272 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
276 function doCategoryQuery() {
277 $dbr = wfGetDB( DB_SLAVE
, 'category' );
279 $this->nextPage
= array(
284 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
286 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
287 # Get the sortkeys for start/end, if applicable. Note that if
288 # the collation in the database differs from the one
289 # set in $wgCategoryCollation, pagination might go totally haywire.
290 $extraConds = array( 'cl_type' => $type );
291 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
292 $extraConds[] = 'cl_sortkey >= '
293 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
294 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
295 $extraConds[] = 'cl_sortkey < '
296 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
297 $this->flip
[$type] = true;
301 array( 'page', 'categorylinks', 'category' ),
302 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
303 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
304 'cat_subcats', 'cat_pages', 'cat_files',
305 'cl_sortkey_prefix', 'cl_collation' ),
306 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
309 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
310 'LIMIT' => $this->limit +
1,
311 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
314 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
315 'category' => array( 'LEFT JOIN', array(
316 'cat_title = page_title',
317 'page_namespace' => NS_CATEGORY
323 foreach ( $res as $row ) {
324 $title = Title
::newFromRow( $row );
325 if ( $row->cl_collation
=== '' ) {
326 // Hack to make sure that while updating from 1.16 schema
327 // and db is inconsistent, that the sky doesn't fall.
328 // See r83544. Could perhaps be removed in a couple decades...
329 $humanSortkey = $row->cl_sortkey
;
331 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
334 if ( ++
$count > $this->limit
) {
335 # We've reached the one extra which shows that there
336 # are additional pages to be had. Stop here...
337 $this->nextPage
[$type] = $humanSortkey;
341 if ( $title->getNamespace() == NS_CATEGORY
) {
342 $cat = Category
::newFromRow( $row, $title );
343 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
344 } elseif ( $title->getNamespace() == NS_FILE
) {
345 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
347 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
356 function getCategoryTop() {
357 $r = $this->getCategoryBottom();
360 : "<br style=\"clear:both;\"/>\n" . $r;
366 function getSubcategorySection() {
367 # Don't show subcategories section if there are none.
369 $rescnt = count( $this->children
);
370 $dbcnt = $this->cat
->getSubcatCount();
371 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
374 # Showing subcategories
375 $r .= "<div id=\"mw-subcategories\">\n";
376 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
378 $r .= $this->getSectionPagingLinks( 'subcat' );
379 $r .= $this->formatList( $this->children
, $this->children_start_char
);
380 $r .= $this->getSectionPagingLinks( 'subcat' );
389 function getPagesSection() {
390 $ti = wfEscapeWikiText( $this->title
->getText() );
391 # Don't show articles section if there are none.
394 # @todo FIXME: Here and in the other two sections: we don't need to bother
395 # with this rigmarole if the entire category contents fit on one page
396 # and have already been retrieved. We can just use $rescnt in that
397 # case and save a query and some logic.
398 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
399 - $this->cat
->getFileCount();
400 $rescnt = count( $this->articles
);
401 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
404 $r = "<div id=\"mw-pages\">\n";
405 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
407 $r .= $this->getSectionPagingLinks( 'page' );
408 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
409 $r .= $this->getSectionPagingLinks( 'page' );
418 function getImageSection() {
420 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
422 $dbcnt = $this->cat
->getFileCount();
423 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
425 $r .= "<div id=\"mw-category-media\">\n";
426 $r .= '<h2>' . $this->msg( 'category-media-header', wfEscapeWikiText( $this->title
->getText() ) )->text() . "</h2>\n";
428 $r .= $this->getSectionPagingLinks( 'file' );
429 if ( $this->showGallery
) {
430 $r .= $this->gallery
->toHTML();
432 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
434 $r .= $this->getSectionPagingLinks( 'file' );
441 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
444 * @param string $type 'page', 'subcat', or 'file'
445 * @return String: HTML output, possibly empty if there are no other pages
447 private function getSectionPagingLinks( $type ) {
448 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
449 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
450 } elseif ( $this->nextPage
[$type] !== null ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) ) {
451 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
460 function getCategoryBottom() {
465 * Format a list of articles chunked by letter, either as a
466 * bullet list or a columnar format, depending on the length.
468 * @param $articles Array
469 * @param $articles_start_char Array
474 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
476 if ( count( $articles ) > $cutoff ) {
477 $list = self
::columnList( $articles, $articles_start_char );
478 } elseif ( count( $articles ) > 0 ) {
479 // for short lists of articles in categories.
480 $list = self
::shortList( $articles, $articles_start_char );
483 $pageLang = $this->title
->getPageLanguage();
484 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
485 'class' => 'mw-content-' . $pageLang->getDir() );
486 $list = Html
::rawElement( 'div', $attribs, $list );
492 * Format a list of articles chunked by letter in a three-column
493 * list, ordered vertically.
495 * TODO: Take the headers into account when creating columns, so they're
496 * more visually equal.
498 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
501 * @param $articles Array
502 * @param $articles_start_char Array
506 static function columnList( $articles, $articles_start_char ) {
507 $columns = array_combine( $articles, $articles_start_char );
508 # Split into three columns
509 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
511 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
514 foreach ( $columns as $column ) {
515 $ret .= '<td style="width: 33.3%;">';
516 $colContents = array();
518 # Kind of like array_flip() here, but we keep duplicates in an
519 # array instead of dropping them.
520 foreach ( $column as $article => $char ) {
521 if ( !isset( $colContents[$char] ) ) {
522 $colContents[$char] = array();
524 $colContents[$char][] = $article;
528 foreach ( $colContents as $char => $articles ) {
529 # Change space to non-breaking space to keep headers aligned
530 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
532 $ret .= '<h3>' . $h3char;
533 if ( $first && $char === $prevchar ) {
534 # We're continuing a previous chunk at the top of a new
535 # column, so add " cont." after the letter.
536 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
541 $ret .= implode( "</li>\n<li>", $articles );
542 $ret .= '</li></ul>';
551 $ret .= '</tr></table>';
556 * Format a list of articles chunked by letter in a bullet list.
557 * @param $articles Array
558 * @param $articles_start_char Array
562 static function shortList( $articles, $articles_start_char ) {
563 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
564 $r .= '<ul><li>' . $articles[0] . '</li>';
565 for ( $index = 1; $index < count( $articles ); $index++
) {
566 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
567 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
570 $r .= "<li>{$articles[$index]}</li>";
577 * Create paging links, as a helper method to getSectionPagingLinks().
579 * @param string $first The 'until' parameter for the generated URL
580 * @param string $last The 'from' parameter for the generated URL
581 * @param string $type A prefix for parameters, 'page' or 'subcat' or
583 * @return String HTML
585 private function pagingLinks( $first, $last, $type = '' ) {
586 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit
)->escaped();
588 if ( $first != '' ) {
589 $prevQuery = $this->query
;
590 $prevQuery["{$type}until"] = $first;
591 unset( $prevQuery["{$type}from"] );
592 $prevLink = Linker
::linkKnown(
593 $this->addFragmentToTitle( $this->title
, $type ),
600 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit
)->escaped();
603 $lastQuery = $this->query
;
604 $lastQuery["{$type}from"] = $last;
605 unset( $lastQuery["{$type}until"] );
606 $nextLink = Linker
::linkKnown(
607 $this->addFragmentToTitle( $this->title
, $type ),
614 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
618 * Takes a title, and adds the fragment identifier that
619 * corresponds to the correct segment of the category.
621 * @param Title $title: The title (usually $this->title)
622 * @param string $section: Which section
623 * @throws MWException
626 private function addFragmentToTitle( $title, $section ) {
627 switch ( $section ) {
629 $fragment = 'mw-pages';
632 $fragment = 'mw-subcategories';
635 $fragment = 'mw-category-media';
638 throw new MWException( __METHOD__
.
639 " Invalid section $section." );
642 return Title
::makeTitle( $title->getNamespace(),
643 $title->getDBkey(), $fragment );
647 * What to do if the category table conflicts with the number of results
648 * returned? This function says what. Each type is considered independently
649 * of the other types.
651 * Note for grepping: uses the messages category-article-count,
652 * category-article-count-limited, category-subcat-count,
653 * category-subcat-count-limited, category-file-count,
654 * category-file-count-limited.
656 * @param int $rescnt The number of items returned by our database query.
657 * @param int $dbcnt The number of items according to the category table.
658 * @param string $type 'subcat', 'article', or 'file'
659 * @return String: A message giving the number of items, to output to HTML.
661 private function getCountMessage( $rescnt, $dbcnt, $type ) {
662 # There are three cases:
663 # 1) The category table figure seems sane. It might be wrong, but
664 # we can't do anything about it if we don't recalculate it on ev-
666 # 2) The category table figure isn't sane, like it's smaller than the
667 # number of actual results, *but* the number of results is less
668 # than $this->limit and there's no offset. In this case we still
669 # know the right figure.
670 # 3) We have no idea.
672 # Check if there's a "from" or "until" for anything
674 // This is a little ugly, but we seem to use different names
675 // for the paging types then for the messages.
676 if ( $type === 'article' ) {
677 $pagingType = 'page';
682 $fromOrUntil = false;
683 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
684 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
689 if ( $dbcnt == $rescnt ||
690 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
692 # Case 1: seems sane.
694 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
695 # Case 2: not sane, but salvageable. Use the number of results.
696 # Since there are fewer than 200, we can also take this opportunity
697 # to refresh the incorrect category table entry -- which should be
698 # quick due to the small number of entries.
700 $this->cat
->refreshCounts();
702 # Case 3: hopeless. Don't give a total count at all.
703 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
705 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();