Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 82
0.00% covered (danger)
0.00%
0 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Hooks
0.00% covered (danger)
0.00%
0 / 82
0.00% covered (danger)
0.00%
0 / 13
1056
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onParserFirstCallInit
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 parserFunction
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 getCategorySidebarBox
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 onSkinBuildSidebar
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 onSkinAfterPortlet
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 parserHook
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 onOutputPageRenderCategoryLink
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 getDataForJs
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 onSpecialTrackingCategories__preprocess
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 onSpecialTrackingCategories__generateCatLink
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 onCategoryViewer__doCategoryQuery
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 onCategoryViewerGenerateLink
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2/**
3 * © 2006-2008 Daniel Kinzler and others
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
25namespace MediaWiki\Extension\CategoryTree;
26
27use MediaWiki\Category\Hook\CategoryViewerGenerateLinkHook;
28use MediaWiki\Config\Config;
29use MediaWiki\Context\IContextSource;
30use MediaWiki\Hook\CategoryViewer__doCategoryQueryHook;
31use MediaWiki\Linker\LinkTarget;
32use MediaWiki\Output\Hook\OutputPageRenderCategoryLinkHook;
33use MediaWiki\Output\OutputPage;
34use MediaWiki\Page\PageReference;
35use MediaWiki\Page\ProperPageIdentity;
36use MediaWiki\Parser\Hook\ParserFirstCallInitHook;
37use MediaWiki\Parser\Parser;
38use MediaWiki\Parser\Sanitizer;
39use MediaWiki\ResourceLoader as RL;
40use MediaWiki\Skin\Hook\SkinBuildSidebarHook;
41use MediaWiki\Skin\Skin;
42use MediaWiki\SpecialPage\SpecialPage;
43use MediaWiki\Specials\Hook\SpecialTrackingCategories__generateCatLinkHook;
44use MediaWiki\Specials\Hook\SpecialTrackingCategories__preprocessHook;
45use MediaWiki\Title\TitleFactory;
46use MediaWiki\Title\TitleFormatter;
47use Wikimedia\Rdbms\IResultWrapper;
48
49/**
50 * Hooks for the CategoryTree extension, an AJAX based gadget
51 * to display the category structure of a wiki
52 */
53class Hooks implements
54    SpecialTrackingCategories__preprocessHook,
55    SpecialTrackingCategories__generateCatLinkHook,
56    SkinBuildSidebarHook,
57    ParserFirstCallInitHook,
58    OutputPageRenderCategoryLinkHook,
59    CategoryViewer__doCategoryQueryHook,
60    CategoryViewerGenerateLinkHook
61{
62    private const PARSE_SOURCE = 'categorytree';
63
64    public function __construct(
65        private readonly CategoryCache $categoryCache,
66        private readonly CategoryTreeFactory $categoryTreeFactory,
67        private readonly Config $config,
68        private readonly TitleFactory $titleFactory,
69        private readonly TitleFormatter $titleFormatter,
70    ) {
71    }
72
73    /**
74     * @param Parser $parser
75     */
76    public function onParserFirstCallInit( $parser ) {
77        if ( !$this->config->get( 'CategoryTreeAllowTag' ) ) {
78            return;
79        }
80        $parser->setHook( 'categorytree', $this->parserHook( ... ) );
81        $parser->setFunctionHook( 'categorytree', $this->parserFunction( ... ) );
82    }
83
84    /**
85     * Entry point for the {{#categorytree}} tag parser function.
86     * This is a wrapper around Hooks::parserHook
87     * @param Parser $parser
88     * @param string $cat
89     * @param string ...$params
90     * @return array|string
91     */
92    public function parserFunction( Parser $parser, string $cat, string ...$params ) {
93        // The first user-supplied parameter is the category name.
94        // On `{{#categorytree:}}` $cat is ''.
95
96        // build associative arguments from flat parameter list
97        $argv = [];
98        foreach ( $params as $p ) {
99            if ( preg_match( '/^\s*(\S.*?)\s*=\s*(.*?)\s*$/', $p, $m ) ) {
100                $k = $m[1];
101                // strip any quotes enclosing the value
102                $v = preg_replace( '/^"\s*(.*?)\s*"$/', '$1', $m[2] );
103            } else {
104                $k = trim( $p );
105                $v = true;
106            }
107
108            $argv[$k] = $v;
109        }
110
111        // now handle just like a <categorytree> tag
112        $html = $this->parserHook( $cat, $argv, $parser );
113        return [ $html, 'noparse' => true, 'isHTML' => true ];
114    }
115
116    /**
117     * Obtain a category sidebar link based on config
118     * @return string|null of link
119     */
120    private function getCategorySidebarBox(): ?string {
121        if ( !$this->config->get( 'CategoryTreeSidebarRoot' ) ) {
122            return null;
123        }
124        return $this->parserHook(
125            $this->config->get( 'CategoryTreeSidebarRoot' ),
126            $this->config->get( 'CategoryTreeSidebarOptions' )
127        );
128    }
129
130    /**
131     * Hook implementation for injecting a category tree into the sidebar.
132     * Only does anything if $wgCategoryTreeSidebarRoot is set to a category name.
133     * @param Skin $skin
134     * @param array &$sidebar
135     */
136    public function onSkinBuildSidebar( $skin, &$sidebar ) {
137        $html = $this->getCategorySidebarBox();
138        if ( $html ) {
139            $sidebar['categorytree-portlet'] = [];
140            CategoryTree::setHeaders( $skin->getOutput() );
141        }
142    }
143
144    /**
145     * Hook implementation for injecting a category tree link into the sidebar.
146     * Only does anything if $wgCategoryTreeSidebarRoot is set to a category name.
147     * @param Skin $skin
148     * @param string $portlet
149     * @param string &$html
150     */
151    public function onSkinAfterPortlet( $skin, $portlet, &$html ) {
152        if ( $portlet === 'categorytree-portlet' ) {
153            $box = $this->getCategorySidebarBox();
154            if ( $box ) {
155                $html .= $box;
156            }
157        }
158    }
159
160    /**
161     * Entry point for the <categorytree> tag parser hook.
162     * This loads CategoryTree and calls CategoryTree::getTag()
163     * @param string|null $cat
164     * @param array $argv
165     * @param Parser|null $parser
166     * @return string
167     */
168    public function parserHook(
169        ?string $cat,
170        array $argv,
171        ?Parser $parser = null
172    ): string {
173        if ( $parser ) {
174            $parserOutput = $parser->getOutput();
175            $parserOutput->addModuleStyles( [ 'ext.categoryTree.styles' ] );
176            $parserOutput->addModules( [ 'ext.categoryTree' ] );
177
178            $disableCache = $this->config->get( 'CategoryTreeDisableCache' );
179            if ( $disableCache === true ) {
180                $parserOutput->updateCacheExpiry( 0, self::PARSE_SOURCE );
181            } elseif ( is_int( $disableCache ) ) {
182                $parserOutput->updateCacheExpiry( $disableCache, self::PARSE_SOURCE );
183            }
184        }
185
186        $ct = $this->categoryTreeFactory->newCategoryTree( $argv );
187
188        $attr = Sanitizer::validateTagAttributes( $argv, 'div' );
189
190        $hideroot = OptionManager::decodeBoolean( $argv['hideroot'] ?? false );
191        $depthArg = (int)( $argv['depth'] ?? 1 );
192
193        $depth = $ct->optionManager->capDepth( $depthArg );
194
195        return $ct->getTag( $cat ?? '', $hideroot, $attr, $depth );
196    }
197
198    /**
199     * OutputPageRenderCategoryLink hook
200     * @param OutputPage $outputPage
201     * @param ProperPageIdentity $categoryTitle
202     * @param string $text
203     * @param ?string &$link
204     */
205    public function onOutputPageRenderCategoryLink(
206        OutputPage $outputPage,
207        ProperPageIdentity $categoryTitle,
208        string $text,
209        ?string &$link
210    ): void {
211        if ( !$this->config->get( 'CategoryTreeHijackPageCategories' ) ) {
212            // Not enabled, don't do anything
213            return;
214        }
215        if ( !$categoryTitle->exists() ) {
216            // Category doesn't exist. Let the normal LinkRenderer generate the link.
217            return;
218        }
219
220        CategoryTree::setHeaders( $outputPage );
221
222        $options = $this->config->get( 'CategoryTreePageCategoryOptions' );
223        $link = $this->parserHook(
224            $this->titleFormatter->getPrefixedText( $categoryTitle ),
225            $options
226        );
227    }
228
229    /**
230     * Get exported data for the "ext.categoryTree" ResourceLoader module.
231     *
232     * @internal For use in extension.json only.
233     * @param RL\Context $context
234     * @param Config $config
235     * @return array Data to be serialised as data.json
236     */
237    public static function getDataForJs( RL\Context $context, Config $config ): array {
238        // Look, this is pretty bad but CategoryTree is just whacky, it needs to be rewritten
239        $optionManager = new OptionManager( $config->get( 'CategoryTreeCategoryPageOptions' ), $config );
240
241        return [
242            'defaultCtOptions' => $optionManager->getOptionsAsJsStructure(),
243        ];
244    }
245
246    /**
247     * Hook handler for the SpecialTrackingCategories::preprocess hook
248     * @param SpecialPage $specialPage SpecialTrackingCategories object
249     * @param array $trackingCategories [ 'msg' => LinkTarget, 'cats' => LinkTarget[] ]
250     * @phan-param array<string,array{msg:LinkTarget,cats:LinkTarget[]}> $trackingCategories
251     */
252    public function onSpecialTrackingCategories__preprocess(
253        $specialPage,
254        $trackingCategories
255    ) {
256        $categoryTargets = [];
257        foreach ( $trackingCategories as $data ) {
258            foreach ( $data['cats'] as $catTitle ) {
259                $categoryTargets[] = $catTitle;
260            }
261        }
262        $this->categoryCache->doQuery( $categoryTargets );
263    }
264
265    /**
266     * Hook handler for the SpecialTrackingCategories::generateCatLink hook
267     * @param SpecialPage $specialPage SpecialTrackingCategories object
268     * @param LinkTarget $catTitle LinkTarget object of the linked category
269     * @param string &$html Result html
270     */
271    public function onSpecialTrackingCategories__generateCatLink( $specialPage,
272        $catTitle, &$html
273    ) {
274        $cat = $this->categoryCache->getCategory( $catTitle );
275
276        $html .= CategoryTree::createCountString( $specialPage->getContext(), $cat, 0 );
277    }
278
279    /**
280     * @param string $type
281     * @param IResultWrapper $res
282     */
283    public function onCategoryViewer__doCategoryQuery( $type, $res ) {
284        if ( $type === 'subcat' ) {
285            $this->categoryCache->fillFromQuery( $res );
286        }
287    }
288
289    /**
290     * @param IContextSource $context
291     * @param string $type
292     * @param PageReference $page
293     * @param string|null $html
294     * @param string|null &$link
295     * @return bool
296     */
297    public function onCategoryViewerGenerateLink(
298        IContextSource $context,
299        string $type,
300        PageReference $page,
301        ?string $html,
302        ?string &$link,
303    ) {
304        if ( $type !== 'subcat' || $link !== null ) {
305            return true;
306        }
307
308        $request = $context->getRequest();
309        if ( $request->getCheck( 'notree' ) ) {
310            return true;
311        }
312
313        $options = $this->config->get( 'CategoryTreeCategoryPageOptions' );
314        $mode = $request->getRawVal( 'mode' );
315        if ( $mode !== null ) {
316            $options['mode'] = $mode;
317        }
318        $tree = $this->categoryTreeFactory->newCategoryTree( $options );
319
320        $title = $this->titleFactory->newFromPageReference( $page );
321        $cat = $this->categoryCache->getCategory( $title );
322
323        $link = $tree->renderNodeInfo( $title, $cat );
324
325        CategoryTree::setHeaders( $context->getOutput() );
326        return false;
327    }
328}