Debian Codegraph @

extensions/Scribunto/includes/Engines/LuaCommon/TitleLibrary.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Scribunto\Engines\LuaCommon;
4
5 use LogicException;
6 use MediaWiki\Content\Content;
7 use MediaWiki\Logger\LoggerFactory;
8 use MediaWiki\MediaWikiServices;
9 use MediaWiki\Parser\ParserOutputFlags;
10 use MediaWiki\Revision\RevisionAccessException;
11 use MediaWiki\Revision\SlotRecord;
12 use MediaWiki\Title\Title;
13
14 class TitleLibrary extends LibraryBase {
15 // Note these caches are naturally limited to
16 // $wgExpensiveParserFunctionLimit + 1 actual Title objects because any
17 // addition besides the one for the current page calls
18 // incrementExpensiveFunctionCount()
19 /** @var Title[] */
20 private $titleCache = [];
21 /** @var (Title|null)[] */
22 private $idCache = [ 0 => null ];
23
24 public function register() {
25 $lib = [
26 'newTitle' => [ $this, 'newTitle' ],
27 'makeTitle' => [ $this, 'makeTitle' ],
28 'getExpensiveData' => [ $this, 'getExpensiveData' ],
29 'getUrl' => [ $this, 'getUrl' ],
30 'getContent' => [ $this, 'getContent' ],
31 'getCategories' => [ $this, 'getCategories' ],
32 'getFileInfo' => [ $this, 'getFileInfo' ],
33 'protectionLevels' => [ $this, 'protectionLevels' ],
34 'cascadingProtection' => [ $this, 'cascadingProtection' ],
35 'redirectTarget' => [ $this, 'redirectTarget' ],
36 'recordVaryFlag' => [ $this, 'recordVaryFlag' ],
37 'getPageLangCode' => [ $this, 'getPageLangCode' ],
38 ];
39 $title = $this->getTitle();
40 return $this->getEngine()->registerInterface( 'mw.title.lua', $lib, [
41 'thisTitle' => $title ? $this->getInexpensiveTitleData( $title ) : null,
42 'NS_MEDIA' => NS_MEDIA,
43 ] );
44 }
45
46 /**
47 * Check a namespace parameter
48 * @param string $name Function name (for errors)
49 * @param int $argIdx Argument index (for errors)
50 * @param mixed &$arg Argument
51 * @param int|null $default Default value, if $arg is null
52 */
53 private function checkNamespace( $name, $argIdx, &$arg, $default = null ) {
54 if ( $arg === null && $default !== null ) {
55 $arg = $default;
56 } elseif ( is_numeric( $arg ) ) {
57 $arg = (int)$arg;
58 if ( !MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $arg ) ) {
59 throw new LuaError(
60 "bad argument #$argIdx to '$name' (unrecognized namespace number '$arg')"
61 );
62 }
63 } elseif ( is_string( $arg ) ) {
64 $ns = MediaWikiServices::getInstance()->getContentLanguage()->getNsIndex( $arg );
65 if ( $ns === false ) {
66 throw new LuaError(
67 "bad argument #$argIdx to '$name' (unrecognized namespace name '$arg')"
68 );
69 }
70 $arg = $ns;
71 } else {
72 $this->checkType( $name, $argIdx, $arg, 'namespace number or name' );
73 }
74 }
75
76 /**
77 * Extract inexpensive information from a Title object for return to Lua
78 *
79 * @param Title $title Title to return
80 * @return array Lua data
81 */
82 private function getInexpensiveTitleData( Title $title ) {
83 $ns = $title->getNamespace();
84 $ret = [
85 'isCurrentTitle' => (bool)$title->equals( $this->getTitle() ),
86 'isLocal' => (bool)$title->isLocal(),
87 'interwiki' => $title->getInterwiki(),
88 'namespace' => $ns,
89 'nsText' => $title->getNsText(),
90 'text' => $title->getText(),
91 'fragment' => $title->getFragment(),
92 'thePartialUrl' => $title->getPartialURL(),
93 ];
94 if ( $ns === NS_SPECIAL ) {
95 // Core doesn't currently record special page links, but it may in the future.
96 if ( $this->getParser() && !$title->equals( $this->getTitle() ) ) {
97 $this->getParser()->getOutput()->addLink( $title );
98 }
99 $ret['exists'] = MediaWikiServices::getInstance()
100 ->getSpecialPageFactory()->exists( $title->getDBkey() );
101 }
102 if ( $ns !== NS_FILE && $ns !== NS_MEDIA ) {
103 $ret['file'] = false;
104 }
105 return $ret;
106 }
107
108 /**
109 * Extract expensive information from a Title object for return to Lua
110 *
111 * This records a link to this title in the current ParserOutput and caches the
112 * title for repeated lookups. It may call incrementExpensiveFunctionCount() if
113 * the title is not already cached.
114 *
115 * @internal
116 * @param string $text Title text
117 * @return array Lua data
118 */
119 public function getExpensiveData( $text ) {
120 $this->checkType( 'getExpensiveData', 1, $text, 'string' );
121 $title = Title::newFromText( $text );
122 if ( !$title ) {
123 return [ null ];
124 }
125 $dbKey = $title->getPrefixedDBkey();
126 if ( isset( $this->titleCache[$dbKey] ) ) {
127 // It was already cached, so we already did the expensive work and added a link
128 $title = $this->titleCache[$dbKey];
129 } else {
130 if ( !$title->equals( $this->getTitle() ) ) {
131 $this->incrementExpensiveFunctionCount();
132
133 // Record a link
134 if ( $this->getParser() ) {
135 $this->getParser()->getOutput()->addLink( $title );
136 }
137 }
138
139 // Cache it
140 $this->titleCache[$dbKey] = $title;
141 if ( $title->getArticleID() > 0 ) {
142 $this->idCache[$title->getArticleID()] = $title;
143 }
144 }
145
146 $ret = [
147 'isRedirect' => (bool)$title->isRedirect(),
148 'id' => $title->getArticleID(),
149 'contentModel' => $title->getContentModel(),
150 ];
151 if ( $title->getNamespace() === NS_SPECIAL ) {
152 $ret['exists'] = MediaWikiServices::getInstance()
153 ->getSpecialPageFactory()->exists( $title->getDBkey() );
154 } else {
155 // bug 70495: don't just check whether the ID != 0
156 $ret['exists'] = $title->exists();
157 }
158 return [ $ret ];
159 }
160
161 /**
162 * Handler for title.new
163 *
164 * Calls Title::newFromID or Title::newFromTitle as appropriate for the
165 * arguments.
166 *
167 * @internal
168 * @param string|int $text_or_id Title or page_id to fetch
169 * @param string|int|null $defaultNamespace Namespace name or number to use if
170 * $text_or_id doesn't override
171 * @return array Lua data
172 */
173 public function newTitle( $text_or_id, $defaultNamespace = null ) {
174 $type = $this->getLuaType( $text_or_id );
175 if ( $type === 'number' ) {
176 if ( array_key_exists( $text_or_id, $this->idCache ) ) {
177 $title = $this->idCache[$text_or_id];
178 } else {
179 $this->incrementExpensiveFunctionCount();
180 $title = Title::newFromID( $text_or_id );
181 $this->idCache[$text_or_id] = $title;
182
183 // Record a link
184 if ( $title && $this->getParser() && !$title->equals( $this->getTitle() ) ) {
185 $this->getParser()->getOutput()->addLink( $title );
186 }
187 }
188 if ( $title ) {
189 $this->titleCache[$title->getPrefixedDBkey()] = $title;
190 } else {
191 return [ null ];
192 }
193 } elseif ( $type === 'string' ) {
194 $this->checkNamespace( 'title.new', 2, $defaultNamespace, NS_MAIN );
195
196 // Note this just fills in the given fields, it doesn't fetch from
197 // the page table.
198 $title = Title::newFromText( $text_or_id, $defaultNamespace );
199 if ( !$title ) {
200 return [ null ];
201 }
202 } else {
203 $this->checkType( 'title.new', 1, $text_or_id, 'number or string' );
204 throw new LogicException( 'checkType above should have failed' );
205 }
206
207 return [ $this->getInexpensiveTitleData( $title ) ];
208 }
209
210 /**
211 * Handler for title.makeTitle
212 *
213 * Calls Title::makeTitleSafe.
214 *
215 * @internal
216 * @param string|int $ns Namespace
217 * @param string $text Title text
218 * @param string|null $fragment URI fragment
219 * @param string|null $interwiki Interwiki code
220 * @return array Lua data
221 */
222 public function makeTitle( $ns, $text, $fragment = null, $interwiki = null ) {
223 $this->checkNamespace( 'makeTitle', 1, $ns );
224 $this->checkType( 'makeTitle', 2, $text, 'string' );
225 $this->checkTypeOptional( 'makeTitle', 3, $fragment, 'string', '' );
226 $this->checkTypeOptional( 'makeTitle', 4, $interwiki, 'string', '' );
227
228 // Note this just fills in the given fields, it doesn't fetch from the
229 // page table.
230 $title = Title::makeTitleSafe( $ns, $text, $fragment, $interwiki );
231 if ( !$title ) {
232 return [ null ];
233 }
234
235 return [ $this->getInexpensiveTitleData( $title ) ];
236 }
237
238 /**
239 * Get a URL referring to this title
240 * @internal
241 * @param string $text Title text.
242 * @param string $which 'fullUrl', 'localUrl', or 'canonicalUrl'
243 * @param string|array|null $query Query string or query string data.
244 * @param string|null $proto 'http', 'https', 'relative', or 'canonical'
245 * @return array
246 */
247 public function getUrl( $text, $which, $query = null, $proto = null ) {
248 static $protoMap = [
249 'http' => PROTO_HTTP,
250 'https' => PROTO_HTTPS,
251 'relative' => PROTO_RELATIVE,
252 'canonical' => PROTO_CANONICAL,
253 ];
254
255 $this->checkType( 'getUrl', 1, $text, 'string' );
256 $this->checkType( 'getUrl', 2, $which, 'string' );
257 if ( !in_array( $which, [ 'fullUrl', 'localUrl', 'canonicalUrl' ], true ) ) {
258 $this->checkType( 'getUrl', 2, $which, "'fullUrl', 'localUrl', or 'canonicalUrl'" );
259 }
260
261 // May call the following Title methods:
262 // getFullUrl, getLocalUrl, getCanonicalUrl
263 $func = "get" . ucfirst( $which );
264
265 $args = [ $query, false ];
266 if ( !is_string( $query ) && !is_array( $query ) ) {
267 $this->checkTypeOptional( $which, 1, $query, 'table or string', '' );
268 }
269 if ( $which === 'fullUrl' ) {
270 $this->checkTypeOptional( $which, 2, $proto, 'string', 'relative' );
271 if ( !isset( $protoMap[$proto] ) ) {
272 $this->checkType( $which, 2, $proto, "'http', 'https', 'relative', or 'canonical'" );
273 }
274 $args[] = $protoMap[$proto];
275 }
276
277 $title = Title::newFromText( $text );
278 if ( !$title ) {
279 return [ null ];
280 }
281 return [ $title->$func( ...$args ) ];
282 }
283
284 /**
285 * Utility to get a Content object from a title
286 *
287 * The title is counted as a transclusion.
288 *
289 * @param string $text Title text
290 * @return Content|null The Content object of the title, null if missing
291 */
292 private function getContentInternal( $text ) {
293 $title = Title::newFromText( $text );
294 if ( !$title || $title->isExternal() ) {
295 return null;
296 }
297
298 if ( MediaWikiServices::getInstance()->getNamespaceInfo()->isNonincludable( $title->getNamespace() ) ) {
299 return null;
300 }
301
302 $rev = $this->getParser()->fetchCurrentRevisionRecordOfTitle( $title );
303
304 if ( $title->equals( $this->getTitle() ) ) {
305 $parserOutput = $this->getParser()->getOutput();
306 $parserOutput->setOutputFlag( ParserOutputFlags::VARY_REVISION_SHA1 );
307 $parserOutput->setRevisionUsedSha1Base36( $rev ? $rev->getSha1() : '' );
308 wfDebug( __METHOD__ . ": set vary-revision-sha1 for '$title'" );
309 } else {
310 // Record in templatelinks, so edits cause the page to be refreshed
311 $this->getParser()->getOutput()->addTemplate(
312 $title, $title->getArticleID(), $title->getLatestRevID()
313 );
314 }
315
316 if ( !$rev ) {
317 return null;
318 }
319
320 try {
321 $content = $rev->getContent( SlotRecord::MAIN );
322 } catch ( RevisionAccessException $ex ) {
323 $logger = LoggerFactory::getInstance( 'Scribunto' );
324 $logger->warning(
325 __METHOD__ . ': Unable to transclude revision content',
326 [ 'exception' => $ex ]
327 );
328 $content = null;
329 }
330 return $content;
331 }
332
333 /**
334 * Handler for getContent
335 * @internal
336 * @param string $text
337 * @return string[]|null[]
338 */
339 public function getContent( $text ) {
340 $this->checkType( 'getContent', 1, $text, 'string' );
341 $content = $this->getContentInternal( $text );
342 return [ $content ? $content->serialize() : null ];
343 }
344
345 /**
346 * @internal
347 * @param string $text
348 * @return string[][]
349 */
350 public function getCategories( $text ) {
351 $this->checkType( 'getCategories', 1, $text, 'string' );
352 $title = Title::newFromText( $text );
353 if ( !$title ) {
354 return [ [] ];
355 }
356 $page = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
357 $this->incrementExpensiveFunctionCount();
358
359 $parserOutput = $this->getParser()->getOutput();
360 if ( $title->equals( $this->getTitle() ) ) {
361 $parserOutput->setOutputFlag( ParserOutputFlags::VARY_REVISION );
362 } else {
363 // Record in templatelinks, so edits cause the page to be refreshed
364 $parserOutput->addTemplate( $title, $title->getArticleID(), $title->getLatestRevID() );
365 }
366
367 $categoryTitles = $page->getCategories();
368 $categoryNames = [];
369 foreach ( $categoryTitles as $title ) {
370 $categoryNames[] = $title->getText();
371 }
372 return [ self::makeArrayOneBased( $categoryNames ) ];
373 }
374
375 /**
376 * Handler for getFileInfo
377 * @internal
378 * @param string $text
379 * @return array
380 */
381 public function getFileInfo( $text ) {
382 $this->checkType( 'getFileInfo', 1, $text, 'string' );
383 $title = Title::newFromText( $text );
384 if ( !$title ) {
385 return [ false ];
386 }
387 $ns = $title->getNamespace();
388 if ( $ns !== NS_FILE && $ns !== NS_MEDIA ) {
389 return [ false ];
390 }
391
392 $this->incrementExpensiveFunctionCount();
393 $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title );
394 if ( !$file ) {
395 return [ [ 'exists' => false ] ];
396 }
397 $this->getParser()->getOutput()->addImage(
398 $file->getName(), $file->getTimestamp(), $file->getSha1()
399 );
400 if ( !$file->exists() ) {
401 return [ [ 'exists' => false ] ];
402 }
403 $pageCount = $file->pageCount();
404 if ( $pageCount === false ) {
405 $pages = null;
406 } else {
407 $pages = [];
408 for ( $i = 1; $i <= $pageCount; ++$i ) {
409 $pages[$i] = [
410 'width' => $file->getWidth( $i ),
411 'height' => $file->getHeight( $i )
412 ];
413 }
414 }
415 return [ [
416 'exists' => true,
417 'width' => $file->getWidth(),
418 'height' => $file->getHeight(),
419 'mimeType' => $file->getMimeType(),
420 'length' => $file->getLength(),
421 'size' => $file->getSize(),
422 'pages' => $pages
423 ] ];
424 }
425
426 /**
427 * Renumber an array for return to Lua
428 * @param array $arr
429 * @return array
430 */
431 private static function makeArrayOneBased( $arr ) {
432 if ( !$arr ) {
433 return $arr;
434 }
435 return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
436 }
437
438 /**
439 * Handler for protectionLevels
440 * @internal
441 * @param string $text
442 * @return array
443 */
444 public function protectionLevels( $text ) {
445 $this->checkType( 'protectionLevels', 1, $text, 'string' );
446 $title = Title::newFromText( $text );
447 if ( !$title ) {
448 return [ null ];
449 }
450
451 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
452
453 if ( !$restrictionStore->areRestrictionsLoaded( $title ) ) {
454 $this->incrementExpensiveFunctionCount();
455 }
456 return [ array_map(
457 [ self::class, 'makeArrayOneBased' ],
458 $restrictionStore->getAllRestrictions( $title )
459 ) ];
460 }
461
462 /**
463 * Handler for cascadingProtection
464 * @internal
465 * @param string $text
466 * @return array
467 */
468 public function cascadingProtection( $text ) {
469 $this->checkType( 'cascadingProtection', 1, $text, 'string' );
470 $title = Title::newFromText( $text );
471 if ( !$title ) {
472 return [ null ];
473 }
474
475 $restrictionStore = MediaWikiServices::getInstance()->getRestrictionStore();
476 $titleFormatter = MediaWikiServices::getInstance()->getTitleFormatter();
477
478 if ( !$restrictionStore->areCascadeProtectionSourcesLoaded( $title ) ) {
479 $this->incrementExpensiveFunctionCount();
480 }
481
482 [ $sources, $restrictions ] = $restrictionStore->getCascadeProtectionSources( $title );
483
484 return [ [
485 'sources' => self::makeArrayOneBased( array_map(
486 static function ( $t ) use ( $titleFormatter ) {
487 return $titleFormatter->getPrefixedText( $t );
488 },
489 $sources ) ),
490 'restrictions' => array_map(
491 [ self::class, 'makeArrayOneBased' ],
492 $restrictions
493 )
494 ] ];
495 }
496
497 /**
498 * Handler for redirectTarget
499 * @internal
500 * @param string $text
501 * @return string[]|null[]
502 */
503 public function redirectTarget( $text ) {
504 $this->checkType( 'redirectTarget', 1, $text, 'string' );
505 $content = $this->getContentInternal( $text );
506 $redirTitle = $content ? $content->getRedirectTarget() : null;
507 return [ $redirTitle ? $this->getInexpensiveTitleData( $redirTitle ) : null ];
508 }
509
510 /**
511 * Record a ParserOutput flag when the current title is accessed
512 * @internal
513 * @param string $text
514 * @param string $flag
515 * @return array
516 */
517 public function recordVaryFlag( $text, $flag ) {
518 $this->checkType( 'recordVaryFlag', 1, $text, 'string' );
519 $this->checkType( 'recordVaryFlag', 2, $flag, 'string' );
520 $title = Title::newFromText( $text );
521 if ( $title && $title->equals( $this->getTitle() ) ) {
522 // XXX note that we don't check this against the values defined
523 // in ParserOutputFlags
524 $this->getParser()->getOutput()->setOutputFlag( $flag );
525 }
526 return [];
527 }
528
529 /**
530 * Handler for getPageLangCode
531 * @internal
532 * @param string $text Title text.
533 * @return array<?string>
534 */
535 public function getPageLangCode( $text ) {
536 $title = Title::newFromText( $text );
537 if ( $title ) {
538 // If the page language is coming from the page record, we've
539 // probably accounted for the cost of reading the title from
540 // the DB already. However, a PageContentLanguage hook handler
541 // might get invoked here, and who knows how much that costs.
542 // Be safe and increment here, even though this could over-count.
543 $this->incrementExpensiveFunctionCount();
544 return [ $title->getPageLanguage()->getCode() ];
545 }
546 return [ null ];
547 }
548 }