Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 68
0.00% covered (danger)
0.00%
0 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiCategoryTree
0.00% covered (danger)
0.00%
0 / 68
0.00% covered (danger)
0.00%
0 / 7
380
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
 execute
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 extractOptions
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
72
 getConditionalRequestData
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 getHTML
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
6
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 isInternal
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3/**
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
18 */
19
20namespace MediaWiki\Extension\CategoryTree;
21
22use MediaWiki\Api\ApiBase;
23use MediaWiki\Api\ApiMain;
24use MediaWiki\Json\FormatJson;
25use MediaWiki\Language\LanguageConverterFactory;
26use MediaWiki\MainConfigNames;
27use MediaWiki\Title\Title;
28use Wikimedia\ObjectCache\WANObjectCache;
29use Wikimedia\ParamValidator\ParamValidator;
30use Wikimedia\Rdbms\IConnectionProvider;
31
32class ApiCategoryTree extends ApiBase {
33    public function __construct(
34        ApiMain $main,
35        string $action,
36        private readonly CategoryTreeFactory $categoryTreeFactory,
37        private readonly IConnectionProvider $dbProvider,
38        private readonly LanguageConverterFactory $languageConverterFactory,
39        private readonly WANObjectCache $wanCache,
40    ) {
41        parent::__construct( $main, $action );
42    }
43
44    /**
45     * @inheritDoc
46     */
47    public function execute(): void {
48        $params = $this->extractRequestParams();
49
50        $options = $this->extractOptions( $params );
51
52        $title = CategoryTree::makeTitle( $params['category'] );
53        if ( !$title || $title->isExternal() ) {
54            $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['category'] ) ] );
55        }
56
57        $depth = isset( $options['depth'] ) ? (int)$options['depth'] : 1;
58
59        $ct = $this->categoryTreeFactory->newCategoryTree( $options );
60        $depth = $ct->optionManager->capDepth( $depth );
61        $html = $this->getHTML( $ct, $title, $depth );
62
63        $this->getMain()->setCacheMode( 'public' );
64
65        $this->getResult()->addContentValue( $this->getModuleName(), 'html', $html );
66    }
67
68    /**
69     * @param array $params
70     * @return string[]
71     */
72    private function extractOptions( array $params ): array {
73        if ( !isset( $params['options'] ) ) {
74            return [];
75        }
76
77        $options = FormatJson::decode( $params['options'] );
78        if ( !is_object( $options ) ) {
79            $this->dieWithError( 'apierror-categorytree-invalidjson', 'invalidjson' );
80        }
81
82        foreach ( $options as $option => $value ) {
83            if ( is_scalar( $value ) || $value === null ) {
84                continue;
85            }
86            if ( $option === 'namespaces' && is_array( $value ) ) {
87                continue;
88            }
89            $this->dieWithError(
90                [ 'apierror-categorytree-invalidjson-option', $option ], 'invalidjson-option'
91            );
92        }
93
94        return get_object_vars( $options );
95    }
96
97    /** @inheritDoc */
98    public function getConditionalRequestData( $condition ) {
99        if ( $condition === 'last-modified' ) {
100            $params = $this->extractRequestParams();
101            $title = CategoryTree::makeTitle( $params['category'] );
102            return $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
103                ->select( 'page_touched' )
104                ->from( 'page' )
105                ->where( [
106                    'page_namespace' => NS_CATEGORY,
107                    'page_title' => $title->getDBkey(),
108                ] )
109                ->caller( __METHOD__ )
110                ->fetchField();
111        }
112        return null;
113    }
114
115    /**
116     * Get category tree HTML for the given tree, title and depth
117     *
118     * @param CategoryTree $ct
119     * @param Title $title
120     * @param int $depth
121     * @return string HTML
122     */
123    private function getHTML( CategoryTree $ct, Title $title, int $depth ): string {
124        $langConv = $this->languageConverterFactory->getLanguageConverter();
125
126        return $this->wanCache->getWithSetCallback(
127            $this->wanCache->makeKey(
128                'categorytree-html-ajax',
129                md5( $title->getDBkey() ),
130                md5( $ct->optionManager->getOptionsAsCacheKey( $depth ) ),
131                $this->getLanguage()->getCode(),
132                $langConv->getExtraHashOptions(),
133                $this->getConfig()->get( MainConfigNames::RenderHashAppend )
134            ),
135            $this->wanCache::TTL_DAY,
136            static fn () => $ct->renderChildren( $title, $depth ),
137            [
138                'touchedCallback' => function () {
139                    $timestamp = $this->getConditionalRequestData( 'last-modified' );
140
141                    return $timestamp ? wfTimestamp( TS_UNIX, $timestamp ) : null;
142                }
143            ]
144        );
145    }
146
147    /**
148     * @inheritDoc
149     */
150    public function getAllowedParams(): array {
151        return [
152            'category' => [
153                ParamValidator::PARAM_TYPE => 'string',
154                ParamValidator::PARAM_REQUIRED => true,
155            ],
156            'options' => [
157                ParamValidator::PARAM_TYPE => 'string',
158            ],
159        ];
160    }
161
162    /**
163     * @inheritDoc
164     */
165    public function isInternal(): bool {
166        return true;
167    }
168}