summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/CategoryTree/includes/CategoryTree.php
blob: 139012fd89a52ef4ea981b2b86cba02a80044cc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
<?php
/**
 * © 2006-2007 Daniel Kinzler
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Extensions
 * @author Daniel Kinzler, brightbyte.de
 */

/**
 * Core functions for the CategoryTree extension, an AJAX based gadget
 * to display the category structure of a wiki
 */
class CategoryTree {
	public $mOptions = [];

	/**
	 * @param array $options
	 */
	public function __construct( $options ) {
		global $wgCategoryTreeDefaultOptions;

		// ensure default values and order of options.
		// Order may become important, it may influence the cache key!
		foreach ( $wgCategoryTreeDefaultOptions as $option => $default ) {
			if ( isset( $options[$option] ) ) {
				$this->mOptions[$option] = $options[$option];
			} else {
				$this->mOptions[$option] = $default;
			}
		}

		$this->mOptions['mode'] = self::decodeMode( $this->mOptions['mode'] );

		if ( $this->mOptions['mode'] == CategoryTreeMode::PARENTS ) {
			// namespace filter makes no sense with CategoryTreeMode::PARENTS
			$this->mOptions['namespaces'] = false;
		}

		$this->mOptions['hideprefix'] = self::decodeHidePrefix( $this->mOptions['hideprefix'] );
		$this->mOptions['showcount'] = self::decodeBoolean( $this->mOptions['showcount'] );
		$this->mOptions['namespaces'] = self::decodeNamespaces( $this->mOptions['namespaces'] );

		if ( $this->mOptions['namespaces'] ) {
			# automatically adjust mode to match namespace filter
			if ( count( $this->mOptions['namespaces'] ) === 1
				&& $this->mOptions['namespaces'][0] == NS_CATEGORY ) {
				$this->mOptions['mode'] = CategoryTreeMode::CATEGORIES;
			} elseif ( !in_array( NS_FILE, $this->mOptions['namespaces'] ) ) {
				$this->mOptions['mode'] = CategoryTreeMode::PAGES;
			} else {
				$this->mOptions['mode'] = CategoryTreeMode::ALL;
			}
		}
	}

	/**
	 * @param string $name
	 * @return mixed
	 */
	public function getOption( $name ) {
		return $this->mOptions[$name];
	}

	/**
	 * @return bool
	 */
	private function isInverse() {
		return $this->getOption( 'mode' ) == CategoryTreeMode::PARENTS;
	}

	/**
	 * @param mixed $nn
	 * @return array|bool
	 */
	private static function decodeNamespaces( $nn ) {
		global $wgContLang;

		if ( $nn === false || is_null( $nn ) ) {
			return false;
		}

		if ( !is_array( $nn ) ) {
			$nn = preg_split( '![\s#:|]+!', $nn );
		}

		$namespaces = [];

		foreach ( $nn as $n ) {
			if ( is_int( $n ) ) {
				$ns = $n;
			} else {
				$n = trim( $n );
				if ( $n === '' ) {
					continue;
				}

				$lower = strtolower( $n );

				if ( is_numeric( $n ) ) {
					$ns = (int)$n;
				} elseif ( $n == '-' || $n == '_' || $n == '*' || $lower == 'main' ) {
					$ns = NS_MAIN;
				} else {
					$ns = $wgContLang->getNsIndex( $n );
				}
			}

			if ( is_int( $ns ) ) {
				$namespaces[] = $ns;
			}
		}

		sort( $namespaces ); # get elements into canonical order
		return $namespaces;
	}

	/**
	 * @param mixed $mode
	 * @return int|string
	 */
	public static function decodeMode( $mode ) {
		global $wgCategoryTreeDefaultOptions;

		if ( is_null( $mode ) ) {
			return $wgCategoryTreeDefaultOptions['mode'];
		}
		if ( is_int( $mode ) ) {
			return $mode;
		}

		$mode = trim( strtolower( $mode ) );

		if ( is_numeric( $mode ) ) {
			return (int)$mode;
		}

		if ( $mode == 'all' ) {
			$mode = CategoryTreeMode::ALL;
		} elseif ( $mode == 'pages' ) {
			$mode = CategoryTreeMode::PAGES;
		} elseif ( $mode == 'categories' || $mode == 'sub' ) {
			$mode = CategoryTreeMode::CATEGORIES;
		} elseif ( $mode == 'parents' || $mode == 'super' || $mode == 'inverse' ) {
			$mode = CategoryTreeMode::PARENTS;
		} elseif ( $mode == 'default' ) {
			$mode = $wgCategoryTreeDefaultOptions['mode'];
		}

		return (int)$mode;
	}

