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