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