	/**
	 * Helper function to convert a string to a boolean value.
	 * Perhaps make this a global function in MediaWiki proper
	 * @param mixed $value
	 * @return bool|null|string
	 */
	public static function decodeBoolean( $value ) {
		if ( is_null( $value ) ) {
			return null;
		}
		if ( is_bool( $value ) ) {
			return $value;
		}
		if ( is_int( $value ) ) {
			return ( $value > 0 );
		}

		$value = trim( strtolower( $value ) );
		if ( is_numeric( $value ) ) {
			return ( (int)$value > 0 );
		}

		if ( $value == 'yes' || $value == 'y'
			|| $value == 'true' || $value == 't' || $value == 'on'
		) {
			return true;
		} elseif ( $value == 'no' || $value == 'n'
			|| $value == 'false' || $value == 'f' || $value == 'off'
		) {
			return false;
		} elseif ( $value == 'null' || $value == 'default' || $value == 'none' || $value == 'x' ) {
			return null;
		} else {
			return false;
		}
	}

	/**
	 * @param mixed $value
	 * @return int|string
	 */
	public static function decodeHidePrefix( $value ) {
		global $wgCategoryTreeDefaultOptions;

		if ( is_null( $value ) ) {
			return $wgCategoryTreeDefaultOptions['hideprefix'];
		}
		if ( is_int( $value ) ) {
			return $value;
		}
		if ( $value === true ) {
			return CategoryTreeHidePrefix::ALWAYS;
		}
		if ( $value === false ) {
			return CategoryTreeHidePrefix::NEVER;
		}

		$value = trim( strtolower( $value ) );

		if ( $value == 'yes' || $value == 'y'
			|| $value == 'true' || $value == 't' || $value == 'on'
		) {
			return CategoryTreeHidePrefix::ALWAYS;
		} elseif ( $value == 'no' || $value == 'n'
			|| $value == 'false' || $value == 'f' || $value == 'off'
		) {
			return CategoryTreeHidePrefix::NEVER;
		} elseif ( $value == 'always' ) {
			return CategoryTreeHidePrefix::ALWAYS;
		} elseif ( $value == 'never' ) {
			return CategoryTreeHidePrefix::NEVER;
		} elseif ( $value == 'auto' ) {
			return CategoryTreeHidePrefix::AUTO;
		} elseif ( $value == 'categories' || $value == 'category' || $value == 'smart' ) {
			return CategoryTreeHidePrefix::CATEGORIES;
		} else {
			return $wgCategoryTreeDefaultOptions['hideprefix'];
		}
	}

	/**
	 * Add ResourceLoader modules to the OutputPage object
	 * @param OutputPage $outputPage
	 */
	public static function setHeaders( $outputPage ) {
		# Add the modules
		$outputPage->addModuleStyles( 'ext.categoryTree.css' );
		$outputPage->addModules( 'ext.categoryTree' );
	}

	/**
	 * @param array $options
	 * @param string $enc
	 * @return mixed
	 * @throws Exception
	 */
	protected static function encodeOptions( $options, $enc ) {
		if ( $enc == 'mode' || $enc == '' ) {
			$opt = $options['mode'];
		} elseif ( $enc == 'json' ) {
			$opt = FormatJson::encode( $options );
		} else {
			throw new Exception( 'Unknown encoding for CategoryTree options: ' . $enc );
		}

		return $opt;
	}

	/**
	 * @param string|null $depth
	 * @return string
	 */
	public function getOptionsAsCacheKey( $depth = null ) {
		$key = "";

		foreach ( $this->mOptions as $k => $v ) {
			if ( is_array( $v ) ) {
				$v = implode( '|', $v );
			}
			$key .= $k . ':' . $v . ';';
		}

		if ( !is_null( $depth ) ) {
			$key .= ";depth=" . $depth;
		}
		return $key;
	}

	/**
	 * @param int|null $depth
	 * @return mixed
	 */
	public function getOptionsAsJsStructure( $depth = null ) {
		if ( $depth !== null ) {
			$opt = $this->mOptions;
			$opt['depth'] = $depth;
			$s = self::encodeOptions( $opt, 'json' );
		} else {
			$s = self::encodeOptions( $this->mOptions, 'json' );
		}

		return $s;
	}

