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