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