Merge "Make sure images that don't have an explicit alignment get aligned right"
[mediawiki.git] / includes / CategoryViewer.php
blob49818e6a12e17fe4244a57205d9902d8b76424e8
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 $flip;
60 /** @var Title */
61 protected $title;
63 /** @var Collation */
64 protected $collation;
66 /** @var ImageGallery */
67 protected $gallery;
69 /** @var Category Category object for this page. */
70 private $cat;
72 /** @var array The original query array, to be used in generating paging links. */
73 private $query;
75 /**
76 * @since 1.19 $context is a second, required parameter
77 * @param Title $title
78 * @param IContextSource $context
79 * @param array $from An array with keys page, subcat,
80 * and file for offset of results of each section (since 1.17)
81 * @param array $until An array with 3 keys for until of each section (since 1.17)
82 * @param array $query
84 function __construct( $title, IContextSource $context, $from = array(),
85 $until = array(), $query = array()
86 ) {
87 global $wgCategoryPagingLimit;
88 $this->title = $title;
89 $this->setContext( $context );
90 $this->from = $from;
91 $this->until = $until;
92 $this->limit = $wgCategoryPagingLimit;
93 $this->cat = Category::newFromTitle( $title );
94 $this->query = $query;
95 $this->collation = Collation::singleton();
96 unset( $this->query['title'] );
99 /**
100 * Format the category data list.
102 * @return string HTML output
104 public function getHTML() {
105 global $wgCategoryMagicGallery;
106 wfProfileIn( __METHOD__ );
108 $this->showGallery = $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery;
110 $this->clearCategoryState();
111 $this->doCategoryQuery();
112 $this->finaliseCategoryState();
114 $r = $this->getSubcategorySection() .
115 $this->getPagesSection() .
116 $this->getImageSection();
118 if ( $r == '' ) {
119 // If there is no category content to display, only
120 // show the top part of the navigation links.
121 // @todo FIXME: Cannot be completely suppressed because it
122 // is unknown if 'until' or 'from' makes this
123 // give 0 results.
124 $r = $r . $this->getCategoryTop();
125 } else {
126 $r = $this->getCategoryTop() .
127 $r .
128 $this->getCategoryBottom();
131 // Give a proper message if category is empty
132 if ( $r == '' ) {
133 $r = $this->msg( 'category-empty' )->parseAsBlock();
136 $lang = $this->getLanguage();
137 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
138 # put a div around the headings which are in the user language
139 $r = Html::openElement( 'div', $langAttribs ) . $r . '</div>';
141 wfProfileOut( __METHOD__ );
142 return $r;
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 );
153 try {
154 $this->gallery = ImageGalleryBase::factory( $mode );
155 } catch ( MWException $e ) {
156 // User specified something invalid, fallback to default.
157 $this->gallery = ImageGalleryBase::factory();
160 $this->gallery->setHideBadImages();
161 $this->gallery->setContext( $this->getContext() );
162 } else {
163 $this->imgsNoGallery = array();
164 $this->imgsNoGallery_start_char = array();
169 * Add a subcategory to the internal lists, using a Category object
170 * @param Category $cat
171 * @param string $sortkey
172 * @param int $pageLength
174 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
175 // Subcategory; strip the 'Category' namespace from the link text.
176 $title = $cat->getTitle();
178 $link = Linker::link( $title, htmlspecialchars( $title->getText() ) );
179 if ( $title->isRedirect() ) {
180 // This didn't used to add redirect-in-category, but might
181 // as well be consistent with the rest of the sections
182 // on a category page.
183 $link = '<span class="redirect-in-category">' . $link . '</span>';
185 $this->children[] = $link;
187 $this->children_start_char[] =
188 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
192 * Get the character to be used for sorting subcategories.
193 * If there's a link from Category:A to Category:B, the sortkey of the resulting
194 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
195 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
196 * else use sortkey...
198 * @param Title $title
199 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
200 * @return string
202 function getSubcategorySortChar( $title, $sortkey ) {
203 global $wgContLang;
205 if ( $title->getPrefixedText() == $sortkey ) {
206 $word = $title->getDBkey();
207 } else {
208 $word = $sortkey;
211 $firstChar = $this->collation->getFirstLetter( $word );
213 return $wgContLang->convert( $firstChar );
217 * Add a page in the image namespace
218 * @param Title $title
219 * @param string $sortkey
220 * @param int $pageLength
221 * @param bool $isRedirect
223 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
224 global $wgContLang;
225 if ( $this->showGallery ) {
226 $flip = $this->flip['file'];
227 if ( $flip ) {
228 $this->gallery->insert( $title );
229 } else {
230 $this->gallery->add( $title );
232 } else {
233 $link = Linker::link( $title );
234 if ( $isRedirect ) {
235 // This seems kind of pointless given 'mw-redirect' class,
236 // but keeping for back-compatibility with user css.
237 $link = '<span class="redirect-in-category">' . $link . '</span>';
239 $this->imgsNoGallery[] = $link;
241 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
242 $this->collation->getFirstLetter( $sortkey ) );
247 * Add a miscellaneous page
248 * @param Title $title
249 * @param string $sortkey
250 * @param int $pageLength
251 * @param bool $isRedirect
253 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
254 global $wgContLang;
256 $link = Linker::link( $title );
257 if ( $isRedirect ) {
258 // This seems kind of pointless given 'mw-redirect' class,
259 // but keeping for back-compatibility with user css.
260 $link = '<span class="redirect-in-category">' . $link . '</span>';
262 $this->articles[] = $link;
264 $this->articles_start_char[] = $wgContLang->convert(
265 $this->collation->getFirstLetter( $sortkey ) );
268 function finaliseCategoryState() {
269 if ( $this->flip['subcat'] ) {
270 $this->children = array_reverse( $this->children );
271 $this->children_start_char = array_reverse( $this->children_start_char );
273 if ( $this->flip['page'] ) {
274 $this->articles = array_reverse( $this->articles );
275 $this->articles_start_char = array_reverse( $this->articles_start_char );
277 if ( !$this->showGallery && $this->flip['file'] ) {
278 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
279 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
283 function doCategoryQuery() {
284 $dbr = wfGetDB( DB_SLAVE, 'category' );
286 $this->nextPage = array(
287 'page' => null,
288 'subcat' => null,
289 'file' => null,
291 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
293 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
294 # Get the sortkeys for start/end, if applicable. Note that if
295 # the collation in the database differs from the one
296 # set in $wgCategoryCollation, pagination might go totally haywire.
297 $extraConds = array( 'cl_type' => $type );
298 if ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
299 $extraConds[] = 'cl_sortkey >= '
300 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
301 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
302 $extraConds[] = 'cl_sortkey < '
303 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
304 $this->flip[$type] = true;
307 $res = $dbr->select(
308 array( 'page', 'categorylinks', 'category' ),
309 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
310 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
311 'cat_subcats', 'cat_pages', 'cat_files',
312 'cl_sortkey_prefix', 'cl_collation' ),
313 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
314 __METHOD__,
315 array(
316 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
317 'LIMIT' => $this->limit + 1,
318 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
320 array(
321 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
322 'category' => array( 'LEFT JOIN', array(
323 'cat_title = page_title',
324 'page_namespace' => NS_CATEGORY
329 $count = 0;
330 foreach ( $res as $row ) {
331 $title = Title::newFromRow( $row );
332 if ( $row->cl_collation === '' ) {
333 // Hack to make sure that while updating from 1.16 schema
334 // and db is inconsistent, that the sky doesn't fall.
335 // See r83544. Could perhaps be removed in a couple decades...
336 $humanSortkey = $row->cl_sortkey;
337 } else {
338 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
341 if ( ++$count > $this->limit ) {
342 # We've reached the one extra which shows that there
343 # are additional pages to be had. Stop here...
344 $this->nextPage[$type] = $humanSortkey;
345 break;
348 if ( $title->getNamespace() == NS_CATEGORY ) {
349 $cat = Category::newFromRow( $row, $title );
350 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
351 } elseif ( $title->getNamespace() == NS_FILE ) {
352 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
353 } else {
354 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
361 * @return string
363 function getCategoryTop() {
364 $r = $this->getCategoryBottom();
365 return $r === ''
366 ? $r
367 : "<br style=\"clear:both;\"/>\n" . $r;
371 * @return string
373 function getSubcategorySection() {
374 # Don't show subcategories section if there are none.
375 $r = '';
376 $rescnt = count( $this->children );
377 $dbcnt = $this->cat->getSubcatCount();
378 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
380 if ( $rescnt > 0 ) {
381 # Showing subcategories
382 $r .= "<div id=\"mw-subcategories\">\n";
383 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
384 $r .= $countmsg;
385 $r .= $this->getSectionPagingLinks( 'subcat' );
386 $r .= $this->formatList( $this->children, $this->children_start_char );
387 $r .= $this->getSectionPagingLinks( 'subcat' );
388 $r .= "\n</div>";
390 return $r;
394 * @return string
396 function getPagesSection() {
397 $ti = wfEscapeWikiText( $this->title->getText() );
398 # Don't show articles section if there are none.
399 $r = '';
401 # @todo FIXME: Here and in the other two sections: we don't need to bother
402 # with this rigmarole if the entire category contents fit on one page
403 # and have already been retrieved. We can just use $rescnt in that
404 # case and save a query and some logic.
405 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
406 - $this->cat->getFileCount();
407 $rescnt = count( $this->articles );
408 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
410 if ( $rescnt > 0 ) {
411 $r = "<div id=\"mw-pages\">\n";
412 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
413 $r .= $countmsg;
414 $r .= $this->getSectionPagingLinks( 'page' );
415 $r .= $this->formatList( $this->articles, $this->articles_start_char );
416 $r .= $this->getSectionPagingLinks( 'page' );
417 $r .= "\n</div>";
419 return $r;
423 * @return string
425 function getImageSection() {
426 $r = '';
427 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
428 if ( $rescnt > 0 ) {
429 $dbcnt = $this->cat->getFileCount();
430 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
432 $r .= "<div id=\"mw-category-media\">\n";
433 $r .= '<h2>' .
434 $this->msg(
435 'category-media-header',
436 wfEscapeWikiText( $this->title->getText() )
437 )->text() .
438 "</h2>\n";
439 $r .= $countmsg;
440 $r .= $this->getSectionPagingLinks( 'file' );
441 if ( $this->showGallery ) {
442 $r .= $this->gallery->toHTML();
443 } else {
444 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
446 $r .= $this->getSectionPagingLinks( 'file' );
447 $r .= "\n</div>";
449 return $r;
453 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
454 * of the output.
456 * @param string $type 'page', 'subcat', or 'file'
457 * @return string HTML output, possibly empty if there are no other pages
459 private function getSectionPagingLinks( $type ) {
460 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
461 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
462 } elseif ( $this->nextPage[$type] !== null
463 || ( isset( $this->from[$type] ) && $this->from[$type] !== null )
465 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
466 } else {
467 return '';
472 * @return string
474 function getCategoryBottom() {
475 return '';
479 * Format a list of articles chunked by letter, either as a
480 * bullet list or a columnar format, depending on the length.
482 * @param array $articles
483 * @param array $articles_start_char
484 * @param int $cutoff
485 * @return string
486 * @private
488 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
489 $list = '';
490 if ( count( $articles ) > $cutoff ) {
491 $list = self::columnList( $articles, $articles_start_char );
492 } elseif ( count( $articles ) > 0 ) {
493 // for short lists of articles in categories.
494 $list = self::shortList( $articles, $articles_start_char );
497 $pageLang = $this->title->getPageLanguage();
498 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
499 'class' => 'mw-content-' . $pageLang->getDir() );
500 $list = Html::rawElement( 'div', $attribs, $list );
502 return $list;
506 * Format a list of articles chunked by letter in a three-column
507 * list, ordered vertically.
509 * TODO: Take the headers into account when creating columns, so they're
510 * more visually equal.
512 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
513 * supports those.
515 * @param array $articles
516 * @param string[] $articles_start_char
517 * @return string
518 * @private
520 static function columnList( $articles, $articles_start_char ) {
521 $columns = array_combine( $articles, $articles_start_char );
522 # Split into three columns
523 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
525 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
526 $prevchar = null;
528 foreach ( $columns as $column ) {
529 $ret .= '<td style="width: 33.3%;">';
530 $colContents = array();
532 # Kind of like array_flip() here, but we keep duplicates in an
533 # array instead of dropping them.
534 foreach ( $column as $article => $char ) {
535 if ( !isset( $colContents[$char] ) ) {
536 $colContents[$char] = array();
538 $colContents[$char][] = $article;
541 $first = true;
542 foreach ( $colContents as $char => $articles ) {
543 # Change space to non-breaking space to keep headers aligned
544 $h3char = $char === ' ' ? '&#160;' : htmlspecialchars( $char );
546 $ret .= '<h3>' . $h3char;
547 if ( $first && $char === $prevchar ) {
548 # We're continuing a previous chunk at the top of a new
549 # column, so add " cont." after the letter.
550 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
552 $ret .= "</h3>\n";
554 $ret .= '<ul><li>';
555 $ret .= implode( "</li>\n<li>", $articles );
556 $ret .= '</li></ul>';
558 $first = false;
559 $prevchar = $char;
562 $ret .= "</td>\n";
565 $ret .= '</tr></table>';
566 return $ret;
570 * Format a list of articles chunked by letter in a bullet list.
571 * @param array $articles
572 * @param string[] $articles_start_char
573 * @return string
574 * @private
576 static function shortList( $articles, $articles_start_char ) {
577 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
578 $r .= '<ul><li>' . $articles[0] . '</li>';
579 $articleCount = count( $articles );
580 for ( $index = 1; $index < $articleCount; $index++ ) {
581 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
582 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
585 $r .= "<li>{$articles[$index]}</li>";
587 $r .= '</ul>';
588 return $r;
592 * Create paging links, as a helper method to getSectionPagingLinks().
594 * @param string $first The 'until' parameter for the generated URL
595 * @param string $last The 'from' parameter for the generated URL
596 * @param string $type A prefix for parameters, 'page' or 'subcat' or
597 * 'file'
598 * @return string HTML
600 private function pagingLinks( $first, $last, $type = '' ) {
601 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit )->escaped();
603 if ( $first != '' ) {
604 $prevQuery = $this->query;
605 $prevQuery["{$type}until"] = $first;
606 unset( $prevQuery["{$type}from"] );
607 $prevLink = Linker::linkKnown(
608 $this->addFragmentToTitle( $this->title, $type ),
609 $prevLink,
610 array(),
611 $prevQuery
615 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit )->escaped();
617 if ( $last != '' ) {
618 $lastQuery = $this->query;
619 $lastQuery["{$type}from"] = $last;
620 unset( $lastQuery["{$type}until"] );
621 $nextLink = Linker::linkKnown(
622 $this->addFragmentToTitle( $this->title, $type ),
623 $nextLink,
624 array(),
625 $lastQuery
629 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
633 * Takes a title, and adds the fragment identifier that
634 * corresponds to the correct segment of the category.
636 * @param Title $title The title (usually $this->title)
637 * @param string $section Which section
638 * @throws MWException
639 * @return Title
641 private function addFragmentToTitle( $title, $section ) {
642 switch ( $section ) {
643 case 'page':
644 $fragment = 'mw-pages';
645 break;
646 case 'subcat':
647 $fragment = 'mw-subcategories';
648 break;
649 case 'file':
650 $fragment = 'mw-category-media';
651 break;
652 default:
653 throw new MWException( __METHOD__ .
654 " Invalid section $section." );
657 return Title::makeTitle( $title->getNamespace(),
658 $title->getDBkey(), $fragment );
662 * What to do if the category table conflicts with the number of results
663 * returned? This function says what. Each type is considered independently
664 * of the other types.
666 * @param int $rescnt The number of items returned by our database query.
667 * @param int $dbcnt The number of items according to the category table.
668 * @param string $type 'subcat', 'article', or 'file'
669 * @return string A message giving the number of items, to output to HTML.
671 private function getCountMessage( $rescnt, $dbcnt, $type ) {
672 // There are three cases:
673 // 1) The category table figure seems sane. It might be wrong, but
674 // we can't do anything about it if we don't recalculate it on ev-
675 // ery category view.
676 // 2) The category table figure isn't sane, like it's smaller than the
677 // number of actual results, *but* the number of results is less
678 // than $this->limit and there's no offset. In this case we still
679 // know the right figure.
680 // 3) We have no idea.
682 // Check if there's a "from" or "until" for anything
684 // This is a little ugly, but we seem to use different names
685 // for the paging types then for the messages.
686 if ( $type === 'article' ) {
687 $pagingType = 'page';
688 } else {
689 $pagingType = $type;
692 $fromOrUntil = false;
693 if ( ( isset( $this->from[$pagingType] ) && $this->from[$pagingType] !== null ) ||
694 ( isset( $this->until[$pagingType] ) && $this->until[$pagingType] !== null )
696 $fromOrUntil = true;
699 if ( $dbcnt == $rescnt ||
700 ( ( $rescnt == $this->limit || $fromOrUntil ) && $dbcnt > $rescnt )
702 // Case 1: seems sane.
703 $totalcnt = $dbcnt;
704 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
705 // Case 2: not sane, but salvageable. Use the number of results.
706 // Since there are fewer than 200, we can also take this opportunity
707 // to refresh the incorrect category table entry -- which should be
708 // quick due to the small number of entries.
709 $totalcnt = $rescnt;
710 $this->cat->refreshCounts();
711 } else {
712 // Case 3: hopeless. Don't give a total count at all.
713 // Messages: category-subcat-count-limited, category-article-count-limited,
714 // category-file-count-limited
715 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
717 // Messages: category-subcat-count, category-article-count, category-file-count
718 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();