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