Add sslCAFile option to DatabaseMysqli
[mediawiki.git] / includes / CategoryViewer.php
blob9d692d71b3bd53c708c9ff0e244529ecb96783b2
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() {
111 $this->showGallery = $this->getConfig()->get( 'CategoryMagicGallery' )
112 && !$this->getOutput()->mNoGallery;
114 $this->clearCategoryState();
115 $this->doCategoryQuery();
116 $this->finaliseCategoryState();
118 $r = $this->getSubcategorySection() .
119 $this->getPagesSection() .
120 $this->getImageSection();
122 if ( $r == '' ) {
123 // If there is no category content to display, only
124 // show the top part of the navigation links.
125 // @todo FIXME: Cannot be completely suppressed because it
126 // is unknown if 'until' or 'from' makes this
127 // give 0 results.
128 $r = $r . $this->getCategoryTop();
129 } else {
130 $r = $this->getCategoryTop() .
131 $r .
132 $this->getCategoryBottom();
135 // Give a proper message if category is empty
136 if ( $r == '' ) {
137 $r = $this->msg( 'category-empty' )->parseAsBlock();
140 $lang = $this->getLanguage();
141 $attribs = [
142 'class' => 'mw-category-generated',
143 'lang' => $lang->getHtmlCode(),
144 'dir' => $lang->getDir()
146 # put a div around the headings which are in the user language
147 $r = Html::openElement( 'div', $attribs ) . $r . '</div>';
149 return $r;
152 function clearCategoryState() {
153 $this->articles = [];
154 $this->articles_start_char = [];
155 $this->children = [];
156 $this->children_start_char = [];
157 if ( $this->showGallery ) {
158 // Note that null for mode is taken to mean use default.
159 $mode = $this->getRequest()->getVal( 'gallerymode', null );
160 try {
161 $this->gallery = ImageGalleryBase::factory( $mode, $this->getContext() );
162 } catch ( Exception $e ) {
163 // User specified something invalid, fallback to default.
164 $this->gallery = ImageGalleryBase::factory( false, $this->getContext() );
167 $this->gallery->setHideBadImages();
168 } else {
169 $this->imgsNoGallery = [];
170 $this->imgsNoGallery_start_char = [];
175 * Add a subcategory to the internal lists, using a Category object
176 * @param Category $cat
177 * @param string $sortkey
178 * @param int $pageLength
180 function addSubcategoryObject( Category $cat, $sortkey, $pageLength ) {
181 // Subcategory; strip the 'Category' namespace from the link text.
182 $title = $cat->getTitle();
184 $this->children[] = $this->generateLink(
185 'subcat',
186 $title,
187 $title->isRedirect(),
188 htmlspecialchars( $title->getText() )
191 $this->children_start_char[] =
192 $this->getSubcategorySortChar( $cat->getTitle(), $sortkey );
195 function generateLink( $type, Title $title, $isRedirect, $html = null ) {
196 $link = null;
197 Hooks::run( 'CategoryViewer::generateLink', [ $type, $title, $html, &$link ] );
198 if ( $link === null ) {
199 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
200 if ( $html !== null ) {
201 $html = new HtmlArmor( $html );
203 $link = $linkRenderer->makeLink( $title, $html );
205 if ( $isRedirect ) {
206 $link = '<span class="redirect-in-category">' . $link . '</span>';
209 return $link;
213 * Get the character to be used for sorting subcategories.
214 * If there's a link from Category:A to Category:B, the sortkey of the resulting
215 * entry in the categorylinks table is Category:A, not A, which it SHOULD be.
216 * Workaround: If sortkey == "Category:".$title, than use $title for sorting,
217 * else use sortkey...
219 * @param Title $title
220 * @param string $sortkey The human-readable sortkey (before transforming to icu or whatever).
221 * @return string
223 function getSubcategorySortChar( $title, $sortkey ) {
224 global $wgContLang;
226 if ( $title->getPrefixedText() == $sortkey ) {
227 $word = $title->getDBkey();
228 } else {
229 $word = $sortkey;
232 $firstChar = $this->collation->getFirstLetter( $word );
234 return $wgContLang->convert( $firstChar );
238 * Add a page in the image namespace
239 * @param Title $title
240 * @param string $sortkey
241 * @param int $pageLength
242 * @param bool $isRedirect
244 function addImage( Title $title, $sortkey, $pageLength, $isRedirect = false ) {
245 global $wgContLang;
246 if ( $this->showGallery ) {
247 $flip = $this->flip['file'];
248 if ( $flip ) {
249 $this->gallery->insert( $title );
250 } else {
251 $this->gallery->add( $title );
253 } else {
254 $this->imgsNoGallery[] = $this->generateLink( 'image', $title, $isRedirect );
256 $this->imgsNoGallery_start_char[] = $wgContLang->convert(
257 $this->collation->getFirstLetter( $sortkey ) );
262 * Add a miscellaneous page
263 * @param Title $title
264 * @param string $sortkey
265 * @param int $pageLength
266 * @param bool $isRedirect
268 function addPage( $title, $sortkey, $pageLength, $isRedirect = false ) {
269 global $wgContLang;
271 $this->articles[] = $this->generateLink( 'page', $title, $isRedirect );
273 $this->articles_start_char[] = $wgContLang->convert(
274 $this->collation->getFirstLetter( $sortkey ) );
277 function finaliseCategoryState() {
278 if ( $this->flip['subcat'] ) {
279 $this->children = array_reverse( $this->children );
280 $this->children_start_char = array_reverse( $this->children_start_char );
282 if ( $this->flip['page'] ) {
283 $this->articles = array_reverse( $this->articles );
284 $this->articles_start_char = array_reverse( $this->articles_start_char );
286 if ( !$this->showGallery && $this->flip['file'] ) {
287 $this->imgsNoGallery = array_reverse( $this->imgsNoGallery );
288 $this->imgsNoGallery_start_char = array_reverse( $this->imgsNoGallery_start_char );
292 function doCategoryQuery() {
293 $dbr = wfGetDB( DB_REPLICA, 'category' );
295 $this->nextPage = [
296 'page' => null,
297 'subcat' => null,
298 'file' => null,
300 $this->prevPage = [
301 'page' => null,
302 'subcat' => null,
303 'file' => null,
306 $this->flip = [ 'page' => false, 'subcat' => false, 'file' => false ];
308 foreach ( [ 'page', 'subcat', 'file' ] as $type ) {
309 # Get the sortkeys for start/end, if applicable. Note that if
310 # the collation in the database differs from the one
311 # set in $wgCategoryCollation, pagination might go totally haywire.
312 $extraConds = [ 'cl_type' => $type ];
313 if ( isset( $this->from[$type] ) && $this->from[$type] !== null ) {
314 $extraConds[] = 'cl_sortkey >= '
315 . $dbr->addQuotes( $this->collation->getSortKey( $this->from[$type] ) );
316 } elseif ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
317 $extraConds[] = 'cl_sortkey < '
318 . $dbr->addQuotes( $this->collation->getSortKey( $this->until[$type] ) );
319 $this->flip[$type] = true;
322 $res = $dbr->select(
323 [ 'page', 'categorylinks', 'category' ],
324 array_merge(
325 LinkCache::getSelectFields(),
327 'page_namespace',
328 'page_title',
329 'cl_sortkey',
330 'cat_id',
331 'cat_title',
332 'cat_subcats',
333 'cat_pages',
334 'cat_files',
335 'cl_sortkey_prefix',
336 'cl_collation'
339 array_merge( [ 'cl_to' => $this->title->getDBkey() ], $extraConds ),
340 __METHOD__,
342 'USE INDEX' => [ 'categorylinks' => 'cl_sortkey' ],
343 'LIMIT' => $this->limit + 1,
344 'ORDER BY' => $this->flip[$type] ? 'cl_sortkey DESC' : 'cl_sortkey',
347 'categorylinks' => [ 'INNER JOIN', 'cl_from = page_id' ],
348 'category' => [ 'LEFT JOIN', [
349 'cat_title = page_title',
350 'page_namespace' => NS_CATEGORY
355 Hooks::run( 'CategoryViewer::doCategoryQuery', [ $type, $res ] );
356 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
358 $count = 0;
359 foreach ( $res as $row ) {
360 $title = Title::newFromRow( $row );
361 $linkCache->addGoodLinkObjFromRow( $title, $row );
363 if ( $row->cl_collation === '' ) {
364 // Hack to make sure that while updating from 1.16 schema
365 // and db is inconsistent, that the sky doesn't fall.
366 // See r83544. Could perhaps be removed in a couple decades...
367 $humanSortkey = $row->cl_sortkey;
368 } else {
369 $humanSortkey = $title->getCategorySortkey( $row->cl_sortkey_prefix );
372 if ( ++$count > $this->limit ) {
373 # We've reached the one extra which shows that there
374 # are additional pages to be had. Stop here...
375 $this->nextPage[$type] = $humanSortkey;
376 break;
378 if ( $count == $this->limit ) {
379 $this->prevPage[$type] = $humanSortkey;
382 if ( $title->getNamespace() == NS_CATEGORY ) {
383 $cat = Category::newFromRow( $row, $title );
384 $this->addSubcategoryObject( $cat, $humanSortkey, $row->page_len );
385 } elseif ( $title->getNamespace() == NS_FILE ) {
386 $this->addImage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
387 } else {
388 $this->addPage( $title, $humanSortkey, $row->page_len, $row->page_is_redirect );
395 * @return string
397 function getCategoryTop() {
398 $r = $this->getCategoryBottom();
399 return $r === ''
400 ? $r
401 : "<br style=\"clear:both;\"/>\n" . $r;
405 * @return string
407 function getSubcategorySection() {
408 # Don't show subcategories section if there are none.
409 $r = '';
410 $rescnt = count( $this->children );
411 $dbcnt = $this->cat->getSubcatCount();
412 // This function should be called even if the result isn't used, it has side-effects
413 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'subcat' );
415 if ( $rescnt > 0 ) {
416 # Showing subcategories
417 $r .= "<div id=\"mw-subcategories\">\n";
418 $r .= '<h2>' . $this->msg( 'subcategories' )->parse() . "</h2>\n";
419 $r .= $countmsg;
420 $r .= $this->getSectionPagingLinks( 'subcat' );
421 $r .= $this->formatList( $this->children, $this->children_start_char );
422 $r .= $this->getSectionPagingLinks( 'subcat' );
423 $r .= "\n</div>";
425 return $r;
429 * @return string
431 function getPagesSection() {
432 $ti = wfEscapeWikiText( $this->title->getText() );
433 # Don't show articles section if there are none.
434 $r = '';
436 # @todo FIXME: Here and in the other two sections: we don't need to bother
437 # with this rigmarole if the entire category contents fit on one page
438 # and have already been retrieved. We can just use $rescnt in that
439 # case and save a query and some logic.
440 $dbcnt = $this->cat->getPageCount() - $this->cat->getSubcatCount()
441 - $this->cat->getFileCount();
442 $rescnt = count( $this->articles );
443 // This function should be called even if the result isn't used, it has side-effects
444 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'article' );
446 if ( $rescnt > 0 ) {
447 $r = "<div id=\"mw-pages\">\n";
448 $r .= '<h2>' . $this->msg( 'category_header', $ti )->parse() . "</h2>\n";
449 $r .= $countmsg;
450 $r .= $this->getSectionPagingLinks( 'page' );
451 $r .= $this->formatList( $this->articles, $this->articles_start_char );
452 $r .= $this->getSectionPagingLinks( 'page' );
453 $r .= "\n</div>";
455 return $r;
459 * @return string
461 function getImageSection() {
462 $r = '';
463 $rescnt = $this->showGallery ? $this->gallery->count() : count( $this->imgsNoGallery );
464 $dbcnt = $this->cat->getFileCount();
465 // This function should be called even if the result isn't used, it has side-effects
466 $countmsg = $this->getCountMessage( $rescnt, $dbcnt, 'file' );
468 if ( $rescnt > 0 ) {
469 $r .= "<div id=\"mw-category-media\">\n";
470 $r .= '<h2>' .
471 $this->msg(
472 'category-media-header',
473 wfEscapeWikiText( $this->title->getText() )
474 )->text() .
475 "</h2>\n";
476 $r .= $countmsg;
477 $r .= $this->getSectionPagingLinks( 'file' );
478 if ( $this->showGallery ) {
479 $r .= $this->gallery->toHTML();
480 } else {
481 $r .= $this->formatList( $this->imgsNoGallery, $this->imgsNoGallery_start_char );
483 $r .= $this->getSectionPagingLinks( 'file' );
484 $r .= "\n</div>";
486 return $r;
490 * Get the paging links for a section (subcats/pages/files), to go at the top and bottom
491 * of the output.
493 * @param string $type 'page', 'subcat', or 'file'
494 * @return string HTML output, possibly empty if there are no other pages
496 private function getSectionPagingLinks( $type ) {
497 if ( isset( $this->until[$type] ) && $this->until[$type] !== null ) {
498 // The new value for the until parameter should be pointing to the first
499 // result displayed on the page which is the second last result retrieved
500 // from the database.The next link should have a from parameter pointing
501 // to the until parameter of the current page.
502 if ( $this->nextPage[$type] !== null ) {
503 return $this->pagingLinks( $this->prevPage[$type], $this->until[$type], $type );
504 } else {
505 // If the nextPage variable is null, it means that we have reached the first page
506 // and therefore the previous link should be disabled.
507 return $this->pagingLinks( null, $this->until[$type], $type );
509 } elseif ( $this->nextPage[$type] !== null
510 || ( isset( $this->from[$type] ) && $this->from[$type] !== null )
512 return $this->pagingLinks( $this->from[$type], $this->nextPage[$type], $type );
513 } else {
514 return '';
519 * @return string
521 function getCategoryBottom() {
522 return '';
526 * Format a list of articles chunked by letter, either as a
527 * bullet list or a columnar format, depending on the length.
529 * @param array $articles
530 * @param array $articles_start_char
531 * @param int $cutoff
532 * @return string
533 * @private
535 function formatList( $articles, $articles_start_char, $cutoff = 6 ) {
536 $list = '';
537 if ( count( $articles ) > $cutoff ) {
538 $list = self::columnList( $articles, $articles_start_char );
539 } elseif ( count( $articles ) > 0 ) {
540 // for short lists of articles in categories.
541 $list = self::shortList( $articles, $articles_start_char );
544 $pageLang = $this->title->getPageLanguage();
545 $attribs = [ 'lang' => $pageLang->getHtmlCode(), 'dir' => $pageLang->getDir(),
546 'class' => 'mw-content-' . $pageLang->getDir() ];
547 $list = Html::rawElement( 'div', $attribs, $list );
549 return $list;
553 * Format a list of articles chunked by letter in a three-column list, ordered
554 * vertically. This is used for categories with a significant number of pages.
556 * TODO: Take the headers into account when creating columns, so they're
557 * more visually equal.
559 * TODO: shortList and columnList are similar, need merging
561 * @param string[] $articles HTML links to each article
562 * @param string[] $articles_start_char The header characters for each article
563 * @return string HTML to output
564 * @private
566 static function columnList( $articles, $articles_start_char ) {
567 $columns = array_combine( $articles, $articles_start_char );
569 $ret = Html::openElement( 'div', [ 'class' => 'mw-category' ] );
571 $colContents = [];
573 # Kind of like array_flip() here, but we keep duplicates in an
574 # array instead of dropping them.
575 foreach ( $columns as $article => $char ) {
576 if ( !isset( $colContents[$char] ) ) {
577 $colContents[$char] = [];
579 $colContents[$char][] = $article;
582 foreach ( $colContents as $char => $articles ) {
583 # Change space to non-breaking space to keep headers aligned
584 $h3char = $char === ' ' ? '&#160;' : htmlspecialchars( $char );
586 $ret .= '<div class="mw-category-group"><h3>' . $h3char;
587 $ret .= "</h3>\n";
589 $ret .= '<ul><li>';
590 $ret .= implode( "</li>\n<li>", $articles );
591 $ret .= '</li></ul></div>';
595 $ret .= Html::closeElement( 'div' );
596 return $ret;
600 * Format a list of articles chunked by letter in a bullet list. This is used
601 * for categories with a small number of pages (when columns aren't needed).
602 * @param string[] $articles HTML links to each article
603 * @param string[] $articles_start_char The header characters for each article
604 * @return string HTML to output
605 * @private
607 static function shortList( $articles, $articles_start_char ) {
608 $r = '<h3>' . htmlspecialchars( $articles_start_char[0] ) . "</h3>\n";
609 $r .= '<ul><li>' . $articles[0] . '</li>';
610 $articleCount = count( $articles );
611 for ( $index = 1; $index < $articleCount; $index++ ) {
612 if ( $articles_start_char[$index] != $articles_start_char[$index - 1] ) {
613 $r .= "</ul><h3>" . htmlspecialchars( $articles_start_char[$index] ) . "</h3>\n<ul>";
616 $r .= "<li>{$articles[$index]}</li>";
618 $r .= '</ul>';
619 return $r;
623 * Create paging links, as a helper method to getSectionPagingLinks().
625 * @param string $first The 'until' parameter for the generated URL
626 * @param string $last The 'from' parameter for the generated URL
627 * @param string $type A prefix for parameters, 'page' or 'subcat' or
628 * 'file'
629 * @return string HTML
631 private function pagingLinks( $first, $last, $type = '' ) {
632 $prevLink = $this->msg( 'prev-page' )->text();
634 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
635 if ( $first != '' ) {
636 $prevQuery = $this->query;
637 $prevQuery["{$type}until"] = $first;
638 unset( $prevQuery["{$type}from"] );
639 $prevLink = $linkRenderer->makeKnownLink(
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 = $linkRenderer->makeKnownLink(
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 DeferredUpdates::addCallableUpdate( [ $this->cat, 'refreshCounts' ] );
743 } else {
744 // Case 3: hopeless. Don't give a total count at all.
745 // Messages: category-subcat-count-limited, category-article-count-limited,
746 // category-file-count-limited
747 return $this->msg( "category-$type-count-limited" )->numParams( $rescnt )->parseAsBlock();
749 // Messages: category-subcat-count, category-article-count, category-file-count
750 return $this->msg( "category-$type-count" )->numParams( $rescnt, $totalcnt )->parseAsBlock();