Use consistent notation for "@todo FIXME". Should update http://svn.wikimedia.org...
[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 // @todo 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 since 1.17 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',
351 'cl_sortkey_prefix', 'cl_collation' ),
352 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
353 __METHOD__,
354 array(
355 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
356 'LIMIT' => $this->limit + 1,
357 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
358 ),
359 array(
360 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
361 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY )
362 )
363 );
364
365 $count = 0;
366 foreach ( $res as $row ) {
367 $title = Title::newFromRow( $row );
368 if ( $row->cl_collation === '' ) {
369 // Hack to make sure that while updating from 1.16 schema
370 // and db is inconsistent, that the sky doesn't fall.
371 // See r83544. Could perhaps be removed in a couple decades...
372 $humanSortkey = $row->cl_sortkey;
373 } else {
374 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
375 }
376
377 if ( ++$count > $this->limit ) {
378 # We've reached the one extra which shows that there
379 # are additional pages to be had. Stop here...
380 $this->nextPage[$type] = $humanSortkey;
381 break;
382 }
383
384 if ( $title->getNamespace() == NS_CATEGORY ) {
385 $cat = Category::newFromRow( $row, $title );
386 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
387 } elseif ( $title->getNamespace() == NS_FILE ) {
388 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
389 } else {
390 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
391 }
392 }
393 }
394 }
395
396 function getCategoryTop() {
397 $r = $this->getCategoryBottom();
398 return $r === ''
399 ? $r
400 : "<br style=\"clear:both;\"/>\n" . $r;
401 }
402
403 function getSubcategorySection() {
404 # Don't show subcategories section if there are none.
405 $r = '';
406 $rescnt = count( $this->children );
407 $dbcnt = $this->cat->getSubcatCount();
408 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
409
410 if ( $rescnt > 0 ) {
411 # Showing subcategories
412 $r .= "<div id=\"mw-subcategories\">\n";
413 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
414 $r .= $countmsg;
415 $r .= $this->getSectionPagingLinks( 'subcat' );
416 $r .= $this->formatList( $this->children, $this->children_start_char );
417 $r .= $this->getSectionPagingLinks( 'subcat' );
418 $r .= "\n</div>";
419 }
420 return $r;
421 }
422
423 function getPagesSection() {
424 $ti = htmlspecialchars( $this->title->getText() );
425 # Don't show articles section if there are none.
426 $r = '';
427
428 # @todo FIXME: Here and in the other two sections: we don't need to bother
429 # with this rigamarole if the entire category contents fit on one page
430 # and have already been retrieved. We can just use $rescnt in that
431 # case and save a query and some logic.
432 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
433 - $this->cat->getFileCount();
434 $rescnt = count( $this->articles );
435 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
436
437 if ( $rescnt > 0 ) {
438 $r = "<div id=\"mw-pages\">\n";
439 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
440 $r .= $countmsg;
441 $r .= $this->getSectionPagingLinks( 'page' );
442 $r .= $this->formatList( $this->articles, $this->articles_start_char );
443 $r .= $this->getSectionPagingLinks( 'page' );
444 $r .= "\n</div>";
445 }
446 return $r;
447 }
448
449 function getImageSection() {
450 $r = '';
451 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
452 if ( $rescnt > 0 ) {
453 $dbcnt = $this->cat->getFileCount();
454 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
455
456 $r .= "<div id=\"mw-category-media\">\n";
457 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title->getText() ) ) . "</h2>\n";
458 $r .= $countmsg;
459 $r .= $this->getSectionPagingLinks( 'file' );
460 if ( $this->showGallery ) {
461 $r .= $this->gallery->toHTML();
462 } else {
463 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
464 }
465 $r .= $this->getSectionPagingLinks( 'file' );
466 $r .= "\n</div>";
467 }
468 return $r;
469 }
470
471 /**
472 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
473 * of the output.
474 *
475 * @param $type String: 'page', 'subcat', or 'file'
476 * @return String: HTML output, possibly empty if there are no other pages
477 */
478 private function getSectionPagingLinks( $type ) {
479 if ( $this->until[$type] !== null ) {
480 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
481 } elseif ( $this->nextPage[$type] !== null || $this->from[$type] !== null ) {
482 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
483 } else {
484 return '';
485 }
486 }
487
488 function getCategoryBottom() {
489 return '';
490 }
491
492 /**
493 * Format a list of articles chunked by letter, either as a
494 * bullet list or a columnar format, depending on the length.
495 *
496 * @param $articles Array
497 * @param $articles_start_char Array
498 * @param $cutoff Int
499 * @return String
500 * @private
501 */
502 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
503 if ( count ( $articles ) > $cutoff ) {
504 return self::columnList( $articles, $articles_start_char );
505 } elseif ( count( $articles ) > 0 ) {
506 // for short lists of articles in categories.
507 return self::shortList( $articles, $articles_start_char );
508 }
509 return '';
510 }
511
512 /**
513 * Format a list of articles chunked by letter in a three-column
514 * list, ordered vertically.
515 *
516 * TODO: Take the headers into account when creating columns, so they're
517 * more visually equal.
518 *
519 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
520 * supports those.
521 *
522 * @param $articles Array
523 * @param $articles_start_char Array
524 * @return String
525 * @private
526 */
527 static function columnList( $articles, $articles_start_char ) {
528 $columns = array_combine( $articles, $articles_start_char );
529 # Split into three columns
530 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
531
532 $ret = '<table width="100%"><tr valign="top"><td>';
533 $prevchar = null;
534
535 foreach ( $columns as $column ) {
536 $colContents = array();
537
538 # Kind of like array_flip() here, but we keep duplicates in an
539 # array instead of dropping them.
540 foreach ( $column as $article => $char ) {
541 if ( !isset( $colContents[$char] ) ) {
542 $colContents[$char] = array();
543 }
544 $colContents[$char][] = $article;
545 }
546
547 $first = true;
548 foreach ( $colContents as $char => $articles ) {
549 $ret .= '<h3>' . htmlspecialchars( $char );
550 if ( $first && $char === $prevchar ) {
551 # We're continuing a previous chunk at the top of a new
552 # column, so add " cont." after the letter.
553 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
554 }
555 $ret .= "</h3>\n";
556
557 $ret .= '<ul><li>';
558 $ret .= implode( "</li>\n<li>", $articles );
559 $ret .= '</li></ul>';
560
561 $first = false;
562 $prevchar = $char;
563 }
564
565 $ret .= "</td>\n<td>";
566 }
567
568 $ret .= '</td></tr></table>';
569 return $ret;
570 }
571
572 /**
573 * Format a list of articles chunked by letter in a bullet list.
574 * @param $articles Array
575 * @param $articles_start_char Array
576 * @return String
577 * @private
578 */
579 static function shortList( $articles, $articles_start_char ) {
580 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
581 $r .= '<ul><li>' . $articles[0] . '</li>';
582 for ( $index = 1; $index < count( $articles ); $index++ ) {
583 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
584 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
585 }
586
587 $r .= "<li>{$articles[$index]}</li>";
588 }
589 $r .= '</ul>';
590 return $r;
591 }
592
593 /**
594 * Create paging links, as a helper method to getSectionPagingLinks().
595 *
596 * @param $first String The 'until' parameter for the generated URL
597 * @param $last String The 'from' parameter for the genererated URL
598 * @param $type String A prefix for parameters, 'page' or 'subcat' or
599 * 'file'
600 * @return String HTML
601 */
602 private function pagingLinks( $first, $last, $type = '' ) {
603 global $wgLang;
604 $sk = $this->getSkin();
605 $limitText = $wgLang->formatNum( $this->limit );
606
607 $prevLink = wfMsgExt( 'prevn', array( 'escape', 'parsemag' ), $limitText );
608
609 if ( $first != '' ) {
610 $prevQuery = $this->query;
611 $prevQuery["{$type}until"] = $first;
612 unset( $prevQuery["{$type}from"] );
613 $prevLink = $sk->linkKnown(
614 $this->title,
615 $prevLink,
616 array(),
617 $prevQuery
618 );
619 }
620
621 $nextLink = wfMsgExt( 'nextn', array( 'escape', 'parsemag' ), $limitText );
622
623 if ( $last != '' ) {
624 $lastQuery = $this->query;
625 $lastQuery["{$type}from"] = $last;
626 unset( $lastQuery["{$type}until"] );
627 $nextLink = $sk->linkKnown(
628 $this->title,
629 $nextLink,
630 array(),
631 $lastQuery
632 );
633 }
634
635 return "($prevLink) ($nextLink)";
636 }
637
638 /**
639 * What to do if the category table conflicts with the number of results
640 * returned? This function says what. Each type is considered independently
641 * of the other types.
642 *
643 * Note for grepping: uses the messages category-article-count,
644 * category-article-count-limited, category-subcat-count,
645 * category-subcat-count-limited, category-file-count,
646 * category-file-count-limited.
647 *
648 * @param $rescnt Int: The number of items returned by our database query.
649 * @param $dbcnt Int: The number of items according to the category table.
650 * @param $type String: 'subcat', 'article', or 'file'
651 * @return String: A message giving the number of items, to output to HTML.
652 */
653 private function getCountMessage( $rescnt, $dbcnt, $type ) {
654 global $wgLang;
655 # There are three cases:
656 # 1) The category table figure seems sane. It might be wrong, but
657 # we can't do anything about it if we don't recalculate it on ev-
658 # ery category view.
659 # 2) The category table figure isn't sane, like it's smaller than the
660 # number of actual results, *but* the number of results is less
661 # than $this->limit and there's no offset. In this case we still
662 # know the right figure.
663 # 3) We have no idea.
664
665 # Check if there's a "from" or "until" for anything
666
667 // This is a little ugly, but we seem to use different names
668 // for the paging types then for the messages.
669 if ( $type === 'article' ) {
670 $pagingType = 'page';
671 } else {
672 $pagingType = $type;
673 }
674
675 $fromOrUntil = false;
676 if ( $this->from[$pagingType] !== null || $this->until[$pagingType] !== null ) {
677 $fromOrUntil = true;
678 }
679
680 if ( $dbcnt == $rescnt || ( ( $rescnt == $this->limit || $fromOrUntil )
681 && $dbcnt > $rescnt ) ) {
682 # Case 1: seems sane.
683 $totalcnt = $dbcnt;
684 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
685 # Case 2: not sane, but salvageable. Use the number of results.
686 # Since there are fewer than 200, we can also take this opportunity
687 # to refresh the incorrect category table entry -- which should be
688 # quick due to the small number of entries.
689 $totalcnt = $rescnt;
690 $this->cat->refreshCounts();
691 } else {
692 # Case 3: hopeless. Don't give a total count at all.
693 return wfMsgExt( "category-$type-count-limited", 'parse',
694 $wgLang->formatNum( $rescnt ) );
695 }
696 return wfMsgExt(
697 "category-$type-count",
698 'parse',
699 $wgLang->formatNum( $rescnt ),
700 $wgLang->formatNum( $totalcnt )
701 );
702 }
703 }