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