	/**
	 * @return string
	 */
	private function getOptionsAsUrlParameters() {
		return http_build_query( $this->mOptions );
	}

	/**
	 * Custom tag implementation. This is called by CategoryTreeHooks::parserHook, which is used to
	 * load CategoryTreeFunctions.php on demand.
	 * @param Parser $parser
	 * @param string $category
	 * @param bool $hideroot
	 * @param array $attr
	 * @param int $depth
	 * @param bool $allowMissing
	 * @return bool|string
	 */
	public function getTag( $parser, $category, $hideroot = false, $attr = [], $depth = 1,
		$allowMissing = false
	) {
		global $wgCategoryTreeDisableCache;

		$category = trim( $category );
		if ( $category === '' ) {
			return false;
		}

		if ( $parser ) {
			if ( $wgCategoryTreeDisableCache === true ) {
				$parser->disableCache();
			} elseif ( is_int( $wgCategoryTreeDisableCache ) ) {
				$parser->getOutput()->updateCacheExpiry( $wgCategoryTreeDisableCache );
			}
		}

		$title = self::makeTitle( $category );

		if ( $title === false || $title === null ) {
			return false;
		}

		if ( isset( $attr['class'] ) ) {
			$attr['class'] .= ' CategoryTreeTag';
		} else {
			$attr['class'] = ' CategoryTreeTag';
		}

		$attr['data-ct-mode'] = $this->mOptions['mode'];
		$attr['data-ct-options'] = $this->getOptionsAsJsStructure();

		$html = '';
		$html .= Html::openElement( 'div', $attr );

		if ( !$allowMissing && !$title->getArticleID() ) {
			$html .= Html::openElement( 'span', [ 'class' => 'CategoryTreeNotice' ] );
			if ( $parser ) {
				$html .= $parser->recursiveTagParse(
					wfMessage( 'categorytree-not-found', $category )->plain() );
			} else {
				$html .= wfMessage( 'categorytree-not-found', $category )->parse();
			}
			$html .= Html::closeElement( 'span' );
		} else {
			if ( !$hideroot ) {
				$html .= $this->renderNode( $title, $depth );
			} else {
				$html .= $this->renderChildren( $title, $depth );
			}
		}

		$html .= Xml::closeElement( 'div' );
		$html .= "\n\t\t";

		return $html;
	}

	/**
	 * Returns a string with an HTML representation of the children of the given category.
	 * @param Title $title
	 * @param int $depth
	 * @return string
	 */
	public function renderChildren( $title, $depth = 1 ) {
		global $wgCategoryTreeMaxChildren, $wgCategoryTreeUseCategoryTable;

		if ( $title->getNamespace() != NS_CATEGORY ) {
			// Non-categories can't have children. :)
			return '';
		}

		$dbr = wfGetDB( DB_REPLICA );

		$inverse = $this->isInverse();
		$mode = $this->getOption( 'mode' );
		$namespaces = $this->getOption( 'namespaces' );

		$tables = [ 'page', 'categorylinks' ];
		$fields = [ 'page_id', 'page_namespace', 'page_title',
			'page_is_redirect', 'page_len', 'page_latest', 'cl_to',
			'cl_from' ];
		$where = [];
		$joins = [];
		$options = [ 'ORDER BY' => 'cl_type, cl_sortkey', 'LIMIT' => $wgCategoryTreeMaxChildren ];

		if ( $inverse ) {
			$joins['categorylinks'] = [ 'RIGHT JOIN', [
				'cl_to = page_title', 'page_namespace' => NS_CATEGORY
			] ];
			$where['cl_from'] = $title->getArticleID();
		} else {
			$joins['categorylinks'] = [ 'JOIN', 'cl_from = page_id' ];
			$where['cl_to'] = $title->getDBkey();
			$options['USE INDEX']['categorylinks'] = 'cl_sortkey';

			# namespace filter.
			if ( $namespaces ) {
				// NOTE: we assume that the $namespaces array contains only integers!
				// decodeNamepsaces makes it so.
				$where['page_namespace'] = $namespaces;
			} elseif ( $mode != CategoryTreeMode::ALL ) {
				if ( $mode == CategoryTreeMode::PAGES ) {
					$where['cl_type'] = [ 'page', 'subcat' ];
				} else {
					$where['cl_type'] = 'subcat';
				}
			}
		}

		# fetch member count if possible
		$doCount = !$inverse && $wgCategoryTreeUseCategoryTable;

		if ( $doCount ) {
			$tables = array_merge( $tables, [ 'category' ] );
			$fields = array_merge( $fields, [
				'cat_id', 'cat_title', 'cat_subcats', 'cat_pages', 'cat_files'
			] );
			$joins['category'] = [ 'LEFT JOIN', [
				'cat_title = page_title', 'page_namespace' => NS_CATEGORY ]
			];
		}

		$res = $dbr->select( $tables, $fields, $where, __METHOD__, $options, $joins );

		# collect categories separately from other pages
		$categories = '';
		$other = '';

		foreach ( $res as $row ) {
			# NOTE: in inverse mode, the page record may be null, because we use a right join.
			#      happens for categories with no category page (red cat links)
			if ( $inverse && $row->page_title === null ) {
				$t = Title::makeTitle( NS_CATEGORY, $row->cl_to );
			} else {
				# TODO: translation support; ideally added to Title object
				$t = Title::newFromRow( $row );
			}

			$cat = null;

			if ( $doCount && $row->page_namespace == NS_CATEGORY ) {
				$cat = Category::newFromRow( $row, $t );
			}

			$s = $this->renderNodeInfo( $t, $cat, $depth - 1 );
			$s .= "\n\t\t";

			if ( $row->page_namespace == NS_CATEGORY ) {
				$categories .= $s;
			} else {
				$other .= $s;
			}
		}

		return $categories . $other;
	}

