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