Remove useless comments from search output
[mediawiki.git] / includes / CategoryViewer.php
blob7f213c352c1244173959f6bdfcae509c42016da9
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 $limit, $from, $until,
25 $articles, $articles_start_char,
26 $children, $children_start_char,
27 $showGallery, $imgsNoGalley,
28 $imgsNoGallery_start_char,
29 $imgsNoGallery;
31 /**
32 * @var Array
34 var $nextPage;
36 /**
37 * @var Array
39 var $flip;
41 /**
42 * @var Title
44 var $title;
46 /**
47 * @var Collation
49 var $collation;
51 /**
52 * @var ImageGallery
54 var $gallery;
56 /**
57 * Category object for this page
58 * @var Category
60 private $cat;
62 /**
63 * The original query array, to be used in generating paging links.
64 * @var array
66 private $query;
68 /**
69 * Constructor
71 * @since 1.19 $context is a second, required parameter
72 * @param $title Title
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)
77 * @param $query Array
79 function __construct( $title, IContextSource $context, $from = array(),
80 $until = array(), $query = array()
81 ) {
82 global $wgCategoryPagingLimit;
83 $this->title = $title;
84 $this->setContext( $context );
85 $this->from = $from;
86 $this->until = $until;
87 $this->limit = $wgCategoryPagingLimit;
88 $this->cat = Category::newFromTitle( $title );
89 $this->query = $query;
90 $this->collation = Collation::singleton();
91 unset( $this->query['title'] );
94 /**
95 * Format the category data list.
97 * @return string HTML output
99 public function getHTML() {
100 global $wgCategoryMagicGallery;
101 wfProfileIn( __METHOD__ );
103 $this->showGallery = $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery;
105 $this->clearCategoryState();
106 $this->doCategoryQuery();
107 $this->finaliseCategoryState();
109 $r = $this->getSubcategorySection() .
110 $this->getPagesSection() .
111 $this->getImageSection();
113 if ( $r == '' ) {
114 // If there is no category content to display, only
115 // show the top part of the navigation links.
116 // @todo FIXME: Cannot be completely suppressed because it
117 // is unknown if 'until' or 'from' makes this
118 // give 0 results.
119 $r = $r . $this->getCategoryTop();
120 } else {
121 $r = $this->getCategoryTop() .
122 $r .
123 $this->getCategoryBottom();
126 // Give a proper message if category is empty
127 if ( $r == '' ) {
128 $r = $this->msg( 'category-empty' )->parseAsBlock();
131 $lang = $this->getLanguage();
132 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
133 # put a div around the headings which are in the user language
134 $r = Html::openElement( 'div', $langAttribs ) . $r . '</div>';
136 wfProfileOut( __METHOD__ );
137 return $r;
140 function clearCategoryState() {
141 $this->articles = array();
142 $this->articles_start_char = array();
143 $this->children = array();
144 $this->children_start_char = array();
145 if ( $this->showGallery ) {
146 // Note that null for mode is taken to mean use default.
147 $mode = $this->getRequest()->getVal( 'gallerymode', null );
148 try {
149 $this->gallery = ImageGalleryBase::factory( $mode );
150 } catch ( MWException $e ) {
151 // User specified something invalid, fallback to default.
152 $this->gallery = ImageGalleryBase::factory();
155 $this->gallery->setHideBadImages();
156 $this->gallery->setContext( $this->getContext() );
157 } else {
158 $this->imgsNoGallery = array();
159 $this->imgsNoGallery_start_char = array();
164 * Add a subcategory to the internal lists, using a Category object
165 * @param $cat Category
166 * @param $sortkey
167 * @param $pageLength
169 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
170 // Subcategory; strip the 'Category' namespace from the link text.
171 $title = $cat->getTitle();
173 $link = Linker::link( $title, htmlspecialchars( $title->getText() ) );
174 if ( $title->isRedirect() ) {
175 // This didn't used to add redirect-in-category, but might
176 // as well be consistent with the rest of the sections
177 // on a category page.
178 $link = '<span class="redirect-in-category">' . $link . '</span>';
180 $this->children[] = $link;
182 $this->children_start_char[] =
183 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
187 * Get the character to be used for sorting subcategories.
188 * If there's a link from Category:A to Category:B, the sortkey of the resulting
189 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
190 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
191 * else use sortkey...
193 * @param Title $title
194 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
195 * @return string
197 function getSubcategorySortChar( $title, $sortkey ) {
198 global $wgContLang;
200 if ( $title->getPrefixedText() == $sortkey ) {
201 $word = $title->getDBkey();
202 } else {
203 $word = $sortkey;
206 $firstChar = $this->collation->getFirstLetter( $word );
208 return $wgContLang->convert( $firstChar );
212 * Add a page in the image namespace
213 * @param $title Title
214 * @param $sortkey
215 * @param $pageLength
216 * @param $isRedirect bool
218 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
219 global $wgContLang;
220 if ( $this->showGallery ) {
221 $flip = $this->flip['file'];
222 if ( $flip ) {
223 $this->gallery->insert( $title );
224 } else {
225 $this->gallery->add( $title );
227 } else {
228 $link = Linker::link( $title );
229 if ( $isRedirect ) {
230 // This seems kind of pointless given 'mw-redirect' class,
231 // but keeping for back-compatibility with user css.
232 $link = '<span class="redirect-in-category">' . $link . '</span>';
234 $this->imgsNoGallery[] = $link;
236 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
237 $this->collation->getFirstLetter( $sortkey ) );
242 * Add a miscellaneous page
243 * @param $title
244 * @param $sortkey
245 * @param $pageLength
246 * @param $isRedirect bool
248 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
249 global $wgContLang;
251 $link = Linker::link( $title );
252 if ( $isRedirect ) {
253 // This seems kind of pointless given 'mw-redirect' class,
254 // but keeping for back-compatibility with user css.
255 $link = '<span class="redirect-in-category">' . $link . '</span>';
257 $this->articles[] = $link;
259 $this->articles_start_char[] = $wgContLang->convert(
260 $this->collation->getFirstLetter( $sortkey ) );
263 function finaliseCategoryState() {
264 if ( $this->flip['subcat'] ) {
265 $this->children = array_reverse( $this->children );
266 $this->children_start_char = array_reverse( $this->children_start_char );
268 if ( $this->flip['page'] ) {
269 $this->articles = array_reverse( $this->articles );
270 $this->articles_start_char = array_reverse( $this->articles_start_char );
272 if ( !$this->showGallery && $this->flip['file'] ) {
273 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
274 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
278 function doCategoryQuery() {
279 $dbr = wfGetDB( DB_SLAVE, 'category' );
281 $this->nextPage = array(
282 'page' => null,
283 'subcat' => null,
284 'file' => null,
286 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
288 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
289 # Get the sortkeys for start/end, if applicable. Note that if
290 # the collation in the database differs from the one
291 # set in $wgCategoryCollation, pagination might go totally haywire.
292 $extraConds = array( 'cl_type' => $type );
293 if ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
294 $extraConds[] = 'cl_sortkey >= '
295 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
296 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
297 $extraConds[] = 'cl_sortkey < '
298 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
299 $this->flip[$type] = true;
302 $res = $dbr->select(
303 array( 'page', 'categorylinks', 'category' ),
304 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
305 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
306 'cat_subcats', 'cat_pages', 'cat_files',
307 'cl_sortkey_prefix', 'cl_collation' ),
308 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
309 __METHOD__,
310 array(
311 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
312 'LIMIT' => $this->limit + 1,
313 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
315 array(
316 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
317 'category' => array( 'LEFT JOIN', array(
318 'cat_title = page_title',
319 'page_namespace' => NS_CATEGORY
324 $count = 0;
325 foreach ( $res as $row ) {
326 $title = Title::newFromRow( $row );
327 if ( $row->cl_collation === '' ) {
328 // Hack to make sure that while updating from 1.16 schema
329 // and db is inconsistent, that the sky doesn't fall.
330 // See r83544. Could perhaps be removed in a couple decades...
331 $humanSortkey = $row->cl_sortkey;
332 } else {
333 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
336 if ( ++$count > $this->limit ) {
337 # We've reached the one extra which shows that there
338 # are additional pages to be had. Stop here...
339 $this->nextPage[$type] = $humanSortkey;
340 break;
343 if ( $title->getNamespace() == NS_CATEGORY ) {
344 $cat = Category::newFromRow( $row, $title );
345 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
346 } elseif ( $title->getNamespace() == NS_FILE ) {
347 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
348 } else {
349 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
356 * @return string
358 function getCategoryTop() {
359 $r = $this->getCategoryBottom();
360 return $r === ''
361 ? $r
362 : "<br style=\"clear:both;\"/>\n" . $r;
366 * @return string
368 function getSubcategorySection() {
369 # Don't show subcategories section if there are none.
370 $r = '';
371 $rescnt = count( $this->children );
372 $dbcnt = $this->cat->getSubcatCount();
373 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
375 if ( $rescnt > 0 ) {
376 # Showing subcategories
377 $r .= "<div id=\"mw-subcategories\">\n";
378 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
379 $r .= $countmsg;
380 $r .= $this->getSectionPagingLinks( 'subcat' );
381 $r .= $this->formatList( $this->children, $this->children_start_char );
382 $r .= $this->getSectionPagingLinks( 'subcat' );
383 $r .= "\n</div>";
385 return $r;
389 * @return string
391 function getPagesSection() {
392 $ti = wfEscapeWikiText( $this->title->getText() );
393 # Don't show articles section if there are none.
394 $r = '';
396 # @todo FIXME: Here and in the other two sections: we don't need to bother
397 # with this rigmarole if the entire category contents fit on one page
398 # and have already been retrieved. We can just use $rescnt in that
399 # case and save a query and some logic.
400 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
401 - $this->cat->getFileCount();
402 $rescnt = count( $this->articles );
403 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
405 if ( $rescnt > 0 ) {
406 $r = "<div id=\"mw-pages\">\n";
407 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
408 $r .= $countmsg;
409 $r .= $this->getSectionPagingLinks( 'page' );
410 $r .= $this->formatList( $this->articles, $this->articles_start_char );
411 $r .= $this->getSectionPagingLinks( 'page' );
412 $r .= "\n</div>";
414 return $r;
418 * @return string
420 function getImageSection() {
421 $r = '';
422 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
423 if ( $rescnt > 0 ) {
424 $dbcnt = $this->cat->getFileCount();
425 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
427 $r .= "<div id=\"mw-category-media\">\n";
428 $r .= '<h2>' .
429 $this->msg(
430 'category-media-header',
431 wfEscapeWikiText( $this->title->getText() )
432 )->text() .
433 "</h2>\n";
434 $r .= $countmsg;
435 $r .= $this->getSectionPagingLinks( 'file' );
436 if ( $this->showGallery ) {
437 $r .= $this->gallery->toHTML();
438 } else {
439 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
441 $r .= $this->getSectionPagingLinks( 'file' );
442 $r .= "\n</div>";
444 return $r;
448 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
449 * of the output.
451 * @param string $type 'page', 'subcat', or 'file'
452 * @return string HTML output, possibly empty if there are no other pages
454 private function getSectionPagingLinks( $type ) {
455 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
456 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
457 } elseif ( $this->nextPage[$type] !== null
458 || ( isset( $this->from[$type] ) && $this->from[$type] !== null )
460 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
461 } else {
462 return '';
467 * @return string
469 function getCategoryBottom() {
470 return '';
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
479 * @param $cutoff Int
480 * @return String
481 * @private
483 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
484 $list = '';
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 );
497 return $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
508 * supports those.
510 * @param $articles Array
511 * @param $articles_start_char Array
512 * @return String
513 * @private
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;">';
521 $prevchar = null;
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;
536 $first = true;
537 foreach ( $colContents as $char => $articles ) {
538 # Change space to non-breaking space to keep headers aligned
539 $h3char = $char === ' ' ? '&#160;' : 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();
547 $ret .= "</h3>\n";
549 $ret .= '<ul><li>';
550 $ret .= implode( "</li>\n<li>", $articles );
551 $ret .= '</li></ul>';
553 $first = false;
554 $prevchar = $char;
557 $ret .= "</td>\n";
560 $ret .= '</tr></table>';
561 return $ret;
565 * Format a list of articles chunked by letter in a bullet list.
566 * @param $articles Array
567 * @param $articles_start_char Array
568 * @return String
569 * @private
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 $articleCount = count( $articles );
575 for ( $index = 1; $index < $articleCount; $index++ ) {
576 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
577 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
580 $r .= "<li>{$articles[$index]}</li>";
582 $r .= '</ul>';
583 return $r;
587 * Create paging links, as a helper method to getSectionPagingLinks().
589 * @param string $first The 'until' parameter for the generated URL
590 * @param string $last The 'from' parameter for the generated URL
591 * @param string $type A prefix for parameters, 'page' or 'subcat' or
592 * 'file'
593 * @return String HTML
595 private function pagingLinks( $first, $last, $type = '' ) {
596 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit )->escaped();
598 if ( $first != '' ) {
599 $prevQuery = $this->query;
600 $prevQuery["{$type}until"] = $first;
601 unset( $prevQuery["{$type}from"] );
602 $prevLink = Linker::linkKnown(
603 $this->addFragmentToTitle( $this->title, $type ),
604 $prevLink,
605 array(),
606 $prevQuery
610 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit )->escaped();
612 if ( $last != '' ) {
613 $lastQuery = $this->query;
614 $lastQuery["{$type}from"] = $last;
615 unset( $lastQuery["{$type}until"] );
616 $nextLink = Linker::linkKnown(
617 $this->addFragmentToTitle( $this->title, $type ),
618 $nextLink,
619 array(),
620 $lastQuery
624 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
628 * Takes a title, and adds the fragment identifier that
629 * corresponds to the correct segment of the category.
631 * @param Title $title The title (usually $this->title)
632 * @param string $section Which section
633 * @throws MWException
634 * @return Title
636 private function addFragmentToTitle( $title, $section ) {
637 switch ( $section ) {
638 case 'page':
639 $fragment = 'mw-pages';
640 break;
641 case 'subcat':
642 $fragment = 'mw-subcategories';
643 break;
644 case 'file':
645 $fragment = 'mw-category-media';
646 break;
647 default:
648 throw new MWException( __METHOD__ .
649 " Invalid section $section." );
652 return Title::makeTitle( $title->getNamespace(),
653 $title->getDBkey(), $fragment );
657 * What to do if the category table conflicts with the number of results
658 * returned? This function says what. Each type is considered independently
659 * of the other types.
661 * @param int $rescnt The number of items returned by our database query.
662 * @param int $dbcnt The number of items according to the category table.
663 * @param string $type 'subcat', 'article', or 'file'
664 * @return string A message giving the number of items, to output to HTML.
666 private function getCountMessage( $rescnt, $dbcnt, $type ) {
667 // There are three cases:
668 // 1) The category table figure seems sane. It might be wrong, but
669 // we can't do anything about it if we don't recalculate it on ev-
670 // ery category view.
671 // 2) The category table figure isn't sane, like it's smaller than the
672 // number of actual results, *but* the number of results is less
673 // than $this->limit and there's no offset. In this case we still
674 // know the right figure.
675 // 3) We have no idea.
677 // Check if there's a "from" or "until" for anything
679 // This is a little ugly, but we seem to use different names
680 // for the paging types then for the messages.
681 if ( $type === 'article' ) {
682 $pagingType = 'page';
683 } else {
684 $pagingType = $type;
687 $fromOrUntil = false;
688 if ( ( isset( $this->from[$pagingType] ) && $this->from[$pagingType] !== null ) ||
689 ( isset( $this->until[$pagingType] ) && $this->until[$pagingType] !== null )
691 $fromOrUntil = true;
694 if ( $dbcnt == $rescnt ||
695 ( ( $rescnt == $this->limit || $fromOrUntil ) && $dbcnt > $rescnt )
697 // Case 1: seems sane.
698 $totalcnt = $dbcnt;
699 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
700 // Case 2: not sane, but salvageable. Use the number of results.
701 // Since there are fewer than 200, we can also take this opportunity
702 // to refresh the incorrect category table entry -- which should be
703 // quick due to the small number of entries.
704 $totalcnt = $rescnt;
705 $this->cat->refreshCounts();
706 } else {
707 // Case 3: hopeless. Don't give a total count at all.
708 // Messages: category-subcat-count-limited, category-article-count-limited,
709 // category-file-count-limited
710 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
712 // Messages: category-subcat-count, category-article-count, category-file-count
713 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();