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