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