add missing deprecation notices and added deprecation version to existing ones
[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
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 */
176 function getSubcategorySortChar( $title, $sortkey ) {
177 global $wgContLang;
178
179 if ( $title->getPrefixedText() == $sortkey ) {
180 $word = $title->getDBkey();
181 } else {
182 $word = $sortkey;
183 }
184
185 $firstChar = $this->collation->getFirstLetter( $word );
186
187 return $wgContLang->convert( $firstChar );
188 }
189
190 /**
191 * Add a page in the image namespace
192 * @param $title Title
193 * @param $sortkey
194 * @param $pageLength
195 * @param $isRedirect bool
196 */
197 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
198 global $wgContLang;
199 if ( $this->showGallery ) {
200 $flip = $this->flip['file'];
201 if ( $flip ) {
202 $this->gallery->insert( $title );
203 } else {
204 $this->gallery->add( $title );
205 }
206 } else {
207 $link = Linker::link( $title );
208 if ( $isRedirect ) {
209 // This seems kind of pointless given 'mw-redirect' class,
210 // but keeping for back-compatibility with user css.
211 $link = '<span class="redirect-in-category">' . $link . '</span>';
212 }
213 $this->imgsNoGallery[] = $link;
214
215 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
216 $this->collation->getFirstLetter( $sortkey ) );
217 }
218 }
219
220 /**
221 * Add a miscellaneous page
222 * @param $title
223 * @param $sortkey
224 * @param $pageLength
225 * @param $isRedirect bool
226 */
227 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
228 global $wgContLang;
229
230 $link = Linker::link( $title );
231 if ( $isRedirect ) {
232 // This seems kind of pointless given 'mw-redirect' class,
233 // but keeping for back-compatiability with user css.
234 $link = '<span class="redirect-in-category">' . $link . '</span>';
235 }
236 $this->articles[] = $link;
237
238 $this->articles_start_char[] = $wgContLang->convert(
239 $this->collation->getFirstLetter( $sortkey ) );
240 }
241
242 function finaliseCategoryState() {
243 if ( $this->flip['subcat'] ) {
244 $this->children = array_reverse( $this->children );
245 $this->children_start_char = array_reverse( $this->children_start_char );
246 }
247 if ( $this->flip['page'] ) {
248 $this->articles = array_reverse( $this->articles );
249 $this->articles_start_char = array_reverse( $this->articles_start_char );
250 }
251 if ( !$this->showGallery && $this->flip['file'] ) {
252 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
253 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
254 }
255 }
256
257 function doCategoryQuery() {
258 $dbr = wfGetDB( DB_SLAVE, 'category' );
259
260 $this->nextPage = array(
261 'page' => null,
262 'subcat' => null,
263 'file' => null,
264 );
265 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
266
267 foreach ( array( 'page', 'subcat', 'file' ) as $type ) {
268 # Get the sortkeys for start/end, if applicable. Note that if
269 # the collation in the database differs from the one
270 # set in $wgCategoryCollation, pagination might go totally haywire.
271 $extraConds = array( 'cl_type' => $type );
272 if ( $this->from[$type] !== null ) {
273 $extraConds[] = 'cl_sortkey >= '
274 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
275 } elseif ( $this->until[$type] !== null ) {
276 $extraConds[] = 'cl_sortkey < '
277 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
278 $this->flip[$type] = true;
279 }
280
281 $res = $dbr->select(
282 array( 'page', 'categorylinks', 'category' ),
283 array( 'page_id', 'page_title', 'page_namespace', 'page_len',
284 'page_is_redirect', 'cl_sortkey', 'cat_id', 'cat_title',
285 'cat_subcats', 'cat_pages', 'cat_files',
286 'cl_sortkey_prefix', 'cl_collation' ),
287 array_merge( array( 'cl_to' => $this->title->getDBkey() ), $extraConds ),
288 __METHOD__,
289 array(
290 'USE INDEX' => array( 'categorylinks' => 'cl_sortkey' ),
291 'LIMIT' => $this->limit + 1,
292 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
293 ),
294 array(
295 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
296 'category' => array( 'LEFT JOIN', 'cat_title = page_title AND page_namespace = ' . NS_CATEGORY )
297 )
298 );
299
300 $count = 0;
301 foreach ( $res as $row ) {
302 $title = Title::newFromRow( $row );
303 if ( $row->cl_collation === '' ) {
304 // Hack to make sure that while updating from 1.16 schema
305 // and db is inconsistent, that the sky doesn't fall.
306 // See r83544. Could perhaps be removed in a couple decades...
307 $humanSortkey = $row->cl_sortkey;
308 } else {
309 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
310 }
311
312 if ( ++$count > $this->limit ) {
313 # We've reached the one extra which shows that there
314 # are additional pages to be had. Stop here...
315 $this->nextPage[$type] = $humanSortkey;
316 break;
317 }
318
319 if ( $title->getNamespace() == NS_CATEGORY ) {
320 $cat = Category::newFromRow( $row, $title );
321 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
322 } elseif ( $title->getNamespace() == NS_FILE ) {
323 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
324 } else {
325 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
326 }
327 }
328 }
329 }
330
331 /**
332 * @return string
333 */
334 function getCategoryTop() {
335 $r = $this->getCategoryBottom();
336 return $r === ''
337 ? $r
338 : "<br style=\"clear:both;\"/>\n" . $r;
339 }
340
341 /**
342 * @return string
343 */
344 function getSubcategorySection() {
345 # Don't show subcategories section if there are none.
346 $r = '';
347 $rescnt = count( $this->children );
348 $dbcnt = $this->cat->getSubcatCount();
349 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
350
351 if ( $rescnt > 0 ) {
352 # Showing subcategories
353 $r .= "<div id=\"mw-subcategories\">\n";
354 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
355 $r .= $countmsg;
356 $r .= $this->getSectionPagingLinks( 'subcat' );
357 $r .= $this->formatList( $this->children, $this->children_start_char );
358 $r .= $this->getSectionPagingLinks( 'subcat' );
359 $r .= "\n</div>";
360 }
361 return $r;
362 }
363
364 /**
365 * @return string
366 */
367 function getPagesSection() {
368 $ti = htmlspecialchars( $this->title->getText() );
369 # Don't show articles section if there are none.
370 $r = '';
371
372 # @todo FIXME: Here and in the other two sections: we don't need to bother
373 # with this rigamarole if the entire category contents fit on one page
374 # and have already been retrieved. We can just use $rescnt in that
375 # case and save a query and some logic.
376 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
377 - $this->cat->getFileCount();
378 $rescnt = count( $this->articles );
379 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
380
381 if ( $rescnt > 0 ) {
382 $r = "<div id=\"mw-pages\">\n";
383 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
384 $r .= $countmsg;
385 $r .= $this->getSectionPagingLinks( 'page' );
386 $r .= $this->formatList( $this->articles, $this->articles_start_char );
387 $r .= $this->getSectionPagingLinks( 'page' );
388 $r .= "\n</div>";
389 }
390 return $r;
391 }
392
393 /**
394 * @return string
395 */
396 function getImageSection() {
397 $r = '';
398 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
399 if ( $rescnt > 0 ) {
400 $dbcnt = $this->cat->getFileCount();
401 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
402
403 $r .= "<div id=\"mw-category-media\">\n";
404 $r .= '<h2>' . wfMsg( 'category-media-header', htmlspecialchars( $this->title->getText() ) ) . "</h2>\n";
405 $r .= $countmsg;
406 $r .= $this->getSectionPagingLinks( 'file' );
407 if ( $this->showGallery ) {
408 $r .= $this->gallery->toHTML();
409 } else {
410 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
411 }
412 $r .= $this->getSectionPagingLinks( 'file' );
413 $r .= "\n</div>";
414 }
415 return $r;
416 }
417
418 /**
419 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
420 * of the output.
421 *
422 * @param $type String: 'page', 'subcat', or 'file'
423 * @return String: HTML output, possibly empty if there are no other pages
424 */
425 private function getSectionPagingLinks( $type ) {
426 if ( $this->until[$type] !== null ) {
427 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
428 } elseif ( $this->nextPage[$type] !== null || $this->from[$type] !== null ) {
429 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
430 } else {
431 return '';
432 }
433 }
434
435 /**
436 * @return string
437 */
438 function getCategoryBottom() {
439 return '';
440 }
441
442 /**
443 * Format a list of articles chunked by letter, either as a
444 * bullet list or a columnar format, depending on the length.
445 *
446 * @param $articles Array
447 * @param $articles_start_char Array
448 * @param $cutoff Int
449 * @return String
450 * @private
451 */
452 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
453 $list = '';
454 if ( count ( $articles ) > $cutoff ) {
455 $list = self::columnList( $articles, $articles_start_char );
456 } elseif ( count( $articles ) > 0 ) {
457 // for short lists of articles in categories.
458 $list = self::shortList( $articles, $articles_start_char );
459 }
460
461 $pageLang = $this->title->getPageLanguage();
462 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
463 'class' => 'mw-content-'.$pageLang->getDir() );
464 $list = Html::rawElement( 'div', $attribs, $list );
465
466 return $list;
467 }
468
469 /**
470 * Format a list of articles chunked by letter in a three-column
471 * list, ordered vertically.
472 *
473 * TODO: Take the headers into account when creating columns, so they're
474 * more visually equal.
475 *
476 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
477 * supports those.
478 *
479 * @param $articles Array
480 * @param $articles_start_char Array
481 * @return String
482 * @private
483 */
484 static function columnList( $articles, $articles_start_char ) {
485 $columns = array_combine( $articles, $articles_start_char );
486 # Split into three columns
487 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
488
489 $ret = '<table width="100%"><tr valign="top"><td>';
490 $prevchar = null;
491
492 foreach ( $columns as $column ) {
493 $colContents = array();
494
495 # Kind of like array_flip() here, but we keep duplicates in an
496 # array instead of dropping them.
497 foreach ( $column as $article => $char ) {
498 if ( !isset( $colContents[$char] ) ) {
499 $colContents[$char] = array();
500 }
501 $colContents[$char][] = $article;
502 }
503
504 $first = true;
505 foreach ( $colContents as $char => $articles ) {
506 $ret .= '<h3>' . htmlspecialchars( $char );
507 if ( $first && $char === $prevchar ) {
508 # We're continuing a previous chunk at the top of a new
509 # column, so add " cont." after the letter.
510 $ret .= ' ' . wfMsgHtml( 'listingcontinuesabbrev' );
511 }
512 $ret .= "</h3>\n";
513
514 $ret .= '<ul><li>';
515 $ret .= implode( "</li>\n<li>", $articles );
516 $ret .= '</li></ul>';
517
518 $first = false;
519 $prevchar = $char;
520 }
521
522 $ret .= "</td>\n<td>";
523 }
524
525 $ret .= '</td></tr></table>';
526 return $ret;
527 }
528
529 /**
530 * Format a list of articles chunked by letter in a bullet list.
531 * @param $articles Array
532 * @param $articles_start_char Array
533 * @return String
534 * @private
535 */
536 static function shortList( $articles, $articles_start_char ) {
537 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
538 $r .= '<ul><li>' . $articles[0] . '</li>';
539 for ( $index = 1; $index < count( $articles ); $index++ ) {
540 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
541 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
542 }
543
544 $r .= "<li>{$articles[$index]}</li>";
545 }
546 $r .= '</ul>';
547 return $r;
548 }
549
550 /**
551 * Create paging links, as a helper method to getSectionPagingLinks().
552 *
553 * @param $first String The 'until' parameter for the generated URL
554 * @param $last String The 'from' parameter for the genererated URL
555 * @param $type String A prefix for parameters, 'page' or 'subcat' or
556 * 'file'
557 * @return String HTML
558 */
559 private function pagingLinks( $first, $last, $type = '' ) {
560 $prevLink = wfMessage( 'prevn' )->numParams( $this->limit )->escaped();
561
562 if ( $first != '' ) {
563 $prevQuery = $this->query;
564 $prevQuery["{$type}until"] = $first;
565 unset( $prevQuery["{$type}from"] );
566 $prevLink = Linker::linkKnown(
567 $this->addFragmentToTitle( $this->title, $type ),
568 $prevLink,
569 array(),
570 $prevQuery
571 );
572 }
573
574 $nextLink = wfMessage( 'nextn' )->numParams( $this->limit )->escaped();
575
576 if ( $last != '' ) {
577 $lastQuery = $this->query;
578 $lastQuery["{$type}from"] = $last;
579 unset( $lastQuery["{$type}until"] );
580 $nextLink = Linker::linkKnown(
581 $this->addFragmentToTitle( $this->title, $type ),
582 $nextLink,
583 array(),
584 $lastQuery
585 );
586 }
587
588 return "($prevLink) ($nextLink)";
589 }
590
591 /**
592 * Takes a title, and adds the fragment identifier that
593 * corresponds to the correct segment of the category.
594 *
595 * @param Title $title: The title (usually $this->title)
596 * @param String $section: Which section
597 * @return Title
598 */
599 private function addFragmentToTitle( $title, $section ) {
600 switch ( $section ) {
601 case 'page':
602 $fragment = 'mw-pages';
603 break;
604 case 'subcat':
605 $fragment = 'mw-subcategories';
606 break;
607 case 'file':
608 $fragment = 'mw-category-media';
609 break;
610 default:
611 throw new MWException( __METHOD__ .
612 " Invalid section $section." );
613 }
614
615 return Title::makeTitle( $title->getNamespace(),
616 $title->getDBkey(), $fragment );
617 }
618 /**
619 * What to do if the category table conflicts with the number of results
620 * returned? This function says what. Each type is considered independently
621 * of the other types.
622 *
623 * Note for grepping: uses the messages category-article-count,
624 * category-article-count-limited, category-subcat-count,
625 * category-subcat-count-limited, category-file-count,
626 * category-file-count-limited.
627 *
628 * @param $rescnt Int: The number of items returned by our database query.
629 * @param $dbcnt Int: The number of items according to the category table.
630 * @param $type String: 'subcat', 'article', or 'file'
631 * @return String: A message giving the number of items, to output to HTML.
632 */
633 private function getCountMessage( $rescnt, $dbcnt, $type ) {
634 # There are three cases:
635 # 1) The category table figure seems sane. It might be wrong, but
636 # we can't do anything about it if we don't recalculate it on ev-
637 # ery category view.
638 # 2) The category table figure isn't sane, like it's smaller than the
639 # number of actual results, *but* the number of results is less
640 # than $this->limit and there's no offset. In this case we still
641 # know the right figure.
642 # 3) We have no idea.
643
644 # Check if there's a "from" or "until" for anything
645
646 // This is a little ugly, but we seem to use different names
647 // for the paging types then for the messages.
648 if ( $type === 'article' ) {
649 $pagingType = 'page';
650 } else {
651 $pagingType = $type;
652 }
653
654 $fromOrUntil = false;
655 if ( $this->from[$pagingType] !== null || $this->until[$pagingType] !== null ) {
656 $fromOrUntil = true;
657 }
658
659 if ( $dbcnt == $rescnt || ( ( $rescnt == $this->limit || $fromOrUntil )
660 && $dbcnt > $rescnt ) ) {
661 # Case 1: seems sane.
662 $totalcnt = $dbcnt;
663 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
664 # Case 2: not sane, but salvageable. Use the number of results.
665 # Since there are fewer than 200, we can also take this opportunity
666 # to refresh the incorrect category table entry -- which should be
667 # quick due to the small number of entries.
668 $totalcnt = $rescnt;
669 $this->cat->refreshCounts();
670 } else {
671 # Case 3: hopeless. Don't give a total count at all.
672 return wfMessage( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
673 }
674 return wfMessage( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();
675 }
676 }