Debian Codegraph @

extensions/PageImages/includes/ApiQueryPageImages.php

raw symbols SCIP
1 <?php
2
3 namespace PageImages;
4
5 use MediaWiki\Api\ApiBase;
6 use MediaWiki\Api\ApiQuery;
7 use MediaWiki\Api\ApiQueryBase;
8 use MediaWiki\Page\PageReference;
9 use MediaWiki\Page\PageReferenceValue;
10 use RepoGroup;
11 use Wikimedia\ParamValidator\ParamValidator;
12 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
13
14 /**
15 * Expose image information for a page via a new prop=pageimages API.
16 *
17 * @see https://www.mediawiki.org/wiki/Extension:PageImages#API
18 *
19 * @license WTFPL
20 * @author Max Semenik
21 * @author Ryan Kaldari
22 * @author Yuvi Panda
23 * @author Sam Smith
24 */
25 class ApiQueryPageImages extends ApiQueryBase {
26 /** @var RepoGroup */
27 private $repoGroup;
28
29 /**
30 * @param ApiQuery $query API query module
31 * @param string $moduleName Name of this query module
32 * @param RepoGroup $repoGroup
33 */
34 public function __construct(
35 ApiQuery $query,
36 $moduleName,
37 RepoGroup $repoGroup
38 ) {
39 parent::__construct( $query, $moduleName, 'pi' );
40 $this->repoGroup = $repoGroup;
41 }
42
43 /**
44 * Gets the set of titles to get page images for.
45 *
46 * Note well that the set of titles comprises the set of "good" titles
47 * (see {@see ApiPageSet::getGoodPages}) union the set of "missing"
48 * titles in the File namespace that might correspond to foreign files.
49 * The latter are included because titles in the File namespace are
50 * expected to be found with {@see \RepoGroup::findFile}.
51 *
52 * @return PageReference[] A map of page ID, which will be negative in the case
53 * of missing titles in the File namespace, to PageReference object
54 */
55 protected function getTitles() {
56 $pageSet = $this->getPageSet();
57 $titles = $pageSet->getGoodPages();
58
59 // T98791: We want foreign files to be treated like local files
60 // in #execute, so include the set of missing filespace pages,
61 // which were initially rejected in ApiPageSet#execute.
62 $missingTitles = $pageSet->getMissingTitlesByNamespace();
63 $missingFileTitles = $missingTitles[NS_FILE] ?? [];
64
65 // $titles is a map of ID to title object, which is ideal,
66 // whereas $missingFileTitles is a map of title text to ID.
67 // Do not use array_merge here as it doesn't preserve keys.
68 foreach ( $missingFileTitles as $dbkey => $id ) {
69 $titles[$id] = PageReferenceValue::localReference( NS_FILE, $dbkey );
70 }
71
72 return $titles;
73 }
74
75 /**
76 * Evaluates the parameters, performs the requested retrieval of page images,
77 * and sets up the result
78 */
79 public function execute() {
80 $params = $this->extractRequestParams();
81 $prop = array_flip( $params['prop'] );
82 if ( !count( $prop ) ) {
83 $this->dieWithError(
84 [ 'apierror-paramempty', $this->encodeParamName( 'prop' ) ], 'noprop'
85 );
86 }
87
88 $allTitles = $this->getTitles();
89
90 if ( count( $allTitles ) === 0 ) {
91 return;
92 }
93
94 // Find the offset based on the continue param
95 $offset = 0;
96 if ( isset( $params['continue'] ) ) {
97 // Get the position (not the key) of the 'continue' page within the
98 // array of titles. Set this as the offset.
99 $pageIds = array_keys( $allTitles );
100 $offset = array_search( intval( $params['continue'] ), $pageIds );
101 // If the 'continue' page wasn't found, die with error
102 $this->dieContinueUsageIf( !$offset );
103 }
104
105 $limit = $params['limit'];
106 // Slice the part of the array we want to find images for
107 $titles = array_slice( $allTitles, $offset, $limit, true );
108
109 // Get the next item in the title array and use it to set the continue value
110 $nextItemArray = array_slice( $allTitles, $offset + $limit, 1, true );
111 if ( $nextItemArray ) {
112 $this->setContinueEnumParameter( 'continue', key( $nextItemArray ) );
113 }
114
115 // Find any titles in the file namespace so we can handle those separately
116 $filePageTitles = [];
117 foreach ( $titles as $id => $title ) {
118 if ( $title->getNamespace() === NS_FILE ) {
119 $filePageTitles[$id] = $title;
120 unset( $titles[$id] );
121 }
122 }
123
124 $size = $params['thumbsize'];
125 $lang = $params['langcode'];
126 // Extract page images from the page_props table
127 if ( count( $titles ) > 0 ) {
128 $this->addTables( 'page_props' );
129 $this->addFields( [ 'pp_page', 'pp_propname', 'pp_value' ] );
130 $this->addWhere( [ 'pp_page' => array_keys( $titles ),
131 'pp_propname' => PageImages::getPropNames( $params['license'] ) ] );
132
133 $res = $this->select( __METHOD__ );
134
135 $buffer = [];
136 $propNameAny = PageImages::getPropName( false );
137 foreach ( $res as $row ) {
138 $pageId = $row->pp_page;
139 if ( !array_key_exists( $pageId, $buffer ) || $row->pp_propname === $propNameAny ) {
140 $buffer[$pageId] = $row;
141 }
142 }
143
144 foreach ( $buffer as $pageId => $row ) {
145 $fileName = $row->pp_value;
146 $this->setResultValues( $prop, $pageId, $fileName, $size, $lang );
147 }
148 // End page props image extraction
149 }
150
151 // Extract images from file namespace pages. In this case we just use
152 // the file itself rather than searching for a page_image. (Bug 50252)
153 foreach ( $filePageTitles as $pageId => $title ) {
154 $fileName = $title->getDBkey();
155 $this->setResultValues( $prop, $pageId, $fileName, $size, $lang );
156 }
157 }
158
159 /**
160 * Get the cache mode for the data generated by this module
161 *
162 * @param array $params Ignored parameters
163 * @return string Always returns "public"
164 */
165 public function getCacheMode( $params ) {
166 return 'public';
167 }
168
169 /**
170 * For a given page, set API return values for thumbnail and pageimage as needed
171 *
172 * @param array $prop The prop values from the API request
173 * @param int $pageId The ID of the page
174 * @param string $fileName The name of the file to transform
175 * @param int $size The thumbsize value from the API request
176 * @param string $lang The language code from the API request
177 */
178 protected function setResultValues( array $prop, $pageId, $fileName, $size, $lang ) {
179 $vals = [];
180 if ( isset( $prop['thumbnail'] ) || isset( $prop['original'] ) ) {
181 $file = $this->repoGroup->findFile( $fileName );
182 if ( $file ) {
183 if ( isset( $prop['thumbnail'] ) ) {
184 $thumb = $file->transform( [
185 'width' => $size,
186 'lang' => $lang
187 ] );
188 if ( $thumb && $thumb->getUrl() ) {
189 // You can request a thumb 1000x larger than the original
190 // which (in case of bitmap original) will return a Thumb object
191 // that will lie about its size but have the original as an image.
192 $reportedSize = $thumb->fileIsSource() ? $file : $thumb;
193 $vals['thumbnail'] = [
194 'source' => wfExpandUrl( $thumb->getUrl(), PROTO_CURRENT ),
195 'width' => $reportedSize->getWidth(),
196 'height' => $reportedSize->getHeight(),
197 ];
198 }
199 }
200
201 if ( isset( $prop['original'] ) ) {
202 $originalSize = [
203 'width' => $file->getWidth(),
204 'height' => $file->getHeight()
205 ];
206 if ( $lang ) {
207 $file = $file->transform( [
208 'lang' => $lang,
209 'width' => $originalSize['width'],
210 'height' => $originalSize['height']
211 ] );
212 }
213 $original_url = wfExpandUrl( $file->getUrl(), PROTO_CURRENT );
214
215 $vals['original'] = [
216 'source' => $original_url,
217 'width' => $originalSize['width'],
218 'height' => $originalSize['height']
219 ];
220 }
221 }
222 }
223
224 if ( isset( $prop['name'] ) ) {
225 $vals['pageimage'] = $fileName;
226 }
227
228 $this->getResult()->addValue( [ 'query', 'pages' ], $pageId, $vals );
229 }
230
231 /**
232 * Return an array describing all possible parameters to this module
233 * @return array
234 */
235 public function getAllowedParams() {
236 return [
237 'prop' => [
238 ParamValidator::PARAM_TYPE => [ 'thumbnail', 'name', 'original' ],
239 ParamValidator::PARAM_ISMULTI => true,
240 ParamValidator::PARAM_DEFAULT => 'thumbnail|name',
241 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
242 ],
243 'thumbsize' => [
244 ParamValidator::PARAM_TYPE => 'integer',
245 ParamValidator::PARAM_DEFAULT => 50,
246 ],
247 'limit' => [
248 ParamValidator::PARAM_DEFAULT => 50,
249 ParamValidator::PARAM_TYPE => 'limit',
250 IntegerDef::PARAM_MIN => 1,
251 IntegerDef::PARAM_MAX => 50,
252 IntegerDef::PARAM_MAX2 => 100,
253 ],
254 'license' => [
255 ParamValidator::PARAM_TYPE => [ PageImages::LICENSE_FREE, PageImages::LICENSE_ANY ],
256 ParamValidator::PARAM_ISMULTI => false,
257 ParamValidator::PARAM_DEFAULT => $this->getConfig()->get( 'PageImagesAPIDefaultLicense' ),
258 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
259 ],
260 'continue' => [
261 ParamValidator::PARAM_TYPE => 'integer',
262 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
263 ],
264 'langcode' => [
265 ParamValidator::PARAM_TYPE => 'string',
266 ParamValidator::PARAM_DEFAULT => null
267 ]
268 ];
269 }
270
271 /**
272 * @inheritDoc
273 */
274 protected function getExamplesMessages() {
275 return [
276 'action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100' =>
277 'apihelp-query+pageimages-example-1',
278 ];
279 }
280
281 /**
282 * @see ApiBase::getHelpUrls()
283 * @return string
284 */
285 public function getHelpUrls() {
286 return "https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:PageImages#API";
287 }
288
289 }