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