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