Special case opus mime detction
[mediawiki.git] / includes / CategoryViewer.php
blobfacf847892a1193312a2430035760ca5858b3e1b
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
22 use MediaWiki\MediaWikiServices;
24 class CategoryViewer extends ContextSource {
25 /** @var int */
26 public $limit;
28 /** @var array */
29 public $from;
31 /** @var array */
32 public $until;
34 /** @var string[] */
35 public $articles;
37 /** @var array */
38 public $articles_start_char;
40 /** @var array */
41 public $children;
43 /** @var array */
44 public $children_start_char;
46 /** @var bool */
47 public $showGallery;
49 /** @var array */
50 public $imgsNoGallery_start_char;
52 /** @var array */
53 public $imgsNoGallery;
55 /** @var array */
56 public $nextPage;
58 /** @var array */
59 protected $prevPage;
61 /** @var array */
62 public $flip;
64 /** @var Title */
65 public $title;
67 /** @var Collation */
68 public $collation;
70 /** @var ImageGalleryBase */
71 public $gallery;
73 /** @var Category Category object for this page. */
74 private $cat;
76 /** @var array The original query array, to be used in generating paging links. */
77 private $query;
79 /**
80 * @since 1.19 $context is a second, required parameter
81 * @param Title $title
82 * @param IContextSource $context
83 * @param array $from An array with keys page, subcat,
84 * and file for offset of results of each section (since 1.17)
85 * @param array $until An array with 3 keys for until of each section (since 1.17)
86 * @param array $query
88 function __construct( $title, IContextSource $context, $from = [],
89 $until = [], $query = []
90 ) {
91 $this->title = $title;
92 $this->setContext( $context );
93 $this->getOutput()->addModuleStyles( [
94 'mediawiki.action.view.categoryPage.styles'
95 ] );
96 $this->from = $from;
97 $this->until = $until;
98 $this->limit = $context->getConfig()->get( 'CategoryPagingLimit' );
99 $this->cat = Category::newFromTitle( $title );
100 $this->query = $query;
101 $this->collation = Collation::singleton();
102 unset( $this->query['title'] );
106 * Format the category data list.
108 * @return string HTML output
110 public function getHTML() {
112 $this->showGallery = $this->getConfig()->get( 'CategoryMagicGallery' )
113 && !$this->getOutput()->mNoGallery;
115 $this->clearCategoryState();
116 $this->doCategoryQuery();
117 $this->finaliseCategoryState();
119 $r = $this->getSubcategorySection() .
120 $this->getPagesSection() .
121 $this->getImageSection();
123 if ( $r == '' ) {
124 // If there is no category content to display, only
125 // show the top part of the navigation links.
126 // @todo FIXME: Cannot be completely suppressed because it
127 // is unknown if 'until' or 'from' makes this
128 // give 0 results.
129 $r = $r . $this->getCategoryTop();
130 } else {
131 $r = $this->getCategoryTop() .
132 $r .
133 $this->getCategoryBottom();
136 // Give a proper message if category is empty
137 if ( $r == '' ) {
138 $r = $this->msg( 'category-empty' )->parseAsBlock();
141 $lang = $this->getLanguage();
142 $attribs = [
143 'class' => 'mw-category-generated',
144 'lang' => $lang->getHtmlCode(),
145 'dir' => $lang->getDir()
147 # put a div around the headings which are in the user language
148 $r = Html::openElement( 'div', $attribs ) . $r . '</div>';
150 return $r;
153 function clearCategoryState() {
154 $this->articles = [];
155 $this->articles_start_char = [];
156 $this->children = [];
157 $this->children_start_char = [];
158 if ( $this->showGallery ) {
159 // Note that null for mode is taken to mean use default.
160 $mode = $this->getRequest()->getVal( 'gallerymode', null );
161 try {
162 $this->gallery = ImageGalleryBase::factory( $mode, $this->getContext() );
163 } catch ( Exception $e ) {
164 // User specified something invalid, fallback to default.
165 $this->gallery = ImageGalleryBase::factory( false, $this->getContext() );
168 $this->gallery->setHideBadImages();
169 } else {
170 $this->imgsNoGallery = [];
171 $this->imgsNoGallery_start_char = [];
176 * Add a subcategory to the internal lists, using a Category object
177 * @param Category $cat
178 * @param string $sortkey
179 * @param int $pageLength
181 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
182 // Subcategory; strip the 'Category' namespace from the link text.
183 $title = $cat->getTitle();
185 $this->children[] = $this->generateLink(
186 'subcat',
187 $title,
188 $title->isRedirect(),
189 htmlspecialchars( $title->getText() )
192 $this->children_start_char[] =
193 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
196 function generateLink( $type, Title $title, $isRedirect, $html = null ) {
197 $link = null;
198 Hooks::run( 'CategoryViewer::generateLink', [ $type, $title, $html, &$link ] );
199 if ( $link === null ) {
200 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
201 if ( $html !== null ) {
202 $html = new HtmlArmor( $html );
204 $link = $linkRenderer->makeLink( $title, $html );
206 if ( $isRedirect ) {
207 $link = '<span class="redirect-in-category">' . $link . '</span>';
210 return $link;
214 * Get the character to be used for sorting subcategories.
215 * If there's a link from Category:A to Category:B, the sortkey of the resulting
216 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
217 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
218 * else use sortkey...
220 * @param Title $title
221 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
222 * @return string
224 function getSubcategorySortChar( $title, $sortkey ) {
225 global $wgContLang;
227 if ( $title->getPrefixedText() == $sortkey ) {
228 $word = $title->getDBkey();
229 } else {
230 $word = $sortkey;
233 $firstChar = $this->collation->getFirstLetter( $word );
235 return $wgContLang->convert( $firstChar );
239 * Add a page in the image namespace
240 * @param Title $title
241 * @param string $sortkey
242 * @param int $pageLength
243 * @param bool $isRedirect
245 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
246 global $wgContLang;
247 if ( $this->showGallery ) {
248 $flip = $this->flip['file'];
249 if ( $flip ) {
250 $this->gallery->insert( $title );
251 } else {
252 $this->gallery->add( $title );
254 } else {
255 $this->imgsNoGallery[] = $this->generateLink( 'image', $title, $isRedirect );
257 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
258 $this->collation->getFirstLetter( $sortkey ) );
263 * Add a miscellaneous page
264 * @param Title $title
265 * @param string $sortkey
266 * @param int $pageLength
267 * @param bool $isRedirect
269 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
270 global $wgContLang;
272 $this->articles[] = $this->generateLink( 'page', $title, $isRedirect );
274 $this->articles_start_char[] = $wgContLang->convert(
275 $this->collation->getFirstLetter( $sortkey ) );
278 function finaliseCategoryState() {
279 if ( $this->flip['subcat'] ) {
280 $this->children = array_reverse( $this->children );
281 $this->children_start_char = array_reverse( $this->children_start_char );
283 if ( $this->flip['page'] ) {
284 $this->articles = array_reverse( $this->articles );
285 $this->articles_start_char = array_reverse( $this->articles_start_char );
287 if ( !$this->showGallery && $this->flip['file'] ) {
288 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
289 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
293 function doCategoryQuery() {
294 $dbr = wfGetDB( DB_REPLICA, 'category' );
296 $this->nextPage = [
297 'page' => null,
298 'subcat' => null,
299 'file' => null,
301 $this->prevPage = [
302 'page' => null,
303 'subcat' => null,
304 'file' => null,
307 $this->flip = [ 'page' => false, 'subcat' => false, 'file' => false ];
309 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
310 # Get the sortkeys for start/end, if applicable. Note that if
311 # the collation in the database differs from the one
312 # set in $wgCategoryCollation, pagination might go totally haywire.
313 $extraConds = [ 'cl_type' => $type ];
314 if ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
315 $extraConds[] = 'cl_sortkey >= '
316 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
317 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
318 $extraConds[] = 'cl_sortkey < '
319 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
320 $this->flip[$type] = true;
323 $res = $dbr->select(
324 [ 'page', 'categorylinks', 'category' ],
325 array_merge(
326 LinkCache::getSelectFields(),
328 'page_namespace',
329 'page_title',
330 'cl_sortkey',
331 'cat_id',
332 'cat_title',
333 'cat_subcats',
334 'cat_pages',
335 'cat_files',
336 'cl_sortkey_prefix',
337 'cl_collation'
340 array_merge( [ 'cl_to' => $this->title->getDBkey() ], $extraConds ),
341 __METHOD__,
343 'USE INDEX' => [ 'categorylinks' => 'cl_sortkey' ],
344 'LIMIT' => $this->limit + 1,
345 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
348 'categorylinks' => [ 'INNER JOIN', 'cl_from = page_id' ],
349 'category' => [ 'LEFT JOIN', [
350 'cat_title = page_title',
351 'page_namespace' => NS_CATEGORY
356 Hooks::run( 'CategoryViewer::doCategoryQuery', [ $type, $res ] );
357 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
359 $count = 0;
360 foreach ( $res as $row ) {
361 $title = Title::newFromRow( $row );
362 $linkCache->addGoodLinkObjFromRow( $title, $row );
364 if ( $row->cl_collation === '' ) {
365 // Hack to make sure that while updating from 1.16 schema
366 // and db is inconsistent, that the sky doesn't fall.
367 // See r83544. Could perhaps be removed in a couple decades...
368 $humanSortkey = $row->cl_sortkey;
369 } else {
370 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
373 if ( ++$count > $this->limit ) {
374 # We've reached the one extra which shows that there
375 # are additional pages to be had. Stop here...
376 $this->nextPage[$type] = $humanSortkey;
377 break;
379 if ( $count == $this->limit ) {
380 $this->prevPage[$type] = $humanSortkey;
383 if ( $title->getNamespace() == NS_CATEGORY ) {
384 $cat = Category::newFromRow( $row, $title );
385 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
386 } elseif ( $title->getNamespace() == NS_FILE ) {
387 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
388 } else {
389 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
396 * @return string
398 function getCategoryTop() {
399 $r = $this->getCategoryBottom();
400 return $r === ''
401 ? $r
402 : "<br style=\"clear:both;\"/>\n" . $r;
406 * @return string
408 function getSubcategorySection() {
409 # Don't show subcategories section if there are none.
410 $r = '';
411 $rescnt = count( $this->children );
412 $dbcnt = $this->cat->getSubcatCount();
413 // This function should be called even if the result isn't used, it has side-effects
414 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
416 if ( $rescnt > 0 ) {
417 # Showing subcategories
418 $r .= "<div id=\"mw-subcategories\">\n";
419 $r .= '<h2>' . $this->msg( 'subcategories' )->parse() . "</h2>\n";
420 $r .= $countmsg;
421 $r .= $this->getSectionPagingLinks( 'subcat' );
422 $r .= $this->formatList( $this->children, $this->children_start_char );
423 $r .= $this->getSectionPagingLinks( 'subcat' );
424 $r .= "\n</div>";
426 return $r;
430 * @return string
432 function getPagesSection() {
433 $ti = wfEscapeWikiText( $this->title->getText() );
434 # Don't show articles section if there are none.
435 $r = '';
437 # @todo FIXME: Here and in the other two sections: we don't need to bother
438 # with this rigmarole if the entire category contents fit on one page
439 # and have already been retrieved. We can just use $rescnt in that
440 # case and save a query and some logic.
441 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
442 - $this->cat->getFileCount();
443 $rescnt = count( $this->articles );
444 // This function should be called even if the result isn't used, it has side-effects
445 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
447 if ( $rescnt > 0 ) {
448 $r = "<div id=\"mw-pages\">\n";
449 $r .= '<h2>' . $this->msg( 'category_header', $ti )->parse() . "</h2>\n";
450 $r .= $countmsg;
451 $r .= $this->getSectionPagingLinks( 'page' );
452 $r .= $this->formatList( $this->articles, $this->articles_start_char );
453 $r .= $this->getSectionPagingLinks( 'page' );
454 $r .= "\n</div>";
456 return $r;
460 * @return string
462 function getImageSection() {
463 $r = '';
464 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
465 $dbcnt = $this->cat->getFileCount();
466 // This function should be called even if the result isn't used, it has side-effects
467 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
469 if ( $rescnt > 0 ) {
470 $r .= "<div id=\"mw-category-media\">\n";
471 $r .= '<h2>' .
472 $this->msg(
473 'category-media-header',
474 wfEscapeWikiText( $this->title->getText() )
475 )->text() .
476 "</h2>\n";
477 $r .= $countmsg;
478 $r .= $this->getSectionPagingLinks( 'file' );
479 if ( $this->showGallery ) {
480 $r .= $this->gallery->toHTML();
481 } else {
482 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
484 $r .= $this->getSectionPagingLinks( 'file' );
485 $r .= "\n</div>";
487 return $r;
491 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
492 * of the output.
494 * @param string $type 'page', 'subcat', or 'file'
495 * @return string HTML output, possibly empty if there are no other pages
497 private function getSectionPagingLinks( $type ) {
498 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
499 // The new value for the until parameter should be pointing to the first
500 // result displayed on the page which is the second last result retrieved
501 // from the database.The next link should have a from parameter pointing
502 // to the until parameter of the current page.
503 if ( $this->nextPage[$type] !== null ) {
504 return $this->pagingLinks( $this->prevPage[$type], $this->until[$type], $type );
505 } else {
506 // If the nextPage variable is null, it means that we have reached the first page
507 // and therefore the previous link should be disabled.
508 return $this->pagingLinks( null, $this->until[$type], $type );
510 } elseif ( $this->nextPage[$type] !== null
511 || ( isset( $this->from[$type] ) && $this->from[$type] !== null )
513 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
514 } else {
515 return '';
520 * @return string
522 function getCategoryBottom() {
523 return '';
527 * Format a list of articles chunked by letter, either as a
528 * bullet list or a columnar format, depending on the length.
530 * @param array $articles
531 * @param array $articles_start_char
532 * @param int $cutoff
533 * @return string
534 * @private
536 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
537 $list = '';
538 if ( count( $articles ) > $cutoff ) {
539 $list = self::columnList( $articles, $articles_start_char );
540 } elseif ( count( $articles ) > 0 ) {
541 // for short lists of articles in categories.
542 $list = self::shortList( $articles, $articles_start_char );
545 $pageLang = $this->title->getPageLanguage();
546 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
547 'class' => 'mw-content-' . $pageLang->getDir() ];
548 $list = Html::rawElement( 'div', $attribs, $list );
550 return $list;
554 * Format a list of articles chunked by letter in a three-column list, ordered
555 * vertically. This is used for categories with a significant number of pages.
557 * TODO: Take the headers into account when creating columns, so they're
558 * more visually equal.
560 * TODO: shortList and columnList are similar, need merging
562 * @param string[] $articles HTML links to each article
563 * @param string[] $articles_start_char The header characters for each article
564 * @return string HTML to output
565 * @private
567 static function columnList( $articles, $articles_start_char ) {
568 $columns = array_combine( $articles, $articles_start_char );
570 $ret = Html::openElement( 'div', [ 'class' => 'mw-category' ] );
572 $colContents = [];
574 # Kind of like array_flip() here, but we keep duplicates in an
575 # array instead of dropping them.
576 foreach ( $columns as $article => $char ) {
577 if ( !isset( $colContents[$char] ) ) {
578 $colContents[$char] = [];
580 $colContents[$char][] = $article;
583 foreach ( $colContents as $char => $articles ) {
584 # Change space to non-breaking space to keep headers aligned
585 $h3char = $char === ' ' ? '&#160;' : htmlspecialchars( $char );
587 $ret .= '<div class="mw-category-group"><h3>' . $h3char;
588 $ret .= "</h3>\n";
590 $ret .= '<ul><li>';
591 $ret .= implode( "</li>\n<li>", $articles );
592 $ret .= '</li></ul></div>';
596 $ret .= Html::closeElement( 'div' );
597 return $ret;
601 * Format a list of articles chunked by letter in a bullet list. This is used
602 * for categories with a small number of pages (when columns aren't needed).
603 * @param string[] $articles HTML links to each article
604 * @param string[] $articles_start_char The header characters for each article
605 * @return string HTML to output
606 * @private
608 static function shortList( $articles, $articles_start_char ) {
609 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
610 $r .= '<ul><li>' . $articles[0] . '</li>';
611 $articleCount = count( $articles );
612 for ( $index = 1; $index < $articleCount; $index++ ) {
613 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
614 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
617 $r .= "<li>{$articles[$index]}</li>";
619 $r .= '</ul>';
620 return $r;
624 * Create paging links, as a helper method to getSectionPagingLinks().
626 * @param string $first The 'until' parameter for the generated URL
627 * @param string $last The 'from' parameter for the generated URL
628 * @param string $type A prefix for parameters, 'page' or 'subcat' or
629 * 'file'
630 * @return string HTML
632 private function pagingLinks( $first, $last, $type = '' ) {
633 $prevLink = $this->msg( 'prev-page' )->text();
635 if ( $first != '' ) {
636 $prevQuery = $this->query;
637 $prevQuery["{$type}until"] = $first;
638 unset( $prevQuery["{$type}from"] );
639 $prevLink = Linker::linkKnown(
640 $this->addFragmentToTitle( $this->title, $type ),
641 $prevLink,
643 $prevQuery
647 $nextLink = $this->msg( 'next-page' )->text();
649 if ( $last != '' ) {
650 $lastQuery = $this->query;
651 $lastQuery["{$type}from"] = $last;
652 unset( $lastQuery["{$type}until"] );
653 $nextLink = Linker::linkKnown(
654 $this->addFragmentToTitle( $this->title, $type ),
655 $nextLink,
657 $lastQuery
661 return $this->msg( 'categoryviewer-pagedlinks' )->rawParams( $prevLink, $nextLink )->escaped();
665 * Takes a title, and adds the fragment identifier that
666 * corresponds to the correct segment of the category.
668 * @param Title $title The title (usually $this->title)
669 * @param string $section Which section
670 * @throws MWException
671 * @return Title
673 private function addFragmentToTitle( $title, $section ) {
674 switch ( $section ) {
675 case 'page':
676 $fragment = 'mw-pages';
677 break;
678 case 'subcat':
679 $fragment = 'mw-subcategories';
680 break;
681 case 'file':
682 $fragment = 'mw-category-media';
683 break;
684 default:
685 throw new MWException( __METHOD__ .
686 " Invalid section $section." );
689 return Title::makeTitle( $title->getNamespace(),
690 $title->getDBkey(), $fragment );
694 * What to do if the category table conflicts with the number of results
695 * returned? This function says what. Each type is considered independently
696 * of the other types.
698 * @param int $rescnt The number of items returned by our database query.
699 * @param int $dbcnt The number of items according to the category table.
700 * @param string $type 'subcat', 'article', or 'file'
701 * @return string A message giving the number of items, to output to HTML.
703 private function getCountMessage( $rescnt, $dbcnt, $type ) {
704 // There are three cases:
705 // 1) The category table figure seems sane. It might be wrong, but
706 // we can't do anything about it if we don't recalculate it on ev-
707 // ery category view.
708 // 2) The category table figure isn't sane, like it's smaller than the
709 // number of actual results, *but* the number of results is less
710 // than $this->limit and there's no offset. In this case we still
711 // know the right figure.
712 // 3) We have no idea.
714 // Check if there's a "from" or "until" for anything
716 // This is a little ugly, but we seem to use different names
717 // for the paging types then for the messages.
718 if ( $type === 'article' ) {
719 $pagingType = 'page';
720 } else {
721 $pagingType = $type;
724 $fromOrUntil = false;
725 if ( ( isset( $this->from[$pagingType] ) && $this->from[$pagingType] !== null ) ||
726 ( isset( $this->until[$pagingType] ) && $this->until[$pagingType] !== null )
728 $fromOrUntil = true;
731 if ( $dbcnt == $rescnt ||
732 ( ( $rescnt == $this->limit || $fromOrUntil ) && $dbcnt > $rescnt )
734 // Case 1: seems sane.
735 $totalcnt = $dbcnt;
736 } elseif ( $rescnt < $this->limit && !$fromOrUntil ) {
737 // Case 2: not sane, but salvageable. Use the number of results.
738 // Since there are fewer than 200, we can also take this opportunity
739 // to refresh the incorrect category table entry -- which should be
740 // quick due to the small number of entries.
741 $totalcnt = $rescnt;
742 $category = $this->cat;
743 DeferredUpdates::addCallableUpdate( function () use ( $category ) {
744 $category->refreshCounts();
745 } );
746 } else {
747 // Case 3: hopeless. Don't give a total count at all.
748 // Messages: category-subcat-count-limited, category-article-count-limited,
749 // category-file-count-limited
750 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
752 // Messages: category-subcat-count, category-article-count, category-file-count
753 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();