Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
7.46% covered (danger)
7.46%
5 / 67
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
TrackingCategories
7.46% covered (danger)
7.46%
5 / 67
25.00% covered (danger)
25.00%
1 / 4
336.96
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getTrackingCategories
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
156
 resolveTrackingCategory
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 addTrackingCategory
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
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
22namespace MediaWiki\Category;
23
24use MediaWiki\Config\ServiceOptions;
25use MediaWiki\Linker\LinkTarget;
26use MediaWiki\MainConfigNames;
27use MediaWiki\Page\PageReference;
28use MediaWiki\Parser\Parser;
29use MediaWiki\Registration\ExtensionRegistry;
30use MediaWiki\Title\NamespaceInfo;
31use MediaWiki\Title\Title;
32use MediaWiki\Title\TitleParser;
33use Psr\Log\LoggerInterface;
34use 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 */
42class 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        'double-px-category',
92    ];
93
94    public function __construct(
95        ServiceOptions $options,
96        NamespaceInfo $namespaceInfo,
97        TitleParser $titleParser,
98        LoggerInterface $logger
99    ) {
100        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
101        $this->options = $options;
102        $this->namespaceInfo = $namespaceInfo;
103        $this->titleParser = $titleParser;
104        $this->logger = $logger;
105
106        // TODO convert ExtensionRegistry to a service and inject it
107        $this->extensionRegistry = ExtensionRegistry::getInstance();
108    }
109
110    /**
111     * Read the global and extract title objects from the corresponding messages
112     *
113     * TODO consider renaming this method, since this class is retrieved from
114     * MediaWikiServices, resulting in calls like:
115     * MediaWikiServices::getInstance()->getTrackingCategories()->getTrackingCategories()
116     *
117     * @return array[] [ 'msg' => LinkTarget, 'cats' => LinkTarget[] ]
118     * @phan-return array<string,array{msg:LinkTarget,cats:LinkTarget[]}>
119     */
120    public function getTrackingCategories() {
121        $categories = array_merge(
122            self::CORE_TRACKING_CATEGORIES,
123            $this->extensionRegistry->getAttribute( MainConfigNames::TrackingCategories ),
124            $this->options->get( MainConfigNames::TrackingCategories ) // deprecated
125        );
126
127        // Only show magic link tracking categories if they are enabled
128        $enableMagicLinks = $this->options->get( MainConfigNames::EnableMagicLinks );
129        if ( $enableMagicLinks['ISBN'] ) {
130            $categories[] = 'magiclink-tracking-isbn';
131        }
132        if ( $enableMagicLinks['RFC'] ) {
133            $categories[] = 'magiclink-tracking-rfc';
134        }
135        if ( $enableMagicLinks['PMID'] ) {
136            $categories[] = 'magiclink-tracking-pmid';
137        }
138
139        $trackingCategories = [];
140        foreach ( $categories as $catMsg ) {
141            /*
142             * Check if the tracking category varies by namespace
143             * Otherwise only pages in the current namespace will be displayed
144             * If it does vary, show pages considering all namespaces
145             *
146             * TODO replace uses of wfMessage with an injected service once that is available
147             */
148            $msgObj = wfMessage( $catMsg )->inContentLanguage();
149            $allCats = [];
150            $catMsgTitle = $this->titleParser->makeTitleValueSafe( NS_MEDIAWIKI, $catMsg );
151            if ( !$catMsgTitle ) {
152                continue;
153            }
154
155            // Match things like {{NAMESPACE}} and {{NAMESPACENUMBER}}.
156            // False positives are ok, this is just an efficiency shortcut
157            if ( str_contains( $msgObj->plain(), '{{' ) ) {
158                $ns = $this->namespaceInfo->getValidNamespaces();
159                foreach ( $ns as $namesp ) {
160                    $tempTitle = $this->titleParser->makeTitleValueSafe( $namesp, $catMsg );
161                    if ( !$tempTitle ) {
162                        continue;
163                    }
164                    // XXX: should be a better way to convert a TitleValue
165                    // to a PageReference!
166                    $tempTitle = Title::newFromLinkTarget( $tempTitle );
167                    $allCats[] = $msgObj->page( $tempTitle )->text();
168                }
169            } else {
170                $allCats[] = $msgObj->text();
171            }
172            $titles = [];
173            foreach ( $allCats as $catName ) {
174                // Extra check in case a message does fancy stuff with {{#if:… and such
175                if ( $catName !== '-' ) {
176                    $catTitle = $this->titleParser->makeTitleValueSafe( NS_CATEGORY, $catName );
177                    if ( $catTitle ) {
178                        $titles[] = $catTitle;
179                    }
180                }
181            }
182            $trackingCategories[$catMsg] = [
183                'cats' => $titles,
184                'msg' => $catMsgTitle,
185            ];
186        }
187
188        return $trackingCategories;
189    }
190
191    /**
192     * Resolve a tracking category.
193     * @param string $msg Message key
194     * @param ?PageReference $contextPage Context page title
195     * @return ?LinkTarget the proper category page, or null if
196     *   the tracking category is disabled or unsafe
197     * @since 1.38
198     */
199    public function resolveTrackingCategory( string $msg, ?PageReference $contextPage ): ?LinkTarget {
200        if ( !$contextPage ) {
201            $this->logger->debug( "Not adding tracking category $msg to missing page!" );
202            return null;
203        }
204
205        if ( $contextPage->getNamespace() === NS_SPECIAL ) {
206            $this->logger->debug( "Not adding tracking category $msg to special page!" );
207            return null;
208        }
209
210        // Important to parse with correct title (T33469)
211        // TODO replace uses of wfMessage with an injected service once that is available
212        $cat = wfMessage( $msg )
213            ->page( $contextPage )
214            ->inContentLanguage()
215            ->text();
216
217        # Allow tracking categories to be disabled by setting them to "-"
218        if ( $cat === '-' ) {
219            return null;
220        }
221
222        $containerCategory = $this->titleParser->makeTitleValueSafe( NS_CATEGORY, $cat );
223        if ( $containerCategory === null ) {
224            $this->logger->debug( "[[MediaWiki:$msg]] is not a valid title!" );
225            return null;
226        }
227        return $containerCategory;
228    }
229
230    /**
231     * Add a tracking category to a ParserOutput, getting the title from a
232     * system message.
233     *
234     * Any message used with this function should be registered so it will
235     * show up on [[Special:TrackingCategories]].  Core messages should be
236     * added to TrackingCategories::CORE_TRACKING_CATEGORIES, and extensions
237     * should add to "TrackingCategories" in their extension.json.
238     *
239     * @param ContentMetadataCollector $parserOutput The target ParserOutput which will
240     *  store the new category
241     * @param string $msg Message key
242     * @param ?PageReference $contextPage Context page title
243     * @return bool Whether the addition was successful
244     * @since 1.38
245     * @see Parser::addTrackingCategory
246     */
247    public function addTrackingCategory(
248        ContentMetadataCollector $parserOutput,
249        string $msg,
250        ?PageReference $contextPage
251    ): bool {
252        $categoryPage = $this->resolveTrackingCategory( $msg, $contextPage );
253        if ( $categoryPage === null ) {
254            return false;
255        }
256        $parserOutput->addCategory( $categoryPage );
257        return true;
258    }
259}