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