Debian Codegraph @

extensions/CategoryTree/includes/Hooks.php

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