	/**
	 * Returns a string with an HTML representation of the parents of the given category.
	 * @param Title $title
	 * @return string
	 */
	public function renderParents( $title ) {
		global $wgCategoryTreeMaxChildren;

		$dbr = wfGetDB( DB_REPLICA );

		$res = $dbr->select(
			'categorylinks',
			[
				'page_namespace' => NS_CATEGORY,
				'page_title' => 'cl_to',
			],
			[ 'cl_from' => $title->getArticleID() ],
			__METHOD__,
			[
				'LIMIT' => $wgCategoryTreeMaxChildren,
				'ORDER BY' => 'cl_to'
			]
		);

		$special = SpecialPage::getTitleFor( 'CategoryTree' );

		$s = '';

		foreach ( $res as $row ) {
			$t = Title::newFromRow( $row );

			$label = $t->getText();

			$wikiLink = $special->getLocalURL( 'target=' . $t->getPartialURL() .
				'&' . $this->getOptionsAsUrlParameters() );

			if ( $s !== '' ) {
				$s .= wfMessage( 'pipe-separator' )->escaped();
			}

			$s .= Xml::openElement( 'span', [ 'class' => 'CategoryTreeItem' ] );
			$s .= Xml::element( 'a', [ 'class' => 'CategoryTreeLabel', 'href' => $wikiLink ], $label );
			$s .= Xml::closeElement( 'span' );

			$s .= "\n\t\t";
		}

		return $s;
	}

	/**
	 * Returns a string with a HTML represenation of the given page.
	 * @param Title $title
	 * @param int $children
	 * @return string
	 */
	public function renderNode( $title, $children = 0 ) {
		global $wgCategoryTreeUseCategoryTable;

		if ( $wgCategoryTreeUseCategoryTable && $title->getNamespace() == NS_CATEGORY
			&& !$this->isInverse()
		) {
			$cat = Category::newFromTitle( $title );
		} else {
			$cat = null;
		}

		return $this->renderNodeInfo( $title, $cat, $children );
	}

