Debian Codegraph @

includes/Category/TrackingCategories.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Categories
20 */
21
22 namespace MediaWiki\Category;
23
24 use MediaWiki\Config\ServiceOptions;
25 use MediaWiki\Linker\LinkTarget;
26 use MediaWiki\MainConfigNames;
27 use MediaWiki\Page\PageReference;
28 use MediaWiki\Parser\Parser;
29 use MediaWiki\Registration\ExtensionRegistry;
30 use MediaWiki\Title\NamespaceInfo;
31 use MediaWiki\Title\Title;
32 use MediaWiki\Title\TitleParser;
33 use Psr\Log\LoggerInterface;
34 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
35
36 /**
37 * This class performs some operations related to tracking categories, such as
38 * adding a tracking category to a ParserOutput, and creating a list of all
39 * such categories.
40 * @since 1.29
41 */
42 class TrackingCategories {
43
44 /**
45 * @internal For use by ServiceWiring
46 */
47 public const CONSTRUCTOR_OPTIONS = [
48 MainConfigNames::TrackingCategories,
49 MainConfigNames::EnableMagicLinks,
50 ];
51
52 /** @var ServiceOptions */
53 private $options;
54
55 /** @var NamespaceInfo */
56 private $namespaceInfo;
57
58 /** @var TitleParser */
59 private $titleParser;
60
61 /** @var ExtensionRegistry */
62 private $extensionRegistry;
63
64 /** @var LoggerInterface */
65 private $logger;
66
67 /**
68 * Tracking categories that exist in core
69 */
70 private const CORE_TRACKING_CATEGORIES = [
71 'broken-file-category',
72 'duplicate-args-category',
73 'expansion-depth-exceeded-category',
74 'expensive-parserfunction-category',
75 'hidden-category-category',
76 'index-category',
77 'node-count-exceeded-category',
78 'noindex-category',
79 'nonnumeric-formatnum',
80 'post-expand-template-argument-category',
81 'post-expand-template-inclusion-category',
82 'restricted-displaytitle-ignored',
83 # template-equals-category is unused in MW>=1.39, but the category
84 # can be left around for a major release or so for an easier
85 # transition for anyone who didn't do the cleanup. T91154
86 'template-equals-category',
87 'template-loop-category',
88 'unstrip-depth-category',
89 'unstrip-size-category',
90 'bad-language-code-category',
91 'bad-double-underscore-category',
92 'double-px-category',
93 ];
94
95 /**
96 * @param ServiceOptions $options
97 * @param NamespaceInfo $namespaceInfo
98 * @param TitleParser $titleParser
99 * @param LoggerInterface $logger
100 */
101 public function __construct(
102 ServiceOptions $options,
103 NamespaceInfo $namespaceInfo,
104 TitleParser $titleParser,
105 LoggerInterface $logger
106 ) {
107 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
108 $this->options = $options;
109 $this->namespaceInfo = $namespaceInfo;
110 $this->titleParser = $titleParser;
111 $this->logger = $logger;
112
113 // TODO convert ExtensionRegistry to a service and inject it
114 $this->extensionRegistry = ExtensionRegistry::getInstance();
115 }
116
117 /**
118 * Read the global and extract title objects from the corresponding messages
119 *
120 * TODO consider renaming this method, since this class is retrieved from
121 * MediaWikiServices, resulting in calls like:
122 * MediaWikiServices::getInstance()->getTrackingCategories()->getTrackingCategories()
123 *
124 * @return array[] [ 'msg' => LinkTarget, 'cats' => LinkTarget[] ]
125 * @phan-return array<string,array{msg:LinkTarget,cats:LinkTarget[]}>
126 */
127 public function getTrackingCategories() {
128 $categories = array_merge(
129 self::CORE_TRACKING_CATEGORIES,
130 $this->extensionRegistry->getAttribute( MainConfigNames::TrackingCategories ),
131 $this->options->get( MainConfigNames::TrackingCategories ) // deprecated
132 );
133
134 // Only show magic link tracking categories if they are enabled
135 $enableMagicLinks = $this->options->get( MainConfigNames::EnableMagicLinks );
136 if ( $enableMagicLinks['ISBN'] ) {
137 $categories[] = 'magiclink-tracking-isbn';
138 }
139 if ( $enableMagicLinks['RFC'] ) {
140 $categories[] = 'magiclink-tracking-rfc';
141 }
142 if ( $enableMagicLinks['PMID'] ) {
143 $categories[] = 'magiclink-tracking-pmid';
144 }
145
146 $trackingCategories = [];
147 foreach ( $categories as $catMsg ) {
148 /*
149 * Check if the tracking category varies by namespace
150 * Otherwise only pages in the current namespace will be displayed
151 * If it does vary, show pages considering all namespaces
152 *
153 * TODO replace uses of wfMessage with an injected service once that is available
154 */
155 $msgObj = wfMessage( $catMsg )->inContentLanguage();
156 $allCats = [];
157 $catMsgTitle = $this->titleParser->makeTitleValueSafe( NS_MEDIAWIKI, $catMsg );
158 if ( !$catMsgTitle ) {
159 continue;
160 }
161
162 // Match things like {{NAMESPACE}} and {{NAMESPACENUMBER}}.
163 // False positives are ok, this is just an efficiency shortcut
164 if ( strpos( $msgObj->plain(), '{{' ) !== false ) {
165 $ns = $this->namespaceInfo->getValidNamespaces();
166 foreach ( $ns as $namesp ) {
167 $tempTitle = $this->titleParser->makeTitleValueSafe( $namesp, $catMsg );
168 if ( !$tempTitle ) {
169 continue;
170 }
171 // XXX: should be a better way to convert a TitleValue
172 // to a PageReference!
173 $tempTitle = Title::newFromLinkTarget( $tempTitle );
174 $catName = $msgObj->page( $tempTitle )->text();
175 # Allow tracking categories to be disabled by setting them to "-"
176 if ( $catName !== '-' ) {
177 $catTitle = $this->titleParser->makeTitleValueSafe( NS_CATEGORY, $catName );
178 if ( $catTitle ) {
179 $allCats[] = $catTitle;
180 }
181 }
182 }
183 } else {
184 $catName = $msgObj->text();
185 # Allow tracking categories to be disabled by setting them to "-"
186 if ( $catName !== '-' ) {
187 $catTitle = $this->titleParser->makeTitleValueSafe( NS_CATEGORY, $catName );
188 if ( $catTitle ) {
189 $allCats[] = $catTitle;
190 }
191 }
192 }
193 $trackingCategories[$catMsg] = [
194 'cats' => $allCats,
195 'msg' => $catMsgTitle,
196 ];
197 }
198
199 return $trackingCategories;
200 }
201
202 /**
203 * Resolve a tracking category.
204 * @param string $msg Message key
205 * @param ?PageReference $contextPage Context page title
206 * @return ?LinkTarget the proper category page, or null if
207 * the tracking category is disabled or unsafe
208 * @since 1.38
209 */
210 public function resolveTrackingCategory( string $msg, ?PageReference $contextPage ): ?LinkTarget {
211 if ( !$contextPage ) {
212 $this->logger->debug( "Not adding tracking category $msg to missing page!" );
213 return null;
214 }
215
216 if ( $contextPage->getNamespace() === NS_SPECIAL ) {
217 $this->logger->debug( "Not adding tracking category $msg to special page!" );
218 return null;
219 }
220
221 // Important to parse with correct title (T33469)
222 // TODO replace uses of wfMessage with an injected service once that is available
223 $cat = wfMessage( $msg )
224 ->page( $contextPage )
225 ->inContentLanguage()
226 ->text();
227
228 # Allow tracking categories to be disabled by setting them to "-"
229 if ( $cat === '-' ) {
230 return null;
231 }
232
233 $containerCategory = $this->titleParser->makeTitleValueSafe( NS_CATEGORY, $cat );
234 if ( $containerCategory === null ) {
235 $this->logger->debug( "[[MediaWiki:$msg]] is not a valid title!" );
236 return null;
237 }
238 return $containerCategory;
239 }
240
241 /**
242 * Add a tracking category to a ParserOutput, getting the title from a
243 * system message.
244 *
245 * Any message used with this function should be registered so it will
246 * show up on [[Special:TrackingCategories]]. Core messages should be
247 * added to TrackingCategories::CORE_TRACKING_CATEGORIES, and extensions
248 * should add to "TrackingCategories" in their extension.json.
249 *
250 * @param ContentMetadataCollector $parserOutput The target ParserOutput which will
251 * store the new category
252 * @param string $msg Message key
253 * @param ?PageReference $contextPage Context page title
254 * @return bool Whether the addition was successful
255 * @since 1.38
256 * @see Parser::addTrackingCategory
257 */
258 public function addTrackingCategory(
259 ContentMetadataCollector $parserOutput,
260 string $msg,
261 ?PageReference $contextPage
262 ): bool {
263 $categoryPage = $this->resolveTrackingCategory( $msg, $contextPage );
264 if ( $categoryPage === null ) {
265 return false;
266 }
267 $parserOutput->addCategory( $categoryPage );
268 return true;
269 }
270 }
271
272 /** @deprecated class alias since 1.40 */
273 class_alias( TrackingCategories::class, 'TrackingCategories' );