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