Debian Codegraph @

extensions/CategoryTree/includes/CategoryTree.php

raw symbols SCIP
1 <?php
2 /**
3 * © 2006-2007 Daniel Kinzler
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 * @ingroup Extensions
22 * @author Daniel Kinzler, brightbyte.de
23 */
24
25 namespace MediaWiki\Extension\CategoryTree;
26
27 use MediaWiki\Category\Category;
28 use MediaWiki\Config\Config;
29 use MediaWiki\Context\IContextSource;
30 use MediaWiki\Context\RequestContext;
31 use MediaWiki\Extension\Translate\PageTranslation\TranslatablePage;
32 use MediaWiki\Html\Html;
33 use MediaWiki\Linker\LinkRenderer;
34 use MediaWiki\MediaWikiServices;
35 use MediaWiki\Output\OutputPage;
36 use MediaWiki\Registration\ExtensionRegistry;
37 use MediaWiki\SpecialPage\SpecialPage;
38 use MediaWiki\Title\Title;
39 use Wikimedia\Rdbms\IConnectionProvider;
40
41 /**
42 * Core functions for the CategoryTree extension, an AJAX based gadget
43 * to display the category structure of a wiki
44 */
45 class CategoryTree {
46 public OptionManager $optionManager;
47 private Config $config;
48 private IConnectionProvider $dbProvider;
49 private LinkRenderer $linkRenderer;
50
51 public function __construct(
52 array $options,
53 Config $config,
54 IConnectionProvider $dbProvider,
55 LinkRenderer $linkRenderer
56 ) {
57 $this->optionManager = new OptionManager( $options, $config );
58 $this->config = $config;
59 $this->dbProvider = $dbProvider;
60 $this->linkRenderer = $linkRenderer;
61 }
62
63 /**
64 * Add ResourceLoader modules to the OutputPage object
65 */
66 public static function setHeaders( OutputPage $outputPage ): void {
67 # Add the modules
68 $outputPage->addModuleStyles( 'ext.categoryTree.styles' );
69 $outputPage->addModules( 'ext.categoryTree' );
70 }
71
72 /**
73 * Custom tag implementation. This is called by Hooks::parserHook, which is used to
74 * load CategoryTreeFunctions.php on demand.
75 * @param string $category
76 * @param bool $hideroot
77 * @param array $attr
78 * @param int $depth
79 * @return bool|string
80 */
81 public function getTag( string $category, bool $hideroot = false, array $attr = [],
82 int $depth = 1
83 ) {
84 $title = self::makeTitle( $category );
85 if ( !$title ) {
86 return false;
87 }
88
89 if ( isset( $attr['class'] ) ) {
90 $attr['class'] .= ' CategoryTreeTag';
91 } else {
92 $attr['class'] = 'CategoryTreeTag';
93 }
94
95 $attr['data-ct-mode'] = $this->optionManager->getOption( 'mode' );
96 $attr['data-ct-options'] = $this->optionManager->getOptionsAsJsStructure();
97
98 if ( !$title->getArticleID() ) {
99 $html = Html::rawElement( 'span', [ 'class' => 'CategoryTreeNotice' ],
100 wfMessage( 'categorytree-not-found' )
101 ->plaintextParams( $category )
102 ->parse()
103 );
104 } else {
105 if ( !$hideroot ) {
106 $html = $this->renderNode( $title, $depth );
107 } else {
108 $html = $this->renderChildren( $title, $depth );
109 }
110 }
111
112 return Html::rawElement( 'div', $attr, $html );
113 }
114
115 /**
116 * Returns a string with an HTML representation of the children of the given category.
117 * @suppress PhanUndeclaredClassMethod,PhanUndeclaredClassInstanceof
118 */
119 public function renderChildren( Title $title, int $depth = 1 ): string {
120 if ( !$title->inNamespace( NS_CATEGORY ) ) {
121 // Non-categories can't have children. :)
122 return '';
123 }
124
125 $dbr = $this->dbProvider->getReplicaDatabase();
126
127 $inverse = $this->optionManager->isInverse();
128 $mode = $this->optionManager->getOption( 'mode' );
129 $namespaces = $this->optionManager->getOption( 'namespaces' );
130
131 $queryBuilder = $dbr->newSelectQueryBuilder()
132 ->select( [
133 'page_id', 'page_namespace', 'page_title',
134 'page_is_redirect', 'page_len', 'page_latest', 'cl_to', 'cl_from'
135 ] )
136 ->orderBy( [ 'cl_type', 'cl_sortkey' ] )
137 ->limit( $this->config->get( 'CategoryTreeMaxChildren' ) )
138 ->caller( __METHOD__ );
139
140 if ( $inverse ) {
141 $queryBuilder
142 ->from( 'categorylinks' )
143 ->leftJoin( 'page', null, [
144 'cl_to = page_title', 'page_namespace' => NS_CATEGORY
145 ] )
146 ->where( [ 'cl_from' => $title->getArticleID() ] );
147 } else {
148 $queryBuilder
149 ->from( 'page' )
150 ->join( 'categorylinks', null, 'cl_from = page_id' )
151 ->where( [ 'cl_to' => $title->getDBkey() ] )
152 ->useIndex( 'cl_sortkey' );
153
154 # namespace filter.
155 if ( $namespaces ) {
156 // NOTE: we assume that the $namespaces array contains only integers!
157 // decodeNamepsaces makes it so.
158 $queryBuilder->where( [ 'page_namespace' => $namespaces ] );
159 } elseif ( $mode !== CategoryTreeMode::ALL ) {
160 if ( $mode === CategoryTreeMode::PAGES ) {
161 $queryBuilder->where( [ 'cl_type' => [ 'page', 'subcat' ] ] );
162 } else {
163 $queryBuilder->where( [ 'cl_type' => 'subcat' ] );
164 }
165 }
166 }
167
168 # fetch member count if possible
169 $doCount = !$inverse && $this->config->get( 'CategoryTreeUseCategoryTable' );
170
171 if ( $doCount ) {
172 $queryBuilder
173 ->leftJoin( 'category', null, [ 'cat_title = page_title', 'page_namespace' => NS_CATEGORY ] )
174 ->fields( [ 'cat_id', 'cat_title', 'cat_subcats', 'cat_pages', 'cat_files' ] );
175 }
176
177 $res = $queryBuilder->fetchResultSet();
178
179 # collect categories separately from other pages
180 $categories = '';
181 $other = '';
182 $suppressTranslations = OptionManager::decodeBoolean(
183 $this->optionManager->getOption( 'notranslations' )
184 ) && ExtensionRegistry::getInstance()->isLoaded( 'Translate' );
185
186 if ( $suppressTranslations ) {
187 $lb = MediaWikiServices::getInstance()->getLinkBatchFactory()->newLinkBatch();
188 foreach ( $res as $row ) {
189 $title = Title::newFromText( $row->page_title, $row->page_namespace );
190 // Page name could have slashes, check the subpage for valid language built-in codes
191 if ( $title !== null && $title->getSubpageText() ) {
192 $lb->addObj( $title->getBaseTitle() );
193 }
194 }
195
196 $lb->execute();
197 }
198
199 foreach ( $res as $row ) {
200 if ( $suppressTranslations ) {
201 $title = Title::newFromRow( $row );
202 $baseTitle = $title->getBaseTitle();
203 $page = TranslatablePage::isTranslationPage( $title );
204
205 if ( ( $page instanceof TranslatablePage ) && $baseTitle->exists() ) {
206 // T229265: Render only the default pages created and ignore their
207 // translations.
208 continue;
209 }
210 }
211
212 # NOTE: in inverse mode, the page record may be null, because we use a right join.
213 # happens for categories with no category page (red cat links)
214 if ( $inverse && $row->page_title === null ) {
215 $t = Title::makeTitle( NS_CATEGORY, $row->cl_to );
216 } else {
217 # TODO: translation support; ideally added to Title object
218 $t = Title::newFromRow( $row );
219 }
220
221 $cat = null;
222
223 if ( $doCount && (int)$row->page_namespace === NS_CATEGORY ) {
224 $cat = Category::newFromRow( $row, $t );
225 }
226
227 $s = $this->renderNodeInfo( $t, $cat, $depth - 1 );
228
229 if ( (int)$row->page_namespace === NS_CATEGORY ) {
230 $categories .= $s;
231 } else {
232 $other .= $s;
233 }
234 }
235
236 return $categories . $other;
237 }
238
239 /**
240 * Returns a string with an HTML representation of the parents of the given category.
241 */
242 public function renderParents( Title $title ): string {
243 $dbr = $this->dbProvider->getReplicaDatabase();
244
245 $res = $dbr->newSelectQueryBuilder()
246 ->select( 'cl_to' )
247 ->from( 'categorylinks' )
248 ->where( [ 'cl_from' => $title->getArticleID() ] )
249 ->limit( $this->config->get( 'CategoryTreeMaxChildren' ) )
250 ->orderBy( 'cl_to' )
251 ->caller( __METHOD__ )
252 ->fetchResultSet();
253
254 $special = SpecialPage::getTitleFor( 'CategoryTree' );
255
256 $s = [];
257
258 foreach ( $res as $row ) {
259 $t = Title::makeTitle( NS_CATEGORY, $row->cl_to );
260
261 $s[] = Html::rawElement( 'span', [ 'class' => 'CategoryTreeItem' ],
262 $this->linkRenderer->makeLink(
263 $special,
264 $t->getText(),
265 [ 'class' => 'CategoryTreeLabel' ],
266 [ 'target' => $t->getDBkey() ] + $this->optionManager->getOptions()
267 )
268 );
269 }
270
271 return implode( wfMessage( 'pipe-separator' )->escaped(), $s );
272 }
273
274 /**
275 * Returns a string with a HTML represenation of the given page.
276 * @param Title $title
277 * @param int $children
278 * @return string
279 */
280 public function renderNode( Title $title, int $children = 0 ): string {
281 if ( $this->config->get( 'CategoryTreeUseCategoryTable' )
282 && $title->inNamespace( NS_CATEGORY )
283 && !$this->optionManager->isInverse()
284 ) {
285 $cat = Category::newFromTitle( $title );
286 } else {
287 $cat = null;
288 }
289
290 return $this->renderNodeInfo( $title, $cat, $children );
291 }
292
293 /**
294 * Returns a string with a HTML represenation of the given page.
295 * $info must be an associative array, containing at least a Title object under the 'title' key.
296 */
297 public function renderNodeInfo( Title $title, ?Category $cat = null, int $children = 0 ): string {
298 $mode = $this->optionManager->getOption( 'mode' );
299
300 $isInCatNS = $title->inNamespace( NS_CATEGORY );
301 $key = $title->getDBkey();
302
303 $hideprefix = $this->optionManager->getOption( 'hideprefix' );
304
305 if ( $hideprefix === CategoryTreeHidePrefix::ALWAYS ) {
306 $hideprefix = true;
307 } elseif ( $hideprefix === CategoryTreeHidePrefix::AUTO ) {
308 $hideprefix = ( $mode === CategoryTreeMode::CATEGORIES );
309 } elseif ( $hideprefix === CategoryTreeHidePrefix::CATEGORIES ) {
310 $hideprefix = $isInCatNS;
311 } else {
312 $hideprefix = true;
313 }
314
315 // when showing only categories, omit namespace in label unless we explicitely defined the
316 // configuration setting
317 // patch contributed by Manuel Schneider <[email protected]>, Bug 8011
318 if ( $hideprefix ) {
319 $label = $title->getText();
320 } else {
321 $label = $title->getPrefixedText();
322 }
323
324 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
325 $link = Html::rawElement( 'bdi', [ 'dir' => $contLang->getDir() ],
326 $this->linkRenderer->makeLink( $title, $label ) );
327
328 $count = false;
329 $s = '';
330
331 # NOTE: things in CategoryTree.js rely on the exact order of tags!
332 # Specifically, the CategoryTreeChildren div must be the first
333 # sibling with nodeName = DIV of the grandparent of the expland link.
334
335 $s .= Html::openElement( 'div', [ 'class' => 'CategoryTreeSection' ] );
336 $s .= Html::openElement( 'div', [ 'class' => 'CategoryTreeItem' ] );
337
338 $attr = [ 'class' => 'CategoryTreeBullet' ];
339
340 if ( $isInCatNS ) {
341 if ( $cat ) {
342 if ( $mode === CategoryTreeMode::CATEGORIES ) {
343 $count = $cat->getSubcatCount();
344 } elseif ( $mode === CategoryTreeMode::PAGES ) {
345 $count = $cat->getMemberCount() - $cat->getFileCount();
346 } else {
347 $count = $cat->getMemberCount();
348 }
349 }
350 if ( $count === 0 ) {
351 $bullet = '';
352 $attr['class'] = 'CategoryTreeEmptyBullet';
353 } else {
354 $linkattr = [
355 // href and role will be added client-side
356 'class' => 'CategoryTreeToggle',
357 'data-ct-title' => $key,
358 'href' => $title->getLocalURL(),
359 ];
360
361 if ( $children === 0 ) {
362 $linkattr['aria-expanded'] = 'false';
363 } else {
364 $linkattr['data-ct-loaded'] = true;
365 $linkattr['aria-expanded'] = 'true';
366 }
367
368 $bullet = Html::element( 'a', $linkattr ) . ' ';
369 }
370 } else {
371 $bullet = '';
372 $attr['class'] = 'CategoryTreePageBullet';
373 }
374 $s .= Html::rawElement( 'span', $attr, $bullet ) . ' ';
375
376 $s .= $link;
377
378 if ( $count !== false && $this->optionManager->getOption( 'showcount' ) ) {
379 $s .= self::createCountString( RequestContext::getMain(), $cat, $count );
380 }
381
382 $s .= Html::closeElement( 'div' );
383 $s .= Html::openElement(
384 'div',
385 [
386 'class' => 'CategoryTreeChildren',
387 'style' => $children === 0 ? 'display:none' : null
388 ]
389 );
390
391 if ( $isInCatNS && $children > 0 ) {
392 $children = $this->renderChildren( $title, $children );
393 if ( $children === '' ) {
394 switch ( $mode ) {
395 case CategoryTreeMode::CATEGORIES:
396 $msg = 'categorytree-no-subcategories';
397 break;
398 case CategoryTreeMode::PAGES:
399 $msg = 'categorytree-no-pages';
400 break;
401 case CategoryTreeMode::PARENTS:
402 $msg = 'categorytree-no-parent-categories';
403 break;
404 default:
405 $msg = 'categorytree-nothing-found';
406 break;
407 }
408 $children = Html::element( 'i', [ 'class' => 'CategoryTreeNotice' ],
409 wfMessage( $msg )->text()
410 );
411 }
412 $s .= $children;
413 }
414
415 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'div' );
416
417 return $s;
418 }
419
420 /**
421 * Create a string which format the page, subcat and file counts of a category
422 */
423 public static function createCountString( IContextSource $context, ?Category $cat,
424 int $countMode
425 ): string {
426 $allCount = $cat ? $cat->getMemberCount() : 0;
427 $subcatCount = $cat ? $cat->getSubcatCount() : 0;
428 $fileCount = $cat ? $cat->getFileCount() : 0;
429 $pages = $cat ? $cat->getPageCount( Category::COUNT_CONTENT_PAGES ) : 0;
430
431 $attr = [
432 'title' => $context->msg( 'categorytree-member-counts' )
433 ->numParams( $subcatCount, $pages, $fileCount, $allCount, $countMode )->text(),
434 # numbers and commas get messed up in a mixed dir env
435 'dir' => $context->getLanguage()->getDir()
436 ];
437
438 # Create a list of category members with only non-zero member counts
439 $memberNums = [];
440 if ( $subcatCount ) {
441 $memberNums[] = $context->msg( 'categorytree-num-categories' )
442 ->numParams( $subcatCount )->text();
443 }
444 if ( $pages ) {
445 $memberNums[] = $context->msg( 'categorytree-num-pages' )->numParams( $pages )->text();
446 }
447 if ( $fileCount ) {
448 $memberNums[] = $context->msg( 'categorytree-num-files' )
449 ->numParams( $fileCount )->text();
450 }
451 $memberNumsShort = $memberNums
452 ? $context->getLanguage()->commaList( $memberNums )
453 : $context->msg( 'categorytree-num-empty' )->text();
454
455 # Only $5 is actually used in the default message.
456 # Other arguments can be used in a customized message.
457 $s = ' ' . Html::rawElement(
458 'span',
459 $attr,
460 $context->msg( 'categorytree-member-num' )
461 // Do not use numParams on params 1-4, as they are only used for customisation.
462 ->params( $subcatCount, $pages, $fileCount, $allCount, $memberNumsShort )
463 ->escaped()
464 );
465
466 return $s;
467 }
468
469 /**
470 * Creates a Title object from a user provided (and thus unsafe) string
471 */
472 public static function makeTitle( string $title ): ?Title {
473 $title = trim( $title );
474
475 if ( $title === '' ) {
476 return null;
477 }
478
479 # The title must be in the category namespace
480 # Ignore a leading Category: if there is one
481 $t = Title::newFromText( $title, NS_CATEGORY );
482 if ( !$t || !$t->inNamespace( NS_CATEGORY ) || $t->isExternal() ) {
483 // If we were given something like "Wikipedia:Foo" or "Template:",
484 // try it again but forced.
485 $title = "Category:$title";
486 $t = Title::newFromText( $title );
487 }
488 return $t;
489 }
490 }