	/**
	 * Returns a string with a HTML represenation of the given page.
	 * $info must be an associative array, containing at least a Title object under the 'title' key.
	 * @param Title $title
	 * @param Category $cat
	 * @param int $children
	 * @return string
	 */
	public function renderNodeInfo( $title, $cat, $children = 0 ) {
		$mode = $this->getOption( 'mode' );

		$ns = $title->getNamespace();
		$key = $title->getDBkey();

		$hideprefix = $this->getOption( 'hideprefix' );

		if ( $hideprefix == CategoryTreeHidePrefix::ALWAYS ) {
			$hideprefix = true;
		} elseif ( $hideprefix == CategoryTreeHidePrefix::AUTO ) {
			$hideprefix = ( $mode == CategoryTreeMode::CATEGORIES );
		} elseif ( $hideprefix == CategoryTreeHidePrefix::CATEGORIES ) {
			$hideprefix = ( $ns == NS_CATEGORY );
		} else {
			$hideprefix = true;
		}

		// when showing only categories, omit namespace in label unless we explicitely defined the
		// configuration setting
		// patch contributed by Manuel Schneider <manuel.schneider@wikimedia.ch>, Bug 8011
		if ( $hideprefix ) {
			$label = $title->getText();
		} else {
			$label = $title->getPrefixedText();
		}

		$labelClass = 'CategoryTreeLabel ' . ' CategoryTreeLabelNs' . $ns;

		if ( !$title->getArticleID() ) {
			$labelClass .= ' new';
			$wikiLink = $title->getLocalURL( 'action=edit&redlink=1' );
		} else {
			$wikiLink = $title->getLocalURL();
		}

		if ( $ns == NS_CATEGORY ) {
			$labelClass .= ' CategoryTreeLabelCategory';
		} else {
			$labelClass .= ' CategoryTreeLabelPage';
		}

		if ( ( $ns % 2 ) > 0 ) {
			$labelClass .= ' CategoryTreeLabelTalk';
		}

		$count = false;
		$s = '';

		# NOTE: things in CategoryTree.js rely on the exact order of tags!
		#      Specifically, the CategoryTreeChildren div must be the first
		#      sibling with nodeName = DIV of the grandparent of the expland link.

		$s .= Xml::openElement( 'div', [ 'class' => 'CategoryTreeSection' ] );
		$s .= Xml::openElement( 'div', [ 'class' => 'CategoryTreeItem' ] );

		$attr = [ 'class' => 'CategoryTreeBullet' ];

		if ( $ns == NS_CATEGORY ) {
			if ( $cat ) {
				if ( $mode == CategoryTreeMode::CATEGORIES ) {
					$count = intval( $cat->getSubcatCount() );
				} elseif ( $mode == CategoryTreeMode::PAGES ) {
					$count = intval( $cat->getPageCount() ) - intval( $cat->getFileCount() );
				} else {
					$count = intval( $cat->getPageCount() );
				}
			}
			if ( $count === 0 ) {
				$bullet = wfMessage( 'categorytree-empty-bullet' )->escaped() . ' ';
				$attr['class'] = 'CategoryTreeEmptyBullet';
			} else {
				$linkattr = [];

				$linkattr[ 'class' ] = "CategoryTreeToggle";
				$linkattr['data-ct-title'] = $key;

				$tag = 'span';
				if ( $children == 0 ) {
					// Use ->plain() and htmlspecialchars() to ensure
					// identical to what is done by JS, which does:
					// $link.text( mw.msg( 'categorytree-expand-bullet' ) )
					$txt = htmlspecialchars( wfMessage( 'categorytree-expand-bullet' )->plain() );
					$linkattr[ 'data-ct-state' ] = 'collapsed';
				} else {
					$txt = htmlspecialchars( wfMessage( 'categorytree-collapse-bullet' )->plain() );
					$linkattr[ 'data-ct-loaded' ] = true;
					$linkattr[ 'data-ct-state' ] = 'expanded';
				}

				$bullet = Xml::openElement( $tag, $linkattr ) . $txt . Xml::closeElement( $tag ) . ' ';
			}
		} else {
			$bullet = wfMessage( 'categorytree-page-bullet' )->escaped();
		}
		$s .= Xml::tags( 'span', $attr, $bullet ) . ' ';

		$s .= Xml::element(
			'a',
			[
				'class' => $labelClass,
				'href' => $wikiLink,
				'title' => $title->getPrefixedText()
			],
			$label
		);

		if ( $count !== false && $this->getOption( 'showcount' ) ) {
			$s .= self::createCountString( RequestContext::getMain(), $cat, $count );
		}

		$s .= Xml::closeElement( 'div' );
		$s .= "\n\t\t";
		$s .= Xml::openElement(
			'div',
			[
				'class' => 'CategoryTreeChildren',
				'style' => $children > 0 ? "display:block" : "display:none"
			]
		);

		if ( $ns == NS_CATEGORY && $children > 0 ) {
			$children = $this->renderChildren( $title, $children );
			if ( $children == '' ) {
				$s .= Xml::openElement( 'i', [ 'class' => 'CategoryTreeNotice' ] );
				if ( $mode == CategoryTreeMode::CATEGORIES ) {
					$s .= wfMessage( 'categorytree-no-subcategories' )->escaped();
				} elseif ( $mode == CategoryTreeMode::PAGES ) {
					$s .= wfMessage( 'categorytree-no-pages' )->escaped();
				} elseif ( $mode == CategoryTreeMode::PARENTS ) {
					$s .= wfMessage( 'categorytree-no-parent-categories' )->escaped();
				} else {
					$s .= wfMessage( 'categorytree-nothing-found' )->escaped();
				}
				$s .= Xml::closeElement( 'i' );
			} else {
				$s .= $children;
			}
		}

		$s .= Xml::closeElement( 'div' );
		$s .= Xml::closeElement( 'div' );

		$s .= "\n\t\t";

		return $s;
	}

