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