Move MW_LC_VERSION to class constant instead of global define
[mediawiki.git] / includes / CategoryViewer.php
blob22eb3d1ce74cff5b8102c7324d916d6980922da8
1 <?php
2 /**
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
20 * @file
23 class CategoryViewer extends ContextSource {
24 /** @var int */
25 public $limit;
27 /** @var array */
28 protected $from;
30 /** @var array */
31 protected $until;
33 /** @var string[] */
34 public $articles;
36 /** @var array */
37 public $articles_start_char;
39 /** @var array */
40 protected $children;
42 /** @var array */
43 protected $children_start_char;
45 /** @var bool */
46 protected $showGallery;
48 /** @var array */
49 protected $imgsNoGallery_start_char;
51 /** @var array */
52 protected $imgsNoGallery;
54 /** @var array */
55 protected $nextPage;
57 /** @var array */
58 protected $prevPage;
60 /** @var array */
61 protected $flip;
63 /** @var Title */
64 protected $title;
66 /** @var Collation */
67 protected $collation;
69 /** @var ImageGallery */
70 protected $gallery;
72 /** @var Category Category object for this page. */
73 private $cat;
75 /** @var array The original query array, to be used in generating paging links. */
76 private $query;
78 /**
79 * @since 1.19 $context is a second, required parameter
80 * @param Title $title
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)
85 * @param array $query
87 function __construct( $title, IContextSource $context, $from = array(),
88 $until = array(), $query = array()
89 ) {
90 global $wgCategoryPagingLimit;
91 $this->title = $title;
92 $this->setContext( $context );
93 $this->from = $from;
94 $this->until = $until;
95 $this->limit = $wgCategoryPagingLimit;
96 $this->cat = Category::newFromTitle( $title );
97 $this->query = $query;
98 $this->collation = Collation::singleton();
99 unset( $this->query['title'] );
103 * Format the category data list.
105 * @return string HTML output
107 public function getHTML() {
108 global $wgCategoryMagicGallery;
109 wfProfileIn( __METHOD__ );
111 $this->showGallery = $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery;
113 $this->clearCategoryState();
114 $this->doCategoryQuery();
115 $this->finaliseCategoryState();
117 $r = $this->getSubcategorySection() .
118 $this->getPagesSection() .
119 $this->getImageSection();
121 if ( $r == '' ) {
122 // If there is no category content to display, only
123 // show the top part of the navigation links.
124 // @todo FIXME: Cannot be completely suppressed because it
125 // is unknown if 'until' or 'from' makes this
126 // give 0 results.
127 $r = $r . $this->getCategoryTop();
128 } else {
129 $r = $this->getCategoryTop() .
130 $r .
131 $this->getCategoryBottom();
134 // Give a proper message if category is empty
135 if ( $r == '' ) {
136 $r = $this->msg( 'category-empty' )->parseAsBlock();
139 $lang = $this->getLanguage();
140 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
141 # put a div around the headings which are in the user language
142 $r = Html::openElement( 'div', $langAttribs ) . $r . '</div>';
144 wfProfileOut( __METHOD__ );
145 return $r;
148 function clearCategoryState() {
149 $this->articles = array();
150 $this->articles_start_char = array();
151 $this->children = array();
152 $this->children_start_char = array();
153 if ( $this->showGallery ) {
154 // Note that null for mode is taken to mean use default.
155 $mode = $this->getRequest()->getVal( 'gallerymode', null );
156 try {
157 $this->gallery = ImageGalleryBase::factory( $mode );
158 } catch ( MWException $e ) {
159 // User specified something invalid, fallback to default.
160 $this->gallery = ImageGalleryBase::factory();
163 $this->gallery->setHideBadImages();
164 $this->gallery->setContext( $this->getContext() );
165 } else {
166 $this->imgsNoGallery = array();
167 $this->imgsNoGallery_start_char = array();
172 * Add a subcategory to the internal lists, using a Category object
173 * @param Category $cat
174 * @param string $sortkey
175 * @param int $pageLength
177 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
178 // Subcategory; strip the 'Category' namespace from the link text.
179 $title = $cat->getTitle();
181 $link = Linker::link( $title, htmlspecialchars( $title->getText() ) );
182 if ( $title->isRedirect() ) {
183 // This didn't used to add redirect-in-category, but might
184 // as well be consistent with the rest of the sections
185 // on a category page.
186 $link = '<span class="redirect-in-category">' . $link . '</span>';
188 $this->children[] = $link;
190 $this->children_start_char[] =
191 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
195 * Get the character to be used for sorting subcategories.
196 * If there's a link from Category:A to Category:B, the sortkey of the resulting
197 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
198 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
199 * else use sortkey...
201 * @param Title $title
202 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
203 * @return string
205 function getSubcategorySortChar( $title, $sortkey ) {
206 global $wgContLang;
208 if ( $title->getPrefixedText() == $sortkey ) {
209 $word = $title->getDBkey();
210 } else {
211 $word = $sortkey;
214 $firstChar = $this->collation->getFirstLetter( $word );
216 return $wgContLang->convert( $firstChar );
220 * Add a page in the image namespace
221 * @param Title $title
222 * @param string $sortkey
223 * @param int $pageLength
224 * @param bool $isRedirect
226 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
227 global $wgContLang;
228 if ( $this->showGallery ) {
229 $flip = $this->flip['file'];
230 if ( $flip ) {
231 $this->gallery->insert( $title );
232 } else {
233 $this->gallery->add( $title );
235 } else {
236 $link = Linker::link( $title );
237 if ( $isRedirect ) {
238 // This seems kind of pointless given 'mw-redirect' class,
239 // but keeping for back-compatibility with user css.
240 $link = '<span class="redirect-in-category">' . $link . '</span>';
242 $this->imgsNoGallery[] = $link;
244 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
245 $this->collation->getFirstLetter( $sortkey ) );
250 * Add a miscellaneous page
251 * @param Title $title
252 * @param string $sortkey
253 * @param int $pageLength
254 * @param bool $isRedirect
256 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
257 global $wgContLang;
259 $link = Linker::link( $title );
260 if ( $isRedirect ) {
261 // This seems kind of pointless given 'mw-redirect' class,
262 // but keeping for back-compatibility with user css.
263 $link = '<span class="redirect-in-category">' . $link . '</span>';
265 $this->articles[] = $link;
267 $this->articles_start_char[] = $wgContLang->convert(
268 $this->collation->getFirstLetter( $sortkey ) );
271 function finaliseCategoryState() {
272 if ( $this->flip['subcat'] ) {
273 $this->children = array_reverse( $this->children );
274 $this->children_start_char = array_reverse( $this->children_start_char );
276 if ( $this->flip['page'] ) {
277 $this->articles = array_reverse( $this->articles );
278 $this->articles_start_char = array_reverse( $this->articles_start_char );
280 if ( !$this->showGallery && $this->flip['file'] ) {
281 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
282 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
286 function doCategoryQuery() {
287 $dbr = wfGetDB( DB_SLAVE, 'category' );
289 $this->nextPage = array(
290 'page' => null,
291 'subcat' => null,
292 'file' => null,
294 $this->prevPage = array(
295 'page' => null,
296 'subcat' => null,
297 'file' => null,
300 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
302 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
303 # Get the sortkeys for start/end, if applicable. Note that if
304 # the collation in the database differs from the one
305 # set in $wgCategoryCollation, pagination might go totally haywire.
306 $extraConds = array( 'cl_type' => $type );
307 if ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
308 $extraConds[] = 'cl_sortkey >= '
309 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
310 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
311 $extraConds[] = 'cl_sortkey < '
312 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
313 $this->flip[$type] = true;
316 $res = $dbr->select(
317 array( 'page', 'categorylinks', 'category' ),
318 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
319 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
320 'cat_subcats', 'cat_pages', 'cat_files',
321 'cl_sortkey_prefix', 'cl_collation' ),
322 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
323 __METHOD__,
324 array(
325 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
326 'LIMIT' => $this->limit + 1,
327 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
329 array(
330 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
331 'category' => array( 'LEFT JOIN', array(
332 'cat_title = page_title',
333 'page_namespace' => NS_CATEGORY
338 $count = 0;
339 foreach ( $res as $row ) {
340 $title = Title::newFromRow( $row );
341 if ( $row->cl_collation === '' ) {
342 // Hack to make sure that while updating from 1.16 schema
343 // and db is inconsistent, that the sky doesn't fall.
344 // See r83544. Could perhaps be removed in a couple decades...
345 $humanSortkey = $row->cl_sortkey;
346 } else {
347 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
350 if ( ++$count > $this->limit ) {
351 # We've reached the one extra which shows that there
352 # are additional pages to be had. Stop here...
353 $this->nextPage[$type] = $humanSortkey;
354 break;
356 if ( $count == $this->limit ) {
357 $this->prevPage[$type] = $humanSortkey;
360 if ( $title->getNamespace() == NS_CATEGORY ) {
361 $cat = Category::newFromRow( $row, $title );
362 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
363 } elseif ( $title->getNamespace() == NS_FILE ) {
364 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
365 } else {
366 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
373 * @return string
375 function getCategoryTop() {
376 $r = $this->getCategoryBottom();
377 return $r === ''
378 ? $r
379 : "<br style=\"clear:both;\"/>\n" . $r;
383 * @return string
385 function getSubcategorySection() {
386 # Don't show subcategories section if there are none.
387 $r = '';
388 $rescnt = count( $this->children );
389 $dbcnt = $this->cat->getSubcatCount();
390 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
392 if ( $rescnt > 0 ) {
393 # Showing subcategories
394 $r .= "<div id=\"mw-subcategories\">\n";
395 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
396 $r .= $countmsg;
397 $r .= $this->getSectionPagingLinks( 'subcat' );
398 $r .= $this->formatList( $this->children, $this->children_start_char );
399 $r .= $this->getSectionPagingLinks( 'subcat' );
400 $r .= "\n</div>";
402 return $r;
406 * @return string
408 function getPagesSection() {
409 $ti = wfEscapeWikiText( $this->title->getText() );
410 # Don't show articles section if there are none.
411 $r = '';
413 # @todo FIXME: Here and in the other two sections: we don't need to bother
414 # with this rigmarole if the entire category contents fit on one page
415 # and have already been retrieved. We can just use $rescnt in that
416 # case and save a query and some logic.
417 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
418 - $this->cat->getFileCount();
419 $rescnt = count( $this->articles );
420 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
422 if ( $rescnt > 0 ) {
423 $r = "<div id=\"mw-pages\">\n";
424 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
425 $r .= $countmsg;
426 $r .= $this->getSectionPagingLinks( 'page' );
427 $r .= $this->formatList( $this->articles, $this->articles_start_char );
428 $r .= $this->getSectionPagingLinks( 'page' );
429 $r .= "\n</div>";
431 return $r;
435 * @return string
437 function getImageSection() {
438 $r = '';
439 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
440 if ( $rescnt > 0 ) {
441 $dbcnt = $this->cat->getFileCount();
442 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
444 $r .= "<div id=\"mw-category-media\">\n";
445 $r .= '<h2>' .
446 $this->msg(
447 'category-media-header',
448 wfEscapeWikiText( $this->title->getText() )
449 )->text() .
450 "</h2>\n";
451 $r .= $countmsg;
452 $r .= $this->getSectionPagingLinks( 'file' );
453 if ( $this->showGallery ) {
454 $r .= $this->gallery->toHTML();
455 } else {
456 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
458 $r .= $this->getSectionPagingLinks( 'file' );
459 $r .= "\n</div>";
461 return $r;
465 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
466 * of the output.
468 * @param string $type 'page', 'subcat', or 'file'
469 * @return string HTML output, possibly empty if there are no other pages
471 private function getSectionPagingLinks( $type ) {
472 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
473 // The new value for the until parameter should be pointing to the first
474 // result displayed on the page which is the second last result retrieved
475 // from the database.The next link should have a from parameter pointing
476 // to the until parameter of the current page.
477 if ( $this->nextPage[$type] !== null ) {
478 return $this->pagingLinks( $this->prevPage[$type], $this->until[$type], $type );
479 } else {
480 // If the nextPage variable is null, it means that we have reached the first page
481 // and therefore the previous link should be disabled.
482 return $this->pagingLinks( null, $this->until[$type], $type );
484 } elseif ( $this->nextPage[$type] !== null
485 || ( isset( $this->from[$type] ) && $this->from[$type] !== null )
487 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
488 } else {
489 return '';
494 * @return string
496 function getCategoryBottom() {
497 return '';
501 * Format a list of articles chunked by letter, either as a
502 * bullet list or a columnar format, depending on the length.
504 * @param array $articles
505 * @param array $articles_start_char
506 * @param int $cutoff
507 * @return string
508 * @private
510 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
511 $list = '';
512 if ( count( $articles ) > $cutoff ) {
513 $list = self::columnList( $articles, $articles_start_char );
514 } elseif ( count( $articles ) > 0 ) {
515 // for short lists of articles in categories.
516 $list = self::shortList( $articles, $articles_start_char );
519 $pageLang = $this->title->getPageLanguage();
520 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
521 'class' => 'mw-content-' . $pageLang->getDir() );
522 $list = Html::rawElement( 'div', $attribs, $list );
524 return $list;
528 * Format a list of articles chunked by letter in a three-column
529 * list, ordered vertically.
531 * TODO: Take the headers into account when creating columns, so they're
532 * more visually equal.
534 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
535 * supports those.
537 * @param array $articles
538 * @param string[] $articles_start_char
539 * @return string
540 * @private
542 static function columnList( $articles, $articles_start_char ) {
543 $columns = array_combine( $articles, $articles_start_char );
544 # Split into three columns
545 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
547 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
548 $prevchar = null;
550 foreach ( $columns as $column ) {
551 $ret .= '<td style="width: 33.3%;">';
552 $colContents = array();
554 # Kind of like array_flip() here, but we keep duplicates in an
555 # array instead of dropping them.
556 foreach ( $column as $article => $char ) {
557 if ( !isset( $colContents[$char] ) ) {
558 $colContents[$char] = array();
560 $colContents[$char][] = $article;
563 $first = true;
564 foreach ( $colContents as $char => $articles ) {
565 # Change space to non-breaking space to keep headers aligned
566 $h3char = $char === ' ' ? '&#160;' : htmlspecialchars( $char );
568 $ret .= '<h3>' . $h3char;
569 if ( $first && $char === $prevchar ) {
570 # We're continuing a previous chunk at the top of a new
571 # column, so add " cont." after the letter.
572 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
574 $ret .= "</h3>\n";
576 $ret .= '<ul><li>';
577 $ret .= implode( "</li>\n<li>", $articles );
578 $ret .= '</li></ul>';
580 $first = false;
581 $prevchar = $char;
584 $ret .= "</td>\n";
587 $ret .= '</tr></table>';
588 return $ret;
592 * Format a list of articles chunked by letter in a bullet list.
593 * @param array $articles
594 * @param string[] $articles_start_char
595 * @return string
596 * @private
598 static function shortList( $articles, $articles_start_char ) {
599 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
600 $r .= '<ul><li>' . $articles[0] . '</li>';
601 $articleCount = count( $articles );
602 for ( $index = 1; $index < $articleCount; $index++ ) {
603 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
604 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
607 $r .= "<li>{$articles[$index]}</li>";
609 $r .= '</ul>';
610 return $r;
614 * Create paging links, as a helper method to getSectionPagingLinks().
616 * @param string $first The 'until' parameter for the generated URL
617 * @param string $last The 'from' parameter for the generated URL
618 * @param string $type A prefix for parameters, 'page' or 'subcat' or
619 * 'file'
620 * @return string HTML
622 private function pagingLinks( $first, $last, $type = '' ) {
623 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit )->escaped();
625 if ( $first != '' ) {
626 $prevQuery = $this->query;
627 $prevQuery["{$type}until"] = $first;
628 unset( $prevQuery["{$type}from"] );
629 $prevLink = Linker::linkKnown(
630 $this->addFragmentToTitle( $this->title, $type ),
631 $prevLink,
632 array(),
633 $prevQuery
637 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit )->escaped();
639 if ( $last != '' ) {
640 $lastQuery = $this->query;
641 $lastQuery["{$type}from"] = $last;
642 unset( $lastQuery["{$type}until"] );
643 $nextLink = Linker::linkKnown(
644 $this->addFragmentToTitle( $this->title, $type ),
645 $nextLink,
646 array(),
647 $lastQuery
651 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
655 * Takes a title, and adds the fragment identifier that
656 * corresponds to the correct segment of the category.
658 * @param Title $title The title (usually $this->title)
659 * @param string $section Which section
660 * @throws MWException
661 * @return Title
663 private function addFragmentToTitle( $title, $section ) {
664 switch ( $section ) {
665 case 'page':
666 $fragment = 'mw-pages';
667 break;
668 case 'subcat':
669 $fragment = 'mw-subcategories';
670 break;
671 case 'file':
672 $fragment = 'mw-category-media';
673 break;
674 default:
675 throw new MWException( __METHOD__ .
676 " Invalid section $section." );
679 return Title::makeTitle( $title->getNamespace(),
680 $title->getDBkey(), $fragment );
684 * What to do if the category table conflicts with the number of results
685 * returned? This function says what. Each type is considered independently
686 * of the other types.
688 * @param int $rescnt The number of items returned by our database query.
689 * @param int $dbcnt The number of items according to the category table.
690 * @param string $type 'subcat', 'article', or 'file'
691 * @return string A message giving the number of items, to output to HTML.
693 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-
697 // ery category view.
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';
710 } else {
711 $pagingType = $type;
714 $fromOrUntil = false;
715 if ( ( isset( $this->from[$pagingType] ) && $this->from[$pagingType] !== null ) ||
716 ( isset( $this->until[$pagingType] ) && $this->until[$pagingType] !== null )
718 $fromOrUntil = true;
721 if ( $dbcnt == $rescnt ||
722 ( ( $rescnt == $this->limit || $fromOrUntil ) && $dbcnt > $rescnt )
724 // Case 1: seems sane.
725 $totalcnt = $dbcnt;
726 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
727 // Case 2: not sane, but salvageable. Use the number of results.
728 // Since there are fewer than 200, we can also take this opportunity
729 // to refresh the incorrect category table entry -- which should be
730 // quick due to the small number of entries.
731 $totalcnt = $rescnt;
732 $category = $this->cat;
733 wfGetDB( DB_MASTER )->onTransactionIdle( function () use ( $category ) {
734 $category->refreshCounts();
735 } );
736 } else {
737 // Case 3: hopeless. Don't give a total count at all.
738 // Messages: category-subcat-count-limited, category-article-count-limited,
739 // category-file-count-limited
740 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
742 // Messages: category-subcat-count, category-article-count, category-file-count
743 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();