	/**
	 * Create a string which format the page, subcat and file counts of a category
	 * @param IContextSource $context
	 * @param Category|null $cat
	 * @param int $countMode
	 * @return string
	 */
	public static function createCountString( IContextSource $context, $cat, $countMode ) {
		global $wgContLang;

		# Get counts, with conversion to integer so === works
		# Note: $allCount is the total number of cat members,
		# not the count of how many members are normal pages.
		$allCount = $cat ? intval( $cat->getPageCount() ) : 0;
		$subcatCount = $cat ? intval( $cat->getSubcatCount() ) : 0;
		$fileCount = $cat ? intval( $cat->getFileCount() ) : 0;
		$pages = $allCount - $subcatCount - $fileCount;

		$attr = [
			'title' => $context->msg( 'categorytree-member-counts' )
				->numParams( $subcatCount, $pages, $fileCount, $allCount, $countMode )->text(),
			'dir' => $context->getLanguage()->getDir() # numbers and commas get messed up in a mixed dir env
		];

		$s = $wgContLang->getDirMark() . ' ';

		# Create a list of category members with only non-zero member counts
		$memberNums = [];
		if ( $subcatCount ) {
			$memberNums[] = $context->msg( 'categorytree-num-categories' )
				->numParams( $subcatCount )->text();
		}
		if ( $pages ) {
			$memberNums[] = $context->msg( 'categorytree-num-pages' )->numParams( $pages )->text();
		}
		if ( $fileCount ) {
			$memberNums[] = $context->msg( 'categorytree-num-files' )
				->numParams( $fileCount )->text();
		}
		$memberNumsShort = $memberNums
			? $context->getLanguage()->commaList( $memberNums )
			: $context->msg( 'categorytree-num-empty' )->text();

		# Only $5 is actually used in the default message.
		# Other arguments can be used in a customized message.
		$s .= Xml::tags(
			'span',
			$attr,
			$context->msg( 'categorytree-member-num' )
				// Do not use numParams on params 1-4, as they are only used for customisation.
				->params( $subcatCount, $pages, $fileCount, $allCount, $memberNumsShort )
				->escaped()
		);

		return $s;
	}

	/**
	 * Creates a Title object from a user provided (and thus unsafe) string
	 * @param string $title
	 * @return null|Title
	 */
	public static function makeTitle( $title ) {
		$title = trim( $title );

		if ( strval( $title ) === '' ) {
			return null;
		}

		# The title must be in the category namespace
		# Ignore a leading Category: if there is one
		$t = Title::newFromText( $title, NS_CATEGORY );
		if ( !$t || $t->getNamespace() != NS_CATEGORY || $t->getInterwiki() != '' ) {
			// If we were given something like "Wikipedia:Foo" or "Template:",
			// try it again but forced.
			$title = "Category:$title";
			$t = Title::newFromText( $title );
		}
		return $t;
	}

	/**
	 * Internal function to cap depth
	 * @param string $mode
	 * @param int $depth
	 * @return int|mixed
	 */
	public static function capDepth( $mode, $depth ) {
		global $wgCategoryTreeMaxDepth;

		if ( is_numeric( $depth ) ) {
			$depth = intval( $depth );
		} else {
			return 1;
		}

		if ( is_array( $wgCategoryTreeMaxDepth ) ) {
			$max = isset( $wgCategoryTreeMaxDepth[$mode] ) ? $wgCategoryTreeMaxDepth[$mode] : 1;
		} elseif ( is_numeric( $wgCategoryTreeMaxDepth ) ) {
			$max = $wgCategoryTreeMaxDepth;
		} else {
			wfDebug( 'CategoryTree::capDepth: $wgCategoryTreeMaxDepth is invalid.' );
			$max = 1;
		}

		return min( $depth, $max );
	}
}