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 // Note that null for mode is taken to mean use default.
145 $mode = $this->getRequest()->getVal( 'gallerymode', null );
147 $this->gallery
= ImageGalleryBase
::factory( $mode );
148 } catch ( MWException
$e ) {
149 // User specified something invalid, fallback to default.
150 $this->gallery
= ImageGalleryBase
::factory();
153 $this->gallery
->setHideBadImages();
154 $this->gallery
->setContext( $this->getContext() );
156 $this->imgsNoGallery
= array();
157 $this->imgsNoGallery_start_char
= array();
162 * Add a subcategory to the internal lists, using a Category object
163 * @param $cat Category
167 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
168 // Subcategory; strip the 'Category' namespace from the link text.
169 $title = $cat->getTitle();
171 $link = Linker
::link( $title, htmlspecialchars( $title->getText() ) );
172 if ( $title->isRedirect() ) {
173 // This didn't used to add redirect-in-category, but might
174 // as well be consistent with the rest of the sections
175 // on a category page.
176 $link = '<span class="redirect-in-category">' . $link . '</span>';
178 $this->children
[] = $link;
180 $this->children_start_char
[] =
181 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
185 * Add a subcategory to the internal lists, using a title object
186 * @deprecated since 1.17 kept for compatibility, use addSubcategoryObject instead
188 function addSubcategory( Title
$title, $sortkey, $pageLength ) {
189 wfDeprecated( __METHOD__
, '1.17' );
190 $this->addSubcategoryObject( Category
::newFromTitle( $title ), $sortkey, $pageLength );
194 * Get the character to be used for sorting subcategories.
195 * If there's a link from Category:A to Category:B, the sortkey of the resulting
196 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
197 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
198 * else use sortkey...
200 * @param Title $title
201 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
204 function getSubcategorySortChar( $title, $sortkey ) {
207 if ( $title->getPrefixedText() == $sortkey ) {
208 $word = $title->getDBkey();
213 $firstChar = $this->collation
->getFirstLetter( $word );
215 return $wgContLang->convert( $firstChar );
219 * Add a page in the image namespace
220 * @param $title Title
223 * @param $isRedirect bool
225 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
227 if ( $this->showGallery
) {
228 $flip = $this->flip
['file'];
230 $this->gallery
->insert( $title );
232 $this->gallery
->add( $title );
235 $link = Linker
::link( $title );
237 // This seems kind of pointless given 'mw-redirect' class,
238 // but keeping for back-compatibility with user css.
239 $link = '<span class="redirect-in-category">' . $link . '</span>';
241 $this->imgsNoGallery
[] = $link;
243 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
244 $this->collation
->getFirstLetter( $sortkey ) );
249 * Add a miscellaneous page
253 * @param $isRedirect bool
255 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
258 $link = Linker
::link( $title );
260 // This seems kind of pointless given 'mw-redirect' class,
261 // but keeping for back-compatibility with user css.
262 $link = '<span class="redirect-in-category">' . $link . '</span>';
264 $this->articles
[] = $link;
266 $this->articles_start_char
[] = $wgContLang->convert(
267 $this->collation
->getFirstLetter( $sortkey ) );
270 function finaliseCategoryState() {
271 if ( $this->flip
['subcat'] ) {
272 $this->children
= array_reverse( $this->children
);
273 $this->children_start_char
= array_reverse( $this->children_start_char
);
275 if ( $this->flip
['page'] ) {
276 $this->articles
= array_reverse( $this->articles
);
277 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
279 if ( !$this->showGallery
&& $this->flip
['file'] ) {
280 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
281 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
285 function doCategoryQuery() {
286 $dbr = wfGetDB( DB_SLAVE
, 'category' );
288 $this->nextPage
= array(
293 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
295 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
296 # Get the sortkeys for start/end, if applicable. Note that if
297 # the collation in the database differs from the one
298 # set in $wgCategoryCollation, pagination might go totally haywire.
299 $extraConds = array( 'cl_type' => $type );
300 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
301 $extraConds[] = 'cl_sortkey >= '
302 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
303 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
304 $extraConds[] = 'cl_sortkey < '
305 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
306 $this->flip
[$type] = true;
310 array( 'page', 'categorylinks', 'category' ),
311 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
312 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
313 'cat_subcats', 'cat_pages', 'cat_files',
314 'cl_sortkey_prefix', 'cl_collation' ),
315 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
318 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
319 'LIMIT' => $this->limit +
1,
320 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
323 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
324 'category' => array( 'LEFT JOIN', array(
325 'cat_title = page_title',
326 'page_namespace' => NS_CATEGORY
332 foreach ( $res as $row ) {
333 $title = Title
::newFromRow( $row );
334 if ( $row->cl_collation
=== '' ) {
335 // Hack to make sure that while updating from 1.16 schema
336 // and db is inconsistent, that the sky doesn't fall.
337 // See r83544. Could perhaps be removed in a couple decades...
338 $humanSortkey = $row->cl_sortkey
;
340 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
343 if ( ++
$count > $this->limit
) {
344 # We've reached the one extra which shows that there
345 # are additional pages to be had. Stop here...
346 $this->nextPage
[$type] = $humanSortkey;
350 if ( $title->getNamespace() == NS_CATEGORY
) {
351 $cat = Category
::newFromRow( $row, $title );
352 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
353 } elseif ( $title->getNamespace() == NS_FILE
) {
354 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
356 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
365 function getCategoryTop() {
366 $r = $this->getCategoryBottom();
369 : "<br style=\"clear:both;\"/>\n" . $r;
375 function getSubcategorySection() {
376 # Don't show subcategories section if there are none.
378 $rescnt = count( $this->children
);
379 $dbcnt = $this->cat
->getSubcatCount();
380 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
383 # Showing subcategories
384 $r .= "<div id=\"mw-subcategories\">\n";
385 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
387 $r .= $this->getSectionPagingLinks( 'subcat' );
388 $r .= $this->formatList( $this->children
, $this->children_start_char
);
389 $r .= $this->getSectionPagingLinks( 'subcat' );
398 function getPagesSection() {
399 $ti = wfEscapeWikiText( $this->title
->getText() );
400 # Don't show articles section if there are none.
403 # @todo FIXME: Here and in the other two sections: we don't need to bother
404 # with this rigmarole if the entire category contents fit on one page
405 # and have already been retrieved. We can just use $rescnt in that
406 # case and save a query and some logic.
407 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
408 - $this->cat
->getFileCount();
409 $rescnt = count( $this->articles
);
410 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
413 $r = "<div id=\"mw-pages\">\n";
414 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
416 $r .= $this->getSectionPagingLinks( 'page' );
417 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
418 $r .= $this->getSectionPagingLinks( 'page' );
427 function getImageSection() {
429 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
431 $dbcnt = $this->cat
->getFileCount();
432 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
434 $r .= "<div id=\"mw-category-media\">\n";
435 $r .= '<h2>' . $this->msg( 'category-media-header', wfEscapeWikiText( $this->title
->getText() ) )->text() . "</h2>\n";
437 $r .= $this->getSectionPagingLinks( 'file' );
438 if ( $this->showGallery
) {
439 $r .= $this->gallery
->toHTML();
441 $r .= $this->formatList( $this->imgsNoGallery
, $this->imgsNoGallery_start_char
);
443 $r .= $this->getSectionPagingLinks( 'file' );
450 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
453 * @param string $type 'page', 'subcat', or 'file'
454 * @return String: HTML output, possibly empty if there are no other pages
456 private function getSectionPagingLinks( $type ) {
457 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
458 return $this->pagingLinks( $this->nextPage
[$type], $this->until
[$type], $type );
459 } elseif ( $this->nextPage
[$type] !== null ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) ) {
460 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
469 function getCategoryBottom() {
474 * Format a list of articles chunked by letter, either as a
475 * bullet list or a columnar format, depending on the length.
477 * @param $articles Array
478 * @param $articles_start_char Array
483 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
485 if ( count( $articles ) > $cutoff ) {
486 $list = self
::columnList( $articles, $articles_start_char );
487 } elseif ( count( $articles ) > 0 ) {
488 // for short lists of articles in categories.
489 $list = self
::shortList( $articles, $articles_start_char );
492 $pageLang = $this->title
->getPageLanguage();
493 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
494 'class' => 'mw-content-' . $pageLang->getDir() );
495 $list = Html
::rawElement( 'div', $attribs, $list );
501 * Format a list of articles chunked by letter in a three-column
502 * list, ordered vertically.
504 * TODO: Take the headers into account when creating columns, so they're
505 * more visually equal.
507 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
510 * @param $articles Array
511 * @param $articles_start_char Array
515 static function columnList( $articles, $articles_start_char ) {
516 $columns = array_combine( $articles, $articles_start_char );
517 # Split into three columns
518 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
520 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
523 foreach ( $columns as $column ) {
524 $ret .= '<td style="width: 33.3%;">';
525 $colContents = array();
527 # Kind of like array_flip() here, but we keep duplicates in an
528 # array instead of dropping them.
529 foreach ( $column as $article => $char ) {
530 if ( !isset( $colContents[$char] ) ) {
531 $colContents[$char] = array();
533 $colContents[$char][] = $article;
537 foreach ( $colContents as $char => $articles ) {
538 # Change space to non-breaking space to keep headers aligned
539 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
541 $ret .= '<h3>' . $h3char;
542 if ( $first && $char === $prevchar ) {
543 # We're continuing a previous chunk at the top of a new
544 # column, so add " cont." after the letter.
545 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
550 $ret .= implode( "</li>\n<li>", $articles );
551 $ret .= '</li></ul>';
560 $ret .= '</tr></table>';
565 * Format a list of articles chunked by letter in a bullet list.
566 * @param $articles Array
567 * @param $articles_start_char Array
571 static function shortList( $articles, $articles_start_char ) {
572 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
573 $r .= '<ul><li>' . $articles[0] . '</li>';
574 for ( $index = 1; $index < count( $articles ); $index++
) {
575 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
576 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
579 $r .= "<li>{$articles[$index]}</li>";
586 * Create paging links, as a helper method to getSectionPagingLinks().
588 * @param string $first The 'until' parameter for the generated URL
589 * @param string $last The 'from' parameter for the generated URL
590 * @param string $type A prefix for parameters, 'page' or 'subcat' or
592 * @return String HTML
594 private function pagingLinks( $first, $last, $type = '' ) {
595 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit
)->escaped();
597 if ( $first != '' ) {
598 $prevQuery = $this->query
;
599 $prevQuery["{$type}until"] = $first;
600 unset( $prevQuery["{$type}from"] );
601 $prevLink = Linker
::linkKnown(
602 $this->addFragmentToTitle( $this->title
, $type ),
609 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit
)->escaped();
612 $lastQuery = $this->query
;
613 $lastQuery["{$type}from"] = $last;
614 unset( $lastQuery["{$type}until"] );
615 $nextLink = Linker
::linkKnown(
616 $this->addFragmentToTitle( $this->title
, $type ),
623 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
627 * Takes a title, and adds the fragment identifier that
628 * corresponds to the correct segment of the category.
630 * @param Title $title: The title (usually $this->title)
631 * @param string $section: Which section
632 * @throws MWException
635 private function addFragmentToTitle( $title, $section ) {
636 switch ( $section ) {
638 $fragment = 'mw-pages';
641 $fragment = 'mw-subcategories';
644 $fragment = 'mw-category-media';
647 throw new MWException( __METHOD__
.
648 " Invalid section $section." );
651 return Title
::makeTitle( $title->getNamespace(),
652 $title->getDBkey(), $fragment );
656 * What to do if the category table conflicts with the number of results
657 * returned? This function says what. Each type is considered independently
658 * of the other types.
660 * @param int $rescnt The number of items returned by our database query.
661 * @param int $dbcnt The number of items according to the category table.
662 * @param string $type 'subcat', 'article', or 'file'
663 * @return string: A message giving the number of items, to output to HTML.
665 private function getCountMessage( $rescnt, $dbcnt, $type ) {
666 // There are three cases:
667 // 1) The category table figure seems sane. It might be wrong, but
668 // we can't do anything about it if we don't recalculate it on ev-
669 // ery category view.
670 // 2) The category table figure isn't sane, like it's smaller than the
671 // number of actual results, *but* the number of results is less
672 // than $this->limit and there's no offset. In this case we still
673 // know the right figure.
674 // 3) We have no idea.
676 // Check if there's a "from" or "until" for anything
678 // This is a little ugly, but we seem to use different names
679 // for the paging types then for the messages.
680 if ( $type === 'article' ) {
681 $pagingType = 'page';
686 $fromOrUntil = false;
687 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
688 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
693 if ( $dbcnt == $rescnt ||
694 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $dbcnt > $rescnt )
696 // Case 1: seems sane.
698 } elseif ( $rescnt < $this->limit
&& !$fromOrUntil ) {
699 // Case 2: not sane, but salvageable. Use the number of results.
700 // Since there are fewer than 200, we can also take this opportunity
701 // to refresh the incorrect category table entry -- which should be
702 // quick due to the small number of entries.
704 $this->cat
->refreshCounts();
706 // Case 3: hopeless. Don't give a total count at all.
707 // Messages: category-subcat-count-limited, category-article-count-limited,
708 // category-file-count-limited
709 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
711 // Messages: category-subcat-count, category-article-count, category-file-count
712 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();