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