Bug 33514 - Make category "columns" (table cells) equal width
[lhc/web/wiklou.git] / includes / CategoryViewer.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) )
4 die( 1 );
5
6 class CategoryViewer extends ContextSource {
7 var $limit, $from, $until,
8 $articles, $articles_start_char,
9 $children, $children_start_char,
10 $showGallery, $imgsNoGalley,
11 $imgsNoGallery_start_char,
12 $imgsNoGallery;
13
14 /**
15 * @var
16 */
17 var $nextPage;
18
19 /**
20 * @var Array
21 */
22 var $flip;
23
24 /**
25 * @var Title
26 */
27 var $title;
28
29 /**
30 * @var Collation
31 */
32 var $collation;
33
34 /**
35 * @var ImageGallery
36 */
37 var $gallery;
38
39 /**
40 * Category object for this page
41 * @var Category
42 */
43 private $cat;
44
45 /**
46 * The original query array, to be used in generating paging links.
47 * @var array
48 */
49 private $query;
50
51 /**
52 * Constructor
53 *
54 * @since 1.19 $context is a second, required parameter
55 * @param $title Title
56 * @param $context IContextSource
57 * @param $from String
58 * @param $until String
59 * @param $query Array
60 */
61 function __construct( $title, IContextSource $context, $from = '', $until = '', $query = array() ) {
62 global $wgCategoryPagingLimit;
63 $this->title = $title;
64 $this->setContext( $context );
65 $this->from = $from;
66 $this->until = $until;
67 $this->limit = $wgCategoryPagingLimit;
68 $this->cat = Category::newFromTitle( $title );
69 $this->query = $query;
70 $this->collation = Collation::singleton();
71 unset( $this->query['title'] );
72 }
73
74 /**
75 * Format the category data list.
76 *
77 * @return string HTML output
78 */
79 public function getHTML() {
80 global $wgCategoryMagicGallery;
81 wfProfileIn( __METHOD__ );
82
83 $this->showGallery = $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery;
84
85 $this->clearCategoryState();
86 $this->doCategoryQuery();
87 $this->finaliseCategoryState();
88
89 $r = $this->getSubcategorySection() .
90 $this->getPagesSection() .
91 $this->getImageSection();
92
93 if ( $r == '' ) {
94 // If there is no category content to display, only
95 // show the top part of the navigation links.
96 // @todo FIXME: Cannot be completely suppressed because it
97 // is unknown if 'until' or 'from' makes this
98 // give 0 results.
99 $r = $r . $this->getCategoryTop();
100 } else {
101 $r = $this->getCategoryTop() .
102 $r .
103 $this->getCategoryBottom();
104 }
105
106 // Give a proper message if category is empty
107 if ( $r == '' ) {
108 $r = wfMsgExt( 'category-empty', array( 'parse' ) );
109 }
110
111 $lang = $this->getLanguage();
112 $langAttribs = array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() );
113 # put a div around the headings which are in the user language
114 $r = Html::openElement( 'div', $langAttribs ) . $r . '</div>';
115
116 wfProfileOut( __METHOD__ );
117 return $r;
118 }
119
120 function clearCategoryState() {
121 $this->articles = array();
122 $this->articles_start_char = array();
123 $this->children = array();
124 $this->children_start_char = array();
125 if ( $this->showGallery ) {
126 $this->gallery = new ImageGallery();
127 $this->gallery->setHideBadImages();
128 } else {
129 $this->imgsNoGallery = array();
130 $this->imgsNoGallery_start_char = array();
131 }
132 }
133
134 /**
135 * Add a subcategory to the internal lists, using a Category object
136 * @param $cat Category
137 * @param $sortkey
138 * @param $pageLength
139 */
140 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
141 // Subcategory; strip the 'Category' namespace from the link text.
142 $title = $cat->getTitle();
143
144 $link = Linker::link( $title, htmlspecialchars( $title->getText() ) );
145 if ( $title->isRedirect() ) {
146 // This didn't used to add redirect-in-category, but might
147 // as well be consistent with the rest of the sections
148 // on a category page.
149 $link = '<span class="redirect-in-category">' . $link . '</span>';
150 }
151 $this->children[] = $link;
152
153 $this->children_start_char[] =
154 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
155 }
156
157 /**
158 * Add a subcategory to the internal lists, using a title object
159 * @deprecated since 1.17 kept for compatibility, please use addSubcategoryObject instead
160 */
161 function addSubcategory( Title $title, $sortkey, $pageLength ) {
162 wfDeprecated( __METHOD__, '1.17' );
163 $this->addSubcategoryObject( Category::newFromTitle( $title ), $sortkey, $pageLength );
164 }
165
166 /**
167 * Get the character to be used for sorting subcategories.
168 * If there's a link from Category:A to Category:B, the sortkey of the resulting
169 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
170 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
171 * else use sortkey...
172 *
173 * @param Title $title
174 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
175 */
176 function getSubcategorySortChar( $title, $sortkey ) {
177 global $wgContLang;
178
179 if ( $title->getPrefixedText() == $sortkey ) {
180 $word = $title->getDBkey();
181 } else {
182 $word = $sortkey;
183 }
184
185 $firstChar = $this->collation->getFirstLetter( $word );
186
187 return $wgContLang->convert( $firstChar );
188 }
189
190 /**
191 * Add a page in the image namespace
192 * @param $title Title
193 * @param $sortkey
194 * @param $pageLength
195 * @param $isRedirect bool
196 */
197 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
198 global $wgContLang;
199 if ( $this->showGallery ) {
200 $flip = $this->flip['file'];
201 if ( $flip ) {
202 $this->gallery->insert( $title );
203 } else {
204 $this->gallery->add( $title );
205 }
206 } else {
207 $link = Linker::link( $title );
208 if ( $isRedirect ) {
209 // This seems kind of pointless given 'mw-redirect' class,
210 // but keeping for back-compatibility with user css.
211 $link = '<span class="redirect-in-category">' . $link . '</span>';
212 }
213 $this->imgsNoGallery[] = $link;
214
215 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
216 $this->collation->getFirstLetter( $sortkey ) );
217 }
218 }
219
220 /**
221 * Add a miscellaneous page
222 * @param $title
223 * @param $sortkey
224 * @param $pageLength
225 * @param $isRedirect bool
226 */
227 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
228 global $wgContLang;
229
230 $link = Linker::link( $title );
231 if ( $isRedirect ) {
232 // This seems kind of pointless given 'mw-redirect' class,
233 // but keeping for back-compatiability with user css.
234 $link = '<span class="redirect-in-category">' . $link . '</span>';
235 }
236 $this->articles[] = $link;
237
238 $this->articles_start_char[] = $wgContLang->convert(
239 $this->collation->getFirstLetter( $sortkey ) );
240 }
241
242 function finaliseCategoryState() {
243 if ( $this->flip['subcat'] ) {
244 $this->children = array_reverse( $this->children );
245 $this->children_start_char = array_reverse( $this->children_start_char );
246 }
247 if ( $this->flip['page'] ) {
248 $this->articles = array_reverse( $this->articles );
249 $this->articles_start_char = array_reverse( $this->articles_start_char );
250 }
251 if ( !$this->showGallery && $this->flip['file'] ) {
252 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
253 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
254 }
255 }
256
257 function doCategoryQuery() {
258 $dbr = wfGetDB( DB_SLAVE, 'category' );
259
260 $this->nextPage = array(
261 'page' => null,
262 'subcat' => null,
263 'file' => null,
264 );
265 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
266
267 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
268 # Get the sortkeys for start/end, if applicable. Note that if
269 # the collation in the database differs from the one
270 # set in $wgCategoryCollation, pagination might go totally haywire.
271 $extraConds = array( 'cl_type' => $type );
272 if ( $this->from[$type] !== null ) {
273 $extraConds[] = 'cl_sortkey >= '
274 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
275 } elseif ( $this->until[$type] !== null ) {
276 $extraConds[] = 'cl_sortkey < '
277 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
278 $this->flip[$type] = true;
279 }
280
281 $res = $dbr->select(
282 array( 'page', 'categorylinks', 'category' ),
283 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
284 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
285 'cat_subcats', 'cat_pages', 'cat_files',
286 'cl_sortkey_prefix', 'cl_collation' ),
287 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
288 __METHOD__,
289 array(
290 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
291 'LIMIT' => $this->limit + 1,
292 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
293 ),
294 array(
295 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
296 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY )
297 )
298 );
299
300 $count = 0;
301 foreach ( $res as $row ) {
302 $title = Title::newFromRow( $row );
303 if ( $row->cl_collation === '' ) {
304 // Hack to make sure that while updating from 1.16 schema
305 // and db is inconsistent, that the sky doesn't fall.
306 // See r83544. Could perhaps be removed in a couple decades...
307 $humanSortkey = $row->cl_sortkey;
308 } else {
309 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
310 }
311
312 if ( ++$count > $this->limit ) {
313 # We've reached the one extra which shows that there
314 # are additional pages to be had. Stop here...
315 $this->nextPage[$type] = $humanSortkey;
316 break;
317 }
318
319 if ( $title->getNamespace() == NS_CATEGORY ) {
320 $cat = Category::newFromRow( $row, $title );
321 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
322 } elseif ( $title->getNamespace() == NS_FILE ) {
323 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
324 } else {
325 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
326 }
327 }
328 }
329 }
330
331 /**
332 * @return string
333 */
334 function getCategoryTop() {
335 $r = $this->getCategoryBottom();
336 return $r === ''
337 ? $r
338 : "<br style=\"clear:both;\"/>\n" . $r;
339 }
340
341 /**
342 * @return string
343 */
344 function getSubcategorySection() {
345 # Don't show subcategories section if there are none.
346 $r = '';
347 $rescnt = count( $this->children );
348 $dbcnt = $this->cat->getSubcatCount();
349 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
350
351 if ( $rescnt > 0 ) {
352 # Showing subcategories
353 $r .= "<div id=\"mw-subcategories\">\n";
354 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
355 $r .= $countmsg;
356 $r .= $this->getSectionPagingLinks( 'subcat' );
357 $r .= $this->formatList( $this->children, $this->children_start_char );
358 $r .= $this->getSectionPagingLinks( 'subcat' );
359 $r .= "\n</div>";
360 }
361 return $r;
362 }
363
364 /**
365 * @return string
366 */
367 function getPagesSection() {
368 $ti = htmlspecialchars( $this->title->getText() );
369 # Don't show articles section if there are none.
370 $r = '';
371
372 # @todo FIXME: Here and in the other two sections: we don't need to bother
373 # with this rigamarole if the entire category contents fit on one page
374 # and have already been retrieved. We can just use $rescnt in that
375 # case and save a query and some logic.
376 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
377 - $this->cat->getFileCount();
378 $rescnt = count( $this->articles );
379 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
380
381 if ( $rescnt > 0 ) {
382 $r = "<div id=\"mw-pages\">\n";
383 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
384 $r .= $countmsg;
385 $r .= $this->getSectionPagingLinks( 'page' );
386 $r .= $this->formatList( $this->articles, $this->articles_start_char );
387 $r .= $this->getSectionPagingLinks( 'page' );
388 $r .= "\n</div>";
389 }
390 return $r;
391 }
392
393 /**
394 * @return string
395 */
396 function getImageSection() {
397 $r = '';
398 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
399 if ( $rescnt > 0 ) {
400 $dbcnt = $this->cat->getFileCount();
401 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
402
403 $r .= "<div id=\"mw-category-media\">\n";
404 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title->getText() ) ) . "</h2>\n";
405 $r .= $countmsg;
406 $r .= $this->getSectionPagingLinks( 'file' );
407 if ( $this->showGallery ) {
408 $r .= $this->gallery->toHTML();
409 } else {
410 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
411 }
412 $r .= $this->getSectionPagingLinks( 'file' );
413 $r .= "\n</div>";
414 }
415 return $r;
416 }
417
418 /**
419 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
420 * of the output.
421 *
422 * @param $type String: 'page', 'subcat', or 'file'
423 * @return String: HTML output, possibly empty if there are no other pages
424 */
425 private function getSectionPagingLinks( $type ) {
426 if ( $this->until[$type] !== null ) {
427 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
428 } elseif ( $this->nextPage[$type] !== null || $this->from[$type] !== null ) {
429 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
430 } else {
431 return '';
432 }
433 }
434
435 /**
436 * @return string
437 */
438 function getCategoryBottom() {
439 return '';
440 }
441
442 /**
443 * Format a list of articles chunked by letter, either as a
444 * bullet list or a columnar format, depending on the length.
445 *
446 * @param $articles Array
447 * @param $articles_start_char Array
448 * @param $cutoff Int
449 * @return String
450 * @private
451 */
452 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
453 $list = '';
454 if ( count ( $articles ) > $cutoff ) {
455 $list = self::columnList( $articles, $articles_start_char );
456 } elseif ( count( $articles ) > 0 ) {
457 // for short lists of articles in categories.
458 $list = self::shortList( $articles, $articles_start_char );
459 }
460
461 $pageLang = $this->title->getPageLanguage();
462 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
463 'class' => 'mw-content-'.$pageLang->getDir() );
464 $list = Html::rawElement( 'div', $attribs, $list );
465
466 return $list;
467 }
468
469 /**
470 * Format a list of articles chunked by letter in a three-column
471 * list, ordered vertically.
472 *
473 * TODO: Take the headers into account when creating columns, so they're
474 * more visually equal.
475 *
476 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
477 * supports those.
478 *
479 * @param $articles Array
480 * @param $articles_start_char Array
481 * @return String
482 * @private
483 */
484 static function columnList( $articles, $articles_start_char ) {
485 $columns = array_combine( $articles, $articles_start_char );
486 # Split into three columns
487 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
488
489 $ret = '<table width="100%"><tr valign="top">';
490 $prevchar = null;
491
492 foreach ( $columns as $column ) {
493 $ret .= '<td width="33.3%">';
494 $colContents = array();
495
496 # Kind of like array_flip() here, but we keep duplicates in an
497 # array instead of dropping them.
498 foreach ( $column as $article => $char ) {
499 if ( !isset( $colContents[$char] ) ) {
500 $colContents[$char] = array();
501 }
502 $colContents[$char][] = $article;
503 }
504
505 $first = true;
506 foreach ( $colContents as $char => $articles ) {
507 $ret .= '<h3>' . htmlspecialchars( $char );
508 if ( $first && $char === $prevchar ) {
509 # We're continuing a previous chunk at the top of a new
510 # column, so add " cont." after the letter.
511 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
512 }
513 $ret .= "</h3>\n";
514
515 $ret .= '<ul><li>';
516 $ret .= implode( "</li>\n<li>", $articles );
517 $ret .= '</li></ul>';
518
519 $first = false;
520 $prevchar = $char;
521 }
522
523 $ret .= "</td>\n";
524 }
525
526 $ret .= '</tr></table>';
527 return $ret;
528 }
529
530 /**
531 * Format a list of articles chunked by letter in a bullet list.
532 * @param $articles Array
533 * @param $articles_start_char Array
534 * @return String
535 * @private
536 */
537 static function shortList( $articles, $articles_start_char ) {
538 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
539 $r .= '<ul><li>' . $articles[0] . '</li>';
540 for ( $index = 1; $index < count( $articles ); $index++ ) {
541 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
542 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
543 }
544
545 $r .= "<li>{$articles[$index]}</li>";
546 }
547 $r .= '</ul>';
548 return $r;
549 }
550
551 /**
552 * Create paging links, as a helper method to getSectionPagingLinks().
553 *
554 * @param $first String The 'until' parameter for the generated URL
555 * @param $last String The 'from' parameter for the genererated URL
556 * @param $type String A prefix for parameters, 'page' or 'subcat' or
557 * 'file'
558 * @return String HTML
559 */
560 private function pagingLinks( $first, $last, $type = '' ) {
561 $prevLink = wfMessage( 'prevn' )->numParams( $this->limit )->escaped();
562
563 if ( $first != '' ) {
564 $prevQuery = $this->query;
565 $prevQuery["{$type}until"] = $first;
566 unset( $prevQuery["{$type}from"] );
567 $prevLink = Linker::linkKnown(
568 $this->addFragmentToTitle( $this->title, $type ),
569 $prevLink,
570 array(),
571 $prevQuery
572 );
573 }
574
575 $nextLink = wfMessage( 'nextn' )->numParams( $this->limit )->escaped();
576
577 if ( $last != '' ) {
578 $lastQuery = $this->query;
579 $lastQuery["{$type}from"] = $last;
580 unset( $lastQuery["{$type}until"] );
581 $nextLink = Linker::linkKnown(
582 $this->addFragmentToTitle( $this->title, $type ),
583 $nextLink,
584 array(),
585 $lastQuery
586 );
587 }
588
589 return "($prevLink) ($nextLink)";
590 }
591
592 /**
593 * Takes a title, and adds the fragment identifier that
594 * corresponds to the correct segment of the category.
595 *
596 * @param Title $title: The title (usually $this->title)
597 * @param String $section: Which section
598 * @return Title
599 */
600 private function addFragmentToTitle( $title, $section ) {
601 switch ( $section ) {
602 case 'page':
603 $fragment = 'mw-pages';
604 break;
605 case 'subcat':
606 $fragment = 'mw-subcategories';
607 break;
608 case 'file':
609 $fragment = 'mw-category-media';
610 break;
611 default:
612 throw new MWException( __METHOD__ .
613 " Invalid section $section." );
614 }
615
616 return Title::makeTitle( $title->getNamespace(),
617 $title->getDBkey(), $fragment );
618 }
619 /**
620 * What to do if the category table conflicts with the number of results
621 * returned? This function says what. Each type is considered independently
622 * of the other types.
623 *
624 * Note for grepping: uses the messages category-article-count,
625 * category-article-count-limited, category-subcat-count,
626 * category-subcat-count-limited, category-file-count,
627 * category-file-count-limited.
628 *
629 * @param $rescnt Int: The number of items returned by our database query.
630 * @param $dbcnt Int: The number of items according to the category table.
631 * @param $type String: 'subcat', 'article', or 'file'
632 * @return String: A message giving the number of items, to output to HTML.
633 */
634 private function getCountMessage( $rescnt, $dbcnt, $type ) {
635 # There are three cases:
636 # 1) The category table figure seems sane. It might be wrong, but
637 # we can't do anything about it if we don't recalculate it on ev-
638 # ery category view.
639 # 2) The category table figure isn't sane, like it's smaller than the
640 # number of actual results, *but* the number of results is less
641 # than $this->limit and there's no offset. In this case we still
642 # know the right figure.
643 # 3) We have no idea.
644
645 # Check if there's a "from" or "until" for anything
646
647 // This is a little ugly, but we seem to use different names
648 // for the paging types then for the messages.
649 if ( $type === 'article' ) {
650 $pagingType = 'page';
651 } else {
652 $pagingType = $type;
653 }
654
655 $fromOrUntil = false;
656 if ( $this->from[$pagingType] !== null || $this->until[$pagingType] !== null ) {
657 $fromOrUntil = true;
658 }
659
660 if ( $dbcnt == $rescnt || ( ( $rescnt == $this->limit || $fromOrUntil )
661 && $dbcnt > $rescnt ) ) {
662 # Case 1: seems sane.
663 $totalcnt = $dbcnt;
664 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
665 # Case 2: not sane, but salvageable. Use the number of results.
666 # Since there are fewer than 200, we can also take this opportunity
667 # to refresh the incorrect category table entry -- which should be
668 # quick due to the small number of entries.
669 $totalcnt = $rescnt;
670 $this->cat->refreshCounts();
671 } else {
672 # Case 3: hopeless. Don't give a total count at all.
673 return wfMessage( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
674 }
675 return wfMessage( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();
676 }
677 }