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