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