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