ForeignAPIRepo.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. <?php
  2. /**
  3. * Foreign repository accessible through api.php requests.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup FileRepo
  22. */
  23. use MediaWiki\Logger\LoggerFactory;
  24. /**
  25. * A foreign repository with a remote MediaWiki with an API thingy
  26. *
  27. * Example config:
  28. *
  29. * $wgForeignFileRepos[] = [
  30. * 'class' => ForeignAPIRepo::class,
  31. * 'name' => 'shared',
  32. * 'apibase' => 'https://en.wikipedia.org/w/api.php',
  33. * 'fetchDescription' => true, // Optional
  34. * 'descriptionCacheExpiry' => 3600,
  35. * ];
  36. *
  37. * @ingroup FileRepo
  38. */
  39. class ForeignAPIRepo extends FileRepo {
  40. /* This version string is used in the user agent for requests and will help
  41. * server maintainers in identify ForeignAPI usage.
  42. * Update the version every time you make breaking or significant changes. */
  43. const VERSION = "2.1";
  44. /**
  45. * List of iiprop values for the thumbnail fetch queries.
  46. * @since 1.23
  47. */
  48. protected static $imageInfoProps = [
  49. 'url',
  50. 'timestamp',
  51. ];
  52. protected $fileFactory = [ ForeignAPIFile::class, 'newFromTitle' ];
  53. /** @var int Check back with Commons after this expiry */
  54. protected $apiThumbCacheExpiry = 86400; // 1 day (24*3600)
  55. /** @var int Redownload thumbnail files after this expiry */
  56. protected $fileCacheExpiry = 2592000; // 1 month (30*24*3600)
  57. /** @var array */
  58. protected $mFileExists = [];
  59. /** @var string */
  60. private $mApiBase;
  61. /**
  62. * @param array|null $info
  63. */
  64. function __construct( $info ) {
  65. global $wgLocalFileRepo;
  66. parent::__construct( $info );
  67. // https://commons.wikimedia.org/w/api.php
  68. $this->mApiBase = isset( $info['apibase'] ) ? $info['apibase'] : null;
  69. if ( isset( $info['apiThumbCacheExpiry'] ) ) {
  70. $this->apiThumbCacheExpiry = $info['apiThumbCacheExpiry'];
  71. }
  72. if ( isset( $info['fileCacheExpiry'] ) ) {
  73. $this->fileCacheExpiry = $info['fileCacheExpiry'];
  74. }
  75. if ( !$this->scriptDirUrl ) {
  76. // hack for description fetches
  77. $this->scriptDirUrl = dirname( $this->mApiBase );
  78. }
  79. // If we can cache thumbs we can guess sane defaults for these
  80. if ( $this->canCacheThumbs() && !$this->url ) {
  81. $this->url = $wgLocalFileRepo['url'];
  82. }
  83. if ( $this->canCacheThumbs() && !$this->thumbUrl ) {
  84. $this->thumbUrl = $this->url . '/thumb';
  85. }
  86. }
  87. /**
  88. * @return string
  89. * @since 1.22
  90. */
  91. function getApiUrl() {
  92. return $this->mApiBase;
  93. }
  94. /**
  95. * Per docs in FileRepo, this needs to return false if we don't support versioned
  96. * files. Well, we don't.
  97. *
  98. * @param Title $title
  99. * @param string|bool $time
  100. * @return File|false
  101. */
  102. function newFile( $title, $time = false ) {
  103. if ( $time ) {
  104. return false;
  105. }
  106. return parent::newFile( $title, $time );
  107. }
  108. /**
  109. * @param string[] $files
  110. * @return array
  111. */
  112. function fileExistsBatch( array $files ) {
  113. $results = [];
  114. foreach ( $files as $k => $f ) {
  115. if ( isset( $this->mFileExists[$f] ) ) {
  116. $results[$k] = $this->mFileExists[$f];
  117. unset( $files[$k] );
  118. } elseif ( self::isVirtualUrl( $f ) ) {
  119. # @todo FIXME: We need to be able to handle virtual
  120. # URLs better, at least when we know they refer to the
  121. # same repo.
  122. $results[$k] = false;
  123. unset( $files[$k] );
  124. } elseif ( FileBackend::isStoragePath( $f ) ) {
  125. $results[$k] = false;
  126. unset( $files[$k] );
  127. wfWarn( "Got mwstore:// path '$f'." );
  128. }
  129. }
  130. $data = $this->fetchImageQuery( [
  131. 'titles' => implode( '|', $files ),
  132. 'prop' => 'imageinfo' ]
  133. );
  134. if ( isset( $data['query']['pages'] ) ) {
  135. # First, get results from the query. Note we only care whether the image exists,
  136. # not whether it has a description page.
  137. foreach ( $data['query']['pages'] as $p ) {
  138. $this->mFileExists[$p['title']] = ( $p['imagerepository'] !== '' );
  139. }
  140. # Second, copy the results to any redirects that were queried
  141. if ( isset( $data['query']['redirects'] ) ) {
  142. foreach ( $data['query']['redirects'] as $r ) {
  143. $this->mFileExists[$r['from']] = $this->mFileExists[$r['to']];
  144. }
  145. }
  146. # Third, copy the results to any non-normalized titles that were queried
  147. if ( isset( $data['query']['normalized'] ) ) {
  148. foreach ( $data['query']['normalized'] as $n ) {
  149. $this->mFileExists[$n['from']] = $this->mFileExists[$n['to']];
  150. }
  151. }
  152. # Finally, copy the results to the output
  153. foreach ( $files as $key => $file ) {
  154. $results[$key] = $this->mFileExists[$file];
  155. }
  156. }
  157. return $results;
  158. }
  159. /**
  160. * @param string $virtualUrl
  161. * @return false
  162. */
  163. function getFileProps( $virtualUrl ) {
  164. return false;
  165. }
  166. /**
  167. * @param array $query
  168. * @return string
  169. */
  170. function fetchImageQuery( $query ) {
  171. global $wgLanguageCode;
  172. $query = array_merge( $query,
  173. [
  174. 'format' => 'json',
  175. 'action' => 'query',
  176. 'redirects' => 'true'
  177. ] );
  178. if ( !isset( $query['uselang'] ) ) { // uselang is unset or null
  179. $query['uselang'] = $wgLanguageCode;
  180. }
  181. $data = $this->httpGetCached( 'Metadata', $query );
  182. if ( $data ) {
  183. return FormatJson::decode( $data, true );
  184. } else {
  185. return null;
  186. }
  187. }
  188. /**
  189. * @param array $data
  190. * @return bool|array
  191. */
  192. function getImageInfo( $data ) {
  193. if ( $data && isset( $data['query']['pages'] ) ) {
  194. foreach ( $data['query']['pages'] as $info ) {
  195. if ( isset( $info['imageinfo'][0] ) ) {
  196. $return = $info['imageinfo'][0];
  197. if ( isset( $info['pageid'] ) ) {
  198. $return['pageid'] = $info['pageid'];
  199. }
  200. return $return;
  201. }
  202. }
  203. }
  204. return false;
  205. }
  206. /**
  207. * @param string $hash
  208. * @return ForeignAPIFile[]
  209. */
  210. function findBySha1( $hash ) {
  211. $results = $this->fetchImageQuery( [
  212. 'aisha1base36' => $hash,
  213. 'aiprop' => ForeignAPIFile::getProps(),
  214. 'list' => 'allimages',
  215. ] );
  216. $ret = [];
  217. if ( isset( $results['query']['allimages'] ) ) {
  218. foreach ( $results['query']['allimages'] as $img ) {
  219. // 1.14 was broken, doesn't return name attribute
  220. if ( !isset( $img['name'] ) ) {
  221. continue;
  222. }
  223. $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
  224. }
  225. }
  226. return $ret;
  227. }
  228. /**
  229. * @param string $name
  230. * @param int $width
  231. * @param int $height
  232. * @param array|null &$result Output-only parameter, guaranteed to become an array
  233. * @param string $otherParams
  234. *
  235. * @return string|false
  236. */
  237. function getThumbUrl( $name, $width = -1, $height = -1, &$result = null, $otherParams = '' ) {
  238. $data = $this->fetchImageQuery( [
  239. 'titles' => 'File:' . $name,
  240. 'iiprop' => self::getIIProps(),
  241. 'iiurlwidth' => $width,
  242. 'iiurlheight' => $height,
  243. 'iiurlparam' => $otherParams,
  244. 'prop' => 'imageinfo' ] );
  245. $info = $this->getImageInfo( $data );
  246. if ( $data && $info && isset( $info['thumburl'] ) ) {
  247. wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
  248. $result = $info;
  249. return $info['thumburl'];
  250. } else {
  251. return false;
  252. }
  253. }
  254. /**
  255. * @param string $name
  256. * @param int $width
  257. * @param int $height
  258. * @param string $otherParams
  259. * @param string|null $lang Language code for language of error
  260. * @return bool|MediaTransformError
  261. * @since 1.22
  262. */
  263. function getThumbError( $name, $width = -1, $height = -1, $otherParams = '', $lang = null ) {
  264. $data = $this->fetchImageQuery( [
  265. 'titles' => 'File:' . $name,
  266. 'iiprop' => self::getIIProps(),
  267. 'iiurlwidth' => $width,
  268. 'iiurlheight' => $height,
  269. 'iiurlparam' => $otherParams,
  270. 'prop' => 'imageinfo',
  271. 'uselang' => $lang,
  272. ] );
  273. $info = $this->getImageInfo( $data );
  274. if ( $data && $info && isset( $info['thumberror'] ) ) {
  275. wfDebug( __METHOD__ . " got remote thumb error " . $info['thumberror'] . "\n" );
  276. return new MediaTransformError(
  277. 'thumbnail_error_remote',
  278. $width,
  279. $height,
  280. $this->getDisplayName(),
  281. $info['thumberror'] // already parsed message from foreign repo
  282. );
  283. } else {
  284. return false;
  285. }
  286. }
  287. /**
  288. * Return the imageurl from cache if possible
  289. *
  290. * If the url has been requested today, get it from cache
  291. * Otherwise retrieve remote thumb url, check for local file.
  292. *
  293. * @param string $name Is a dbkey form of a title
  294. * @param int $width
  295. * @param int $height
  296. * @param string $params Other rendering parameters (page number, etc)
  297. * from handler's makeParamString.
  298. * @return bool|string
  299. */
  300. function getThumbUrlFromCache( $name, $width, $height, $params = "" ) {
  301. $cache = ObjectCache::getMainWANInstance();
  302. // We can't check the local cache using FileRepo functions because
  303. // we override fileExistsBatch(). We have to use the FileBackend directly.
  304. $backend = $this->getBackend(); // convenience
  305. if ( !$this->canCacheThumbs() ) {
  306. $result = null; // can't pass "null" by reference, but it's ok as default value
  307. return $this->getThumbUrl( $name, $width, $height, $result, $params );
  308. }
  309. $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
  310. $sizekey = "$width:$height:$params";
  311. /* Get the array of urls that we already know */
  312. $knownThumbUrls = $cache->get( $key );
  313. if ( !$knownThumbUrls ) {
  314. /* No knownThumbUrls for this file */
  315. $knownThumbUrls = [];
  316. } else {
  317. if ( isset( $knownThumbUrls[$sizekey] ) ) {
  318. wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
  319. "{$knownThumbUrls[$sizekey]} \n" );
  320. return $knownThumbUrls[$sizekey];
  321. }
  322. /* This size is not yet known */
  323. }
  324. $metadata = null;
  325. $foreignUrl = $this->getThumbUrl( $name, $width, $height, $metadata, $params );
  326. if ( !$foreignUrl ) {
  327. wfDebug( __METHOD__ . " Could not find thumburl\n" );
  328. return false;
  329. }
  330. // We need the same filename as the remote one :)
  331. $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
  332. if ( !$this->validateFilename( $fileName ) ) {
  333. wfDebug( __METHOD__ . " The deduced filename $fileName is not safe\n" );
  334. return false;
  335. }
  336. $localPath = $this->getZonePath( 'thumb' ) . "/" . $this->getHashPath( $name ) . $name;
  337. $localFilename = $localPath . "/" . $fileName;
  338. $localUrl = $this->getZoneUrl( 'thumb' ) . "/" . $this->getHashPath( $name ) .
  339. rawurlencode( $name ) . "/" . rawurlencode( $fileName );
  340. if ( $backend->fileExists( [ 'src' => $localFilename ] )
  341. && isset( $metadata['timestamp'] )
  342. ) {
  343. wfDebug( __METHOD__ . " Thumbnail was already downloaded before\n" );
  344. $modified = $backend->getFileTimestamp( [ 'src' => $localFilename ] );
  345. $remoteModified = strtotime( $metadata['timestamp'] );
  346. $current = time();
  347. $diff = abs( $modified - $current );
  348. if ( $remoteModified < $modified && $diff < $this->fileCacheExpiry ) {
  349. /* Use our current and already downloaded thumbnail */
  350. $knownThumbUrls[$sizekey] = $localUrl;
  351. $cache->set( $key, $knownThumbUrls, $this->apiThumbCacheExpiry );
  352. return $localUrl;
  353. }
  354. /* There is a new Commons file, or existing thumbnail older than a month */
  355. }
  356. $thumb = self::httpGet( $foreignUrl, 'default', [], $mtime );
  357. if ( !$thumb ) {
  358. wfDebug( __METHOD__ . " Could not download thumb\n" );
  359. return false;
  360. }
  361. # @todo FIXME: Delete old thumbs that aren't being used. Maintenance script?
  362. $backend->prepare( [ 'dir' => dirname( $localFilename ) ] );
  363. $params = [ 'dst' => $localFilename, 'content' => $thumb ];
  364. if ( !$backend->quickCreate( $params )->isOK() ) {
  365. wfDebug( __METHOD__ . " could not write to thumb path '$localFilename'\n" );
  366. return $foreignUrl;
  367. }
  368. $knownThumbUrls[$sizekey] = $localUrl;
  369. $ttl = $mtime
  370. ? $cache->adaptiveTTL( $mtime, $this->apiThumbCacheExpiry )
  371. : $this->apiThumbCacheExpiry;
  372. $cache->set( $key, $knownThumbUrls, $ttl );
  373. wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
  374. return $localUrl;
  375. }
  376. /**
  377. * @see FileRepo::getZoneUrl()
  378. * @param string $zone
  379. * @param string|null $ext Optional file extension
  380. * @return string
  381. */
  382. function getZoneUrl( $zone, $ext = null ) {
  383. switch ( $zone ) {
  384. case 'public':
  385. return $this->url;
  386. case 'thumb':
  387. return $this->thumbUrl;
  388. default:
  389. return parent::getZoneUrl( $zone, $ext );
  390. }
  391. }
  392. /**
  393. * Get the local directory corresponding to one of the basic zones
  394. * @param string $zone
  395. * @return bool|null|string
  396. */
  397. function getZonePath( $zone ) {
  398. $supported = [ 'public', 'thumb' ];
  399. if ( in_array( $zone, $supported ) ) {
  400. return parent::getZonePath( $zone );
  401. }
  402. return false;
  403. }
  404. /**
  405. * Are we locally caching the thumbnails?
  406. * @return bool
  407. */
  408. public function canCacheThumbs() {
  409. return ( $this->apiThumbCacheExpiry > 0 );
  410. }
  411. /**
  412. * The user agent the ForeignAPIRepo will use.
  413. * @return string
  414. */
  415. public static function getUserAgent() {
  416. return Http::userAgent() . " ForeignAPIRepo/" . self::VERSION;
  417. }
  418. /**
  419. * Get information about the repo - overrides/extends the parent
  420. * class's information.
  421. * @return array
  422. * @since 1.22
  423. */
  424. function getInfo() {
  425. $info = parent::getInfo();
  426. $info['apiurl'] = $this->getApiUrl();
  427. $query = [
  428. 'format' => 'json',
  429. 'action' => 'query',
  430. 'meta' => 'siteinfo',
  431. 'siprop' => 'general',
  432. ];
  433. $data = $this->httpGetCached( 'SiteInfo', $query, 7200 );
  434. if ( $data ) {
  435. $siteInfo = FormatJson::decode( $data, true );
  436. $general = $siteInfo['query']['general'];
  437. $info['articlepath'] = $general['articlepath'];
  438. $info['server'] = $general['server'];
  439. if ( isset( $general['favicon'] ) ) {
  440. $info['favicon'] = $general['favicon'];
  441. }
  442. }
  443. return $info;
  444. }
  445. /**
  446. * Like a Http:get request, but with custom User-Agent.
  447. * @see Http::get
  448. * @param string $url
  449. * @param string $timeout
  450. * @param array $options
  451. * @param int|bool &$mtime Resulting Last-Modified UNIX timestamp if received
  452. * @return bool|string
  453. */
  454. public static function httpGet(
  455. $url, $timeout = 'default', $options = [], &$mtime = false
  456. ) {
  457. $options['timeout'] = $timeout;
  458. /* Http::get */
  459. $url = wfExpandUrl( $url, PROTO_HTTP );
  460. wfDebug( "ForeignAPIRepo: HTTP GET: $url\n" );
  461. $options['method'] = "GET";
  462. if ( !isset( $options['timeout'] ) ) {
  463. $options['timeout'] = 'default';
  464. }
  465. $req = MWHttpRequest::factory( $url, $options, __METHOD__ );
  466. $req->setUserAgent( self::getUserAgent() );
  467. $status = $req->execute();
  468. if ( $status->isOK() ) {
  469. $lmod = $req->getResponseHeader( 'Last-Modified' );
  470. $mtime = $lmod ? wfTimestamp( TS_UNIX, $lmod ) : false;
  471. return $req->getContent();
  472. } else {
  473. $logger = LoggerFactory::getInstance( 'http' );
  474. $logger->warning(
  475. $status->getWikiText( false, false, 'en' ),
  476. [ 'caller' => 'ForeignAPIRepo::httpGet' ]
  477. );
  478. return false;
  479. }
  480. }
  481. /**
  482. * @return string
  483. * @since 1.23
  484. */
  485. protected static function getIIProps() {
  486. return implode( '|', self::$imageInfoProps );
  487. }
  488. /**
  489. * HTTP GET request to a mediawiki API (with caching)
  490. * @param string $target Used in cache key creation, mostly
  491. * @param array $query The query parameters for the API request
  492. * @param int $cacheTTL Time to live for the memcached caching
  493. * @return string|null
  494. */
  495. public function httpGetCached( $target, $query, $cacheTTL = 3600 ) {
  496. if ( $this->mApiBase ) {
  497. $url = wfAppendQuery( $this->mApiBase, $query );
  498. } else {
  499. $url = $this->makeUrl( $query, 'api' );
  500. }
  501. $cache = ObjectCache::getMainWANInstance();
  502. return $cache->getWithSetCallback(
  503. $this->getLocalCacheKey( static::class, $target, md5( $url ) ),
  504. $cacheTTL,
  505. function ( $curValue, &$ttl ) use ( $url, $cache ) {
  506. $html = self::httpGet( $url, 'default', [], $mtime );
  507. if ( $html !== false ) {
  508. $ttl = $mtime ? $cache->adaptiveTTL( $mtime, $ttl ) : $ttl;
  509. } else {
  510. $ttl = $cache->adaptiveTTL( $mtime, $ttl );
  511. $html = null; // caches negatives
  512. }
  513. return $html;
  514. },
  515. [ 'pcTTL' => $cache::TTL_PROC_LONG ]
  516. );
  517. }
  518. /**
  519. * @param callable $callback
  520. * @throws MWException
  521. */
  522. function enumFiles( $callback ) {
  523. throw new MWException( 'enumFiles is not supported by ' . static::class );
  524. }
  525. /**
  526. * @throws MWException
  527. */
  528. protected function assertWritableRepo() {
  529. throw new MWException( static::class . ': write operations are not supported.' );
  530. }
  531. }