Non-word characters don't terminate tag names.
[mediawiki.git] / includes / CategoryViewer.php
bloba98f792416f2138527300935a7b3491806b0d1ca
1 <?php
2 /**
3 * List and paging of category members.
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.
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.
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
20 * @file
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;
31 /**
32 * @var Array
34 var $nextPage;
36 /**
37 * @var Array
39 var $flip;
41 /**
42 * @var Title
44 var $title;
46 /**
47 * @var Collation
49 var $collation;
51 /**
52 * @var ImageGallery
54 var $gallery;
56 /**
57 * Category object for this page
58 * @var Category
60 private $cat;
62 /**
63 * The original query array, to be used in generating paging links.
64 * @var array
66 private $query;
68 /**
69 * Constructor
71 * @since 1.19 $context is a second, required parameter
72 * @param $title Title
73 * @param $context IContextSource
74 * @param array $from An array with keys page, subcat,
75 * and file for offset of results of each section (since 1.17)
76 * @param array $until An array with 3 keys for until of each section (since 1.17)
77 * @param $query Array
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'] );
92 /**
93 * Format the category data list.
95 * @return string HTML output
97 public function getHTML() {
98 global $wgCategoryMagicGallery;
99 wfProfileIn( __METHOD__ );
101 $this->showGallery = $wgCategoryMagicGallery && !$this->getOutput()->mNoGallery;
103 $this->clearCategoryState();
104 $this->doCategoryQuery();
105 $this->finaliseCategoryState();
107 $r = $this->getSubcategorySection() .
108 $this->getPagesSection() .
109 $this->getImageSection();
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();
124 // Give a proper message if category is empty
125 if ( $r == '' ) {
126 $r = $this->msg( 'category-empty' )->parseAsBlock();
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>';
134 wfProfileOut( __METHOD__ );
135 return $r;
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();
153 * Add a subcategory to the internal lists, using a Category object
154 * @param $cat Category
155 * @param $sortkey
156 * @param $pageLength
158 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
159 // Subcategory; strip the 'Category' namespace from the link text.
160 $title = $cat->getTitle();
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>';
169 $this->children[] = $link;
171 $this->children_start_char[] =
172 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
176 * Add a subcategory to the internal lists, using a title object
177 * @deprecated since 1.17 kept for compatibility, use addSubcategoryObject instead
179 function addSubcategory( Title $title, $sortkey, $pageLength ) {
180 wfDeprecated( __METHOD__, '1.17' );
181 $this->addSubcategoryObject( Category::newFromTitle( $title ), $sortkey, $pageLength );
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...
191 * @param Title $title
192 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
193 * @return string
195 function getSubcategorySortChar( $title, $sortkey ) {
196 global $wgContLang;
198 if ( $title->getPrefixedText() == $sortkey ) {
199 $word = $title->getDBkey();
200 } else {
201 $word = $sortkey;
204 $firstChar = $this->collation->getFirstLetter( $word );
206 return $wgContLang->convert( $firstChar );
210 * Add a page in the image namespace
211 * @param $title Title
212 * @param $sortkey
213 * @param $pageLength
214 * @param $isRedirect bool
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 );
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>';
232 $this->imgsNoGallery[] = $link;
234 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
235 $this->collation->getFirstLetter( $sortkey ) );
240 * Add a miscellaneous page
241 * @param $title
242 * @param $sortkey
243 * @param $pageLength
244 * @param $isRedirect bool
246 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
247 global $wgContLang;
249 $link = Linker::link( $title );
250 if ( $isRedirect ) {
251 // This seems kind of pointless given 'mw-redirect' class,
252 // but keeping for back-compatibility with user css.
253 $link = '<span class="redirect-in-category">' . $link . '</span>';
255 $this->articles[] = $link;
257 $this->articles_start_char[] = $wgContLang->convert(
258 $this->collation->getFirstLetter( $sortkey ) );
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 );
266 if ( $this->flip['page'] ) {
267 $this->articles = array_reverse( $this->articles );
268 $this->articles_start_char = array_reverse( $this->articles_start_char );
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 );
276 function doCategoryQuery() {
277 $dbr = wfGetDB( DB_SLAVE, 'category' );
279 $this->nextPage = array(
280 'page' => null,
281 'subcat' => null,
282 'file' => null,
284 $this->flip = array( 'page' => false, 'subcat' => false, 'file' => false );
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 ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
292 $extraConds[] = 'cl_sortkey >= '
293 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
294 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
295 $extraConds[] = 'cl_sortkey < '
296 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
297 $this->flip[$type] = true;
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',
313 array(
314 'categorylinks' => array( 'INNER JOIN', 'cl_from = page_id' ),
315 'category' => array( 'LEFT JOIN', array(
316 'cat_title = page_title',
317 'page_namespace' => NS_CATEGORY
322 $count = 0;
323 foreach ( $res as $row ) {
324 $title = Title::newFromRow( $row );
325 if ( $row->cl_collation === '' ) {
326 // Hack to make sure that while updating from 1.16 schema
327 // and db is inconsistent, that the sky doesn't fall.
328 // See r83544. Could perhaps be removed in a couple decades...
329 $humanSortkey = $row->cl_sortkey;
330 } else {
331 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
334 if ( ++$count > $this->limit ) {
335 # We've reached the one extra which shows that there
336 # are additional pages to be had. Stop here...
337 $this->nextPage[$type] = $humanSortkey;
338 break;
341 if ( $title->getNamespace() == NS_CATEGORY ) {
342 $cat = Category::newFromRow( $row, $title );
343 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
344 } elseif ( $title->getNamespace() == NS_FILE ) {
345 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
346 } else {
347 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
354 * @return string
356 function getCategoryTop() {
357 $r = $this->getCategoryBottom();
358 return $r === ''
359 ? $r
360 : "<br style=\"clear:both;\"/>\n" . $r;
364 * @return string
366 function getSubcategorySection() {
367 # Don't show subcategories section if there are none.
368 $r = '';
369 $rescnt = count( $this->children );
370 $dbcnt = $this->cat->getSubcatCount();
371 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
373 if ( $rescnt > 0 ) {
374 # Showing subcategories
375 $r .= "<div id=\"mw-subcategories\">\n";
376 $r .= '<h2>' . $this->msg( 'subcategories' )->text() . "</h2>\n";
377 $r .= $countmsg;
378 $r .= $this->getSectionPagingLinks( 'subcat' );
379 $r .= $this->formatList( $this->children, $this->children_start_char );
380 $r .= $this->getSectionPagingLinks( 'subcat' );
381 $r .= "\n</div>";
383 return $r;
387 * @return string
389 function getPagesSection() {
390 $ti = wfEscapeWikiText( $this->title->getText() );
391 # Don't show articles section if there are none.
392 $r = '';
394 # @todo FIXME: Here and in the other two sections: we don't need to bother
395 # with this rigmarole if the entire category contents fit on one page
396 # and have already been retrieved. We can just use $rescnt in that
397 # case and save a query and some logic.
398 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
399 - $this->cat->getFileCount();
400 $rescnt = count( $this->articles );
401 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
403 if ( $rescnt > 0 ) {
404 $r = "<div id=\"mw-pages\">\n";
405 $r .= '<h2>' . $this->msg( 'category_header', $ti )->text() . "</h2>\n";
406 $r .= $countmsg;
407 $r .= $this->getSectionPagingLinks( 'page' );
408 $r .= $this->formatList( $this->articles, $this->articles_start_char );
409 $r .= $this->getSectionPagingLinks( 'page' );
410 $r .= "\n</div>";
412 return $r;
416 * @return string
418 function getImageSection() {
419 $r = '';
420 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
421 if ( $rescnt > 0 ) {
422 $dbcnt = $this->cat->getFileCount();
423 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
425 $r .= "<div id=\"mw-category-media\">\n";
426 $r .= '<h2>' . $this->msg( 'category-media-header', wfEscapeWikiText( $this->title->getText() ) )->text() . "</h2>\n";
427 $r .= $countmsg;
428 $r .= $this->getSectionPagingLinks( 'file' );
429 if ( $this->showGallery ) {
430 $r .= $this->gallery->toHTML();
431 } else {
432 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
434 $r .= $this->getSectionPagingLinks( 'file' );
435 $r .= "\n</div>";
437 return $r;
441 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
442 * of the output.
444 * @param string $type 'page', 'subcat', or 'file'
445 * @return String: HTML output, possibly empty if there are no other pages
447 private function getSectionPagingLinks( $type ) {
448 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
449 return $this->pagingLinks( $this->nextPage[$type], $this->until[$type], $type );
450 } elseif ( $this->nextPage[$type] !== null || ( isset( $this->from[$type] ) && $this->from[$type] !== null ) ) {
451 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
452 } else {
453 return '';
458 * @return string
460 function getCategoryBottom() {
461 return '';
465 * Format a list of articles chunked by letter, either as a
466 * bullet list or a columnar format, depending on the length.
468 * @param $articles Array
469 * @param $articles_start_char Array
470 * @param $cutoff Int
471 * @return String
472 * @private
474 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
475 $list = '';
476 if ( count( $articles ) > $cutoff ) {
477 $list = self::columnList( $articles, $articles_start_char );
478 } elseif ( count( $articles ) > 0 ) {
479 // for short lists of articles in categories.
480 $list = self::shortList( $articles, $articles_start_char );
483 $pageLang = $this->title->getPageLanguage();
484 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
485 'class' => 'mw-content-' . $pageLang->getDir() );
486 $list = Html::rawElement( 'div', $attribs, $list );
488 return $list;
492 * Format a list of articles chunked by letter in a three-column
493 * list, ordered vertically.
495 * TODO: Take the headers into account when creating columns, so they're
496 * more visually equal.
498 * More distant TODO: Scrap this and use CSS columns, whenever IE finally
499 * supports those.
501 * @param $articles Array
502 * @param $articles_start_char Array
503 * @return String
504 * @private
506 static function columnList( $articles, $articles_start_char ) {
507 $columns = array_combine( $articles, $articles_start_char );
508 # Split into three columns
509 $columns = array_chunk( $columns, ceil( count( $columns ) / 3 ), true /* preserve keys */ );
511 $ret = '<table style="width: 100%;"><tr style="vertical-align: top;">';
512 $prevchar = null;
514 foreach ( $columns as $column ) {
515 $ret .= '<td style="width: 33.3%;">';
516 $colContents = array();
518 # Kind of like array_flip() here, but we keep duplicates in an
519 # array instead of dropping them.
520 foreach ( $column as $article => $char ) {
521 if ( !isset( $colContents[$char] ) ) {
522 $colContents[$char] = array();
524 $colContents[$char][] = $article;
527 $first = true;
528 foreach ( $colContents as $char => $articles ) {
529 # Change space to non-breaking space to keep headers aligned
530 $h3char = $char === ' ' ? '&#160;' : htmlspecialchars( $char );
532 $ret .= '<h3>' . $h3char;
533 if ( $first && $char === $prevchar ) {
534 # We're continuing a previous chunk at the top of a new
535 # column, so add " cont." after the letter.
536 $ret .= ' ' . wfMessage( 'listingcontinuesabbrev' )->escaped();
538 $ret .= "</h3>\n";
540 $ret .= '<ul><li>';
541 $ret .= implode( "</li>\n<li>", $articles );
542 $ret .= '</li></ul>';
544 $first = false;
545 $prevchar = $char;
548 $ret .= "</td>\n";
551 $ret .= '</tr></table>';
552 return $ret;
556 * Format a list of articles chunked by letter in a bullet list.
557 * @param $articles Array
558 * @param $articles_start_char Array
559 * @return String
560 * @private
562 static function shortList( $articles, $articles_start_char ) {
563 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
564 $r .= '<ul><li>' . $articles[0] . '</li>';
565 for ( $index = 1; $index < count( $articles ); $index++ ) {
566 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
567 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
570 $r .= "<li>{$articles[$index]}</li>";
572 $r .= '</ul>';
573 return $r;
577 * Create paging links, as a helper method to getSectionPagingLinks().
579 * @param string $first The 'until' parameter for the generated URL
580 * @param string $last The 'from' parameter for the generated URL
581 * @param string $type A prefix for parameters, 'page' or 'subcat' or
582 * 'file'
583 * @return String HTML
585 private function pagingLinks( $first, $last, $type = '' ) {
586 $prevLink = $this->msg( 'prevn' )->numParams( $this->limit )->escaped();
588 if ( $first != '' ) {
589 $prevQuery = $this->query;
590 $prevQuery["{$type}until"] = $first;
591 unset( $prevQuery["{$type}from"] );
592 $prevLink = Linker::linkKnown(
593 $this->addFragmentToTitle( $this->title, $type ),
594 $prevLink,
595 array(),
596 $prevQuery
600 $nextLink = $this->msg( 'nextn' )->numParams( $this->limit )->escaped();
602 if ( $last != '' ) {
603 $lastQuery = $this->query;
604 $lastQuery["{$type}from"] = $last;
605 unset( $lastQuery["{$type}until"] );
606 $nextLink = Linker::linkKnown(
607 $this->addFragmentToTitle( $this->title, $type ),
608 $nextLink,
609 array(),
610 $lastQuery
614 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
618 * Takes a title, and adds the fragment identifier that
619 * corresponds to the correct segment of the category.
621 * @param Title $title: The title (usually $this->title)
622 * @param string $section: Which section
623 * @throws MWException
624 * @return Title
626 private function addFragmentToTitle( $title, $section ) {
627 switch ( $section ) {
628 case 'page':
629 $fragment = 'mw-pages';
630 break;
631 case 'subcat':
632 $fragment = 'mw-subcategories';
633 break;
634 case 'file':
635 $fragment = 'mw-category-media';
636 break;
637 default:
638 throw new MWException( __METHOD__ .
639 " Invalid section $section." );
642 return Title::makeTitle( $title->getNamespace(),
643 $title->getDBkey(), $fragment );
647 * What to do if the category table conflicts with the number of results
648 * returned? This function says what. Each type is considered independently
649 * of the other types.
651 * Note for grepping: uses the messages category-article-count,
652 * category-article-count-limited, category-subcat-count,
653 * category-subcat-count-limited, category-file-count,
654 * category-file-count-limited.
656 * @param int $rescnt The number of items returned by our database query.
657 * @param int $dbcnt The number of items according to the category table.
658 * @param string $type 'subcat', 'article', or 'file'
659 * @return String: A message giving the number of items, to output to HTML.
661 private function getCountMessage( $rescnt, $dbcnt, $type ) {
662 # There are three cases:
663 # 1) The category table figure seems sane. It might be wrong, but
664 # we can't do anything about it if we don't recalculate it on ev-
665 # ery category view.
666 # 2) The category table figure isn't sane, like it's smaller than the
667 # number of actual results, *but* the number of results is less
668 # than $this->limit and there's no offset. In this case we still
669 # know the right figure.
670 # 3) We have no idea.
672 # Check if there's a "from" or "until" for anything
674 // This is a little ugly, but we seem to use different names
675 // for the paging types then for the messages.
676 if ( $type === 'article' ) {
677 $pagingType = 'page';
678 } else {
679 $pagingType = $type;
682 $fromOrUntil = false;
683 if ( ( isset( $this->from[$pagingType] ) && $this->from[$pagingType] !== null ) ||
684 ( isset( $this->until[$pagingType] ) && $this->until[$pagingType] !== null )
686 $fromOrUntil = true;
689 if ( $dbcnt == $rescnt ||
690 ( ( $rescnt == $this->limit || $fromOrUntil ) && $dbcnt > $rescnt )
692 # Case 1: seems sane.
693 $totalcnt = $dbcnt;
694 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
695 # Case 2: not sane, but salvageable. Use the number of results.
696 # Since there are fewer than 200, we can also take this opportunity
697 # to refresh the incorrect category table entry -- which should be
698 # quick due to the small number of entries.
699 $totalcnt = $rescnt;
700 $this->cat->refreshCounts();
701 } else {
702 # Case 3: hopeless. Don't give a total count at all.
703 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
705 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();