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
{
37 public $articles_start_char;
43 public $children_start_char;
49 public $imgsNoGallery_start_char;
52 public $imgsNoGallery;
69 /** @var ImageGallery */
72 /** @var Category Category object for this page. */
75 /** @var array The original query array, to be used in generating paging links. */
79 * @since 1.19 $context is a second, required parameter
81 * @param IContextSource $context
82 * @param array $from An array with keys page, subcat,
83 * and file for offset of results of each section (since 1.17)
84 * @param array $until An array with 3 keys for until of each section (since 1.17)
87 function __construct( $title, IContextSource
$context, $from = array(),
88 $until = array(), $query = array()
90 $this->title
= $title;
91 $this->setContext( $context );
93 $this->until
= $until;
94 $this->limit
= $context->getConfig()->get( 'CategoryPagingLimit' );
95 $this->cat
= Category
::newFromTitle( $title );
96 $this->query
= $query;
97 $this->collation
= Collation
::singleton();
98 unset( $this->query
['title'] );
102 * Format the category data list.
104 * @return string HTML output
106 public function getHTML() {
108 $this->showGallery
= $this->getConfig()->get( 'CategoryMagicGallery' )
109 && !$this->getOutput()->mNoGallery
;
111 $this->clearCategoryState();
112 $this->doCategoryQuery();
113 $this->finaliseCategoryState();
115 $r = $this->getSubcategorySection() .
116 $this->getPagesSection() .
117 $this->getImageSection();
120 // If there is no category content to display, only
121 // show the top part of the navigation links.
122 // @todo FIXME: Cannot be completely suppressed because it
123 // is unknown if 'until' or 'from' makes this
125 $r = $r . $this->getCategoryTop();
127 $r = $this->getCategoryTop() .
129 $this->getCategoryBottom();
132 // Give a proper message if category is empty
134 $r = $this->msg( 'category-empty' )->parseAsBlock();
137 $lang = $this->getLanguage();
138 $langAttribs = array( 'lang' => $lang->getHtmlCode(), 'dir' => $lang->getDir() );
139 # put a div around the headings which are in the user language
140 $r = Html
::openElement( 'div', $langAttribs ) . $r . '</div>';
145 function clearCategoryState() {
146 $this->articles
= array();
147 $this->articles_start_char
= array();
148 $this->children
= array();
149 $this->children_start_char
= array();
150 if ( $this->showGallery
) {
151 // Note that null for mode is taken to mean use default.
152 $mode = $this->getRequest()->getVal( 'gallerymode', null );
154 $this->gallery
= ImageGalleryBase
::factory( $mode, $this->getContext() );
155 } catch ( Exception
$e ) {
156 // User specified something invalid, fallback to default.
157 $this->gallery
= ImageGalleryBase
::factory( false, $this->getContext() );
160 $this->gallery
->setHideBadImages();
162 $this->imgsNoGallery
= array();
163 $this->imgsNoGallery_start_char
= array();
168 * Add a subcategory to the internal lists, using a Category object
169 * @param Category $cat
170 * @param string $sortkey
171 * @param int $pageLength
173 function addSubcategoryObject( Category
$cat, $sortkey, $pageLength ) {
174 // Subcategory; strip the 'Category' namespace from the link text.
175 $title = $cat->getTitle();
177 $this->children
[] = $this->generateLink(
180 $title->isRedirect(),
181 htmlspecialchars( $title->getText() )
184 $this->children_start_char
[] =
185 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
188 function generateLink( $type, Title
$title, $isRedirect, $html = null ) {
190 Hooks
::run( 'CategoryViewer::generateLink', array( $type, $title, $html, &$link ) );
191 if ( $link === null ) {
192 $link = Linker
::link( $title, $html );
195 $link = '<span class="redirect-in-category">' . $link . '</span>';
202 * Get the character to be used for sorting subcategories.
203 * If there's a link from Category:A to Category:B, the sortkey of the resulting
204 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
205 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
206 * else use sortkey...
208 * @param Title $title
209 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
212 function getSubcategorySortChar( $title, $sortkey ) {
215 if ( $title->getPrefixedText() == $sortkey ) {
216 $word = $title->getDBkey();
221 $firstChar = $this->collation
->getFirstLetter( $word );
223 return $wgContLang->convert( $firstChar );
227 * Add a page in the image namespace
228 * @param Title $title
229 * @param string $sortkey
230 * @param int $pageLength
231 * @param bool $isRedirect
233 function addImage( Title
$title, $sortkey, $pageLength, $isRedirect = false ) {
235 if ( $this->showGallery
) {
236 $flip = $this->flip
['file'];
238 $this->gallery
->insert( $title );
240 $this->gallery
->add( $title );
243 $this->imgsNoGallery
[] = $this->generateLink( 'image', $title, $isRedirect );
245 $this->imgsNoGallery_start_char
[] = $wgContLang->convert(
246 $this->collation
->getFirstLetter( $sortkey ) );
251 * Add a miscellaneous page
252 * @param Title $title
253 * @param string $sortkey
254 * @param int $pageLength
255 * @param bool $isRedirect
257 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
260 $this->articles
[] = $this->generateLink( 'page', $title, $isRedirect );
262 $this->articles_start_char
[] = $wgContLang->convert(
263 $this->collation
->getFirstLetter( $sortkey ) );
266 function finaliseCategoryState() {
267 if ( $this->flip
['subcat'] ) {
268 $this->children
= array_reverse( $this->children
);
269 $this->children_start_char
= array_reverse( $this->children_start_char
);
271 if ( $this->flip
['page'] ) {
272 $this->articles
= array_reverse( $this->articles
);
273 $this->articles_start_char
= array_reverse( $this->articles_start_char
);
275 if ( !$this->showGallery
&& $this->flip
['file'] ) {
276 $this->imgsNoGallery
= array_reverse( $this->imgsNoGallery
);
277 $this->imgsNoGallery_start_char
= array_reverse( $this->imgsNoGallery_start_char
);
281 function doCategoryQuery() {
282 $dbr = wfGetDB( DB_SLAVE
, 'category' );
284 $this->nextPage
= array(
289 $this->prevPage
= array(
295 $this->flip
= array( 'page' => false, 'subcat' => false, 'file' => false );
297 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
298 # Get the sortkeys for start/end, if applicable. Note that if
299 # the collation in the database differs from the one
300 # set in $wgCategoryCollation, pagination might go totally haywire.
301 $extraConds = array( 'cl_type' => $type );
302 if ( isset( $this->from
[$type] ) && $this->from
[$type] !== null ) {
303 $extraConds[] = 'cl_sortkey >= '
304 . $dbr->addQuotes( $this->collation
->getSortKey( $this->from
[$type] ) );
305 } elseif ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
306 $extraConds[] = 'cl_sortkey < '
307 . $dbr->addQuotes( $this->collation
->getSortKey( $this->until
[$type] ) );
308 $this->flip
[$type] = true;
312 array( 'page', 'categorylinks', 'category' ),
313 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
314 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
315 'cat_subcats', 'cat_pages', 'cat_files',
316 'cl_sortkey_prefix', 'cl_collation' ),
317 array_merge( array( 'cl_to' => $this->title
->getDBkey() ), $extraConds ),
320 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
321 'LIMIT' => $this->limit +
1,
322 'ORDER BY' => $this->flip
[$type] ?
'cl_sortkey DESC' : 'cl_sortkey',
325 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
326 'category' => array( 'LEFT JOIN', array(
327 'cat_title = page_title',
328 'page_namespace' => NS_CATEGORY
333 Hooks
::run( 'CategoryViewer::doCategoryQuery', array( $type, $res ) );
336 foreach ( $res as $row ) {
337 $title = Title
::newFromRow( $row );
338 if ( $row->cl_collation
=== '' ) {
339 // Hack to make sure that while updating from 1.16 schema
340 // and db is inconsistent, that the sky doesn't fall.
341 // See r83544. Could perhaps be removed in a couple decades...
342 $humanSortkey = $row->cl_sortkey
;
344 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix
);
347 if ( ++
$count > $this->limit
) {
348 # We've reached the one extra which shows that there
349 # are additional pages to be had. Stop here...
350 $this->nextPage
[$type] = $humanSortkey;
353 if ( $count == $this->limit
) {
354 $this->prevPage
[$type] = $humanSortkey;
357 if ( $title->getNamespace() == NS_CATEGORY
) {
358 $cat = Category
::newFromRow( $row, $title );
359 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len
);
360 } elseif ( $title->getNamespace() == NS_FILE
) {
361 $this->addImage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
363 $this->addPage( $title, $humanSortkey, $row->page_len
, $row->page_is_redirect
);
372 function getCategoryTop() {
373 $r = $this->getCategoryBottom();
376 : "<br style=\"clear:both;\"/>\n" . $r;
382 function getSubcategorySection() {
383 # Don't show subcategories section if there are none.
385 $rescnt = count( $this->children
);
386 $dbcnt = $this->cat
->getSubcatCount();
387 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
390 # Showing subcategories
391 $r .= "<div id=\"mw-subcategories\">\n";
392 $r .= '<h2>' . $this->msg( 'subcategories' )->parse() . "</h2>\n";
394 $r .= $this->getSectionPagingLinks( 'subcat' );
395 $r .= $this->formatList( $this->children
, $this->children_start_char
);
396 $r .= $this->getSectionPagingLinks( 'subcat' );
405 function getPagesSection() {
406 $ti = wfEscapeWikiText( $this->title
->getText() );
407 # Don't show articles section if there are none.
410 # @todo FIXME: Here and in the other two sections: we don't need to bother
411 # with this rigmarole if the entire category contents fit on one page
412 # and have already been retrieved. We can just use $rescnt in that
413 # case and save a query and some logic.
414 $dbcnt = $this->cat
->getPageCount() - $this->cat
->getSubcatCount()
415 - $this->cat
->getFileCount();
416 $rescnt = count( $this->articles
);
417 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
420 $r = "<div id=\"mw-pages\">\n";
421 $r .= '<h2>' . $this->msg( 'category_header', $ti )->parse() . "</h2>\n";
423 $r .= $this->getSectionPagingLinks( 'page' );
424 $r .= $this->formatList( $this->articles
, $this->articles_start_char
);
425 $r .= $this->getSectionPagingLinks( 'page' );
434 function getImageSection() {
436 $rescnt = $this->showGallery ?
$this->gallery
->count() : count( $this->imgsNoGallery
);
438 $dbcnt = $this->cat
->getFileCount();
439 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
441 $r .= "<div id=\"mw-category-media\">\n";
444 'category-media-header',
445 wfEscapeWikiText( $this->title
->getText() )
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 string $type 'page', 'subcat', or 'file'
466 * @return string HTML output, possibly empty if there are no other pages
468 private function getSectionPagingLinks( $type ) {
469 if ( isset( $this->until
[$type] ) && $this->until
[$type] !== null ) {
470 // The new value for the until parameter should be pointing to the first
471 // result displayed on the page which is the second last result retrieved
472 // from the database.The next link should have a from parameter pointing
473 // to the until parameter of the current page.
474 if ( $this->nextPage
[$type] !== null ) {
475 return $this->pagingLinks( $this->prevPage
[$type], $this->until
[$type], $type );
477 // If the nextPage variable is null, it means that we have reached the first page
478 // and therefore the previous link should be disabled.
479 return $this->pagingLinks( null, $this->until
[$type], $type );
481 } elseif ( $this->nextPage
[$type] !== null
482 ||
( isset( $this->from
[$type] ) && $this->from
[$type] !== null )
484 return $this->pagingLinks( $this->from
[$type], $this->nextPage
[$type], $type );
493 function getCategoryBottom() {
498 * Format a list of articles chunked by letter, either as a
499 * bullet list or a columnar format, depending on the length.
501 * @param array $articles
502 * @param array $articles_start_char
507 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
509 if ( count( $articles ) > $cutoff ) {
510 $list = self
::columnList( $articles, $articles_start_char );
511 } elseif ( count( $articles ) > 0 ) {
512 // for short lists of articles in categories.
513 $list = self
::shortList( $articles, $articles_start_char );
516 $pageLang = $this->title
->getPageLanguage();
517 $attribs = array( 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
518 'class' => 'mw-content-' . $pageLang->getDir() );
519 $list = Html
::rawElement( 'div', $attribs, $list );
525 * Format a list of articles chunked by letter in a three-column
526 * list, ordered vertically.
528 * TODO: Take the headers into account when creating columns, so they're
529 * more visually equal.
531 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
534 * @param array $articles
535 * @param string[] $articles_start_char
539 static function columnList( $articles, $articles_start_char ) {
540 $columns = array_combine( $articles, $articles_start_char );
541 # Split into three columns
542 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
544 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
547 foreach ( $columns as $column ) {
548 $ret .= '<td style="width: 33.3%;">';
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 # Change space to non-breaking space to keep headers aligned
563 $h3char = $char === ' ' ?
' ' : htmlspecialchars( $char );
565 $ret .= '<h3>' . $h3char;
566 if ( $first && $char === $prevchar ) {
567 # We're continuing a previous chunk at the top of a new
568 # column, so add " cont." after the letter.
569 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
574 $ret .= implode( "</li>\n<li>", $articles );
575 $ret .= '</li></ul>';
584 $ret .= '</tr></table>';
589 * Format a list of articles chunked by letter in a bullet list.
590 * @param array $articles
591 * @param string[] $articles_start_char
595 static function shortList( $articles, $articles_start_char ) {
596 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
597 $r .= '<ul><li>' . $articles[0] . '</li>';
598 $articleCount = count( $articles );
599 for ( $index = 1; $index < $articleCount; $index++
) {
600 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
601 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
604 $r .= "<li>{$articles[$index]}</li>";
611 * Create paging links, as a helper method to getSectionPagingLinks().
613 * @param string $first The 'until' parameter for the generated URL
614 * @param string $last The 'from' parameter for the generated URL
615 * @param string $type A prefix for parameters, 'page' or 'subcat' or
617 * @return string HTML
619 private function pagingLinks( $first, $last, $type = '' ) {
620 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit
)->escaped();
622 if ( $first != '' ) {
623 $prevQuery = $this->query
;
624 $prevQuery["{$type}until"] = $first;
625 unset( $prevQuery["{$type}from"] );
626 $prevLink = Linker
::linkKnown(
627 $this->addFragmentToTitle( $this->title
, $type ),
634 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit
)->escaped();
637 $lastQuery = $this->query
;
638 $lastQuery["{$type}from"] = $last;
639 unset( $lastQuery["{$type}until"] );
640 $nextLink = Linker
::linkKnown(
641 $this->addFragmentToTitle( $this->title
, $type ),
648 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
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
657 * @throws MWException
660 private function addFragmentToTitle( $title, $section ) {
661 switch ( $section ) {
663 $fragment = 'mw-pages';
666 $fragment = 'mw-subcategories';
669 $fragment = 'mw-category-media';
672 throw new MWException( __METHOD__
.
673 " Invalid section $section." );
676 return Title
::makeTitle( $title->getNamespace(),
677 $title->getDBkey(), $fragment );
681 * What to do if the category table conflicts with the number of results
682 * returned? This function says what. Each type is considered independently
683 * of the other types.
685 * @param int $rescnt The number of items returned by our database query.
686 * @param int $dbcnt The number of items according to the category table.
687 * @param string $type 'subcat', 'article', or 'file'
688 * @return string A message giving the number of items, to output to HTML.
690 private function getCountMessage( $rescnt, $dbcnt, $type ) {
691 // There are three cases:
692 // 1) The category table figure seems sane. It might be wrong, but
693 // we can't do anything about it if we don't recalculate it on ev-
694 // ery category view.
695 // 2) The category table figure isn't sane, like it's smaller than the
696 // number of actual results, *but* the number of results is less
697 // than $this->limit and there's no offset. In this case we still
698 // know the right figure.
699 // 3) We have no idea.
701 // Check if there's a "from" or "until" for anything
703 // This is a little ugly, but we seem to use different names
704 // for the paging types then for the messages.
705 if ( $type === 'article' ) {
706 $pagingType = 'page';
711 $fromOrUntil = false;
712 if ( ( isset( $this->from
[$pagingType] ) && $this->from
[$pagingType] !== null ) ||
713 ( isset( $this->until
[$pagingType] ) && $this->until
[$pagingType] !== null )
718 if ( $dbcnt == $rescnt ||
719 ( ( $rescnt == $this->limit ||
$fromOrUntil ) && $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 $category = $this->cat
;
730 wfGetDB( DB_MASTER
)->onTransactionIdle( function () use ( $category ) {
731 $category->refreshCounts();
734 // Case 3: hopeless. Don't give a total count at all.
735 // Messages: category-subcat-count-limited, category-article-count-limited,
736 // category-file-count-limited
737 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
739 // Messages: category-subcat-count, category-article-count, category-file-count
740 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();