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