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