* Fix typo in ApiQueryImageInfo which made mime type query fail to work :)
[lhc/web/wiklou.git] / includes / filerepo / ForeignAPIRepo.php
1 <?php
2
3 /**
4 * A foreign repository with a remote MediaWiki with an API thingy
5 * Very hacky and inefficient
6 * do not use except for testing :D
7 *
8 * Example config:
9 *
10 * $wgForeignFileRepos[] = array(
11 * 'class' => 'ForeignAPIRepo',
12 * 'name' => 'shared',
13 * 'apibase' => 'http://en.wikipedia.org/w/api.php',
14 * 'fetchDescription' => true, // Optional
15 * );
16 *
17 * @ingroup FileRepo
18 */
19 class ForeignAPIRepo extends FileRepo {
20 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
21 protected $mQueryCache = array();
22
23 function __construct( $info ) {
24 parent::__construct( $info );
25 $this->mApiBase = $info['apibase']; // http://commons.wikimedia.org/w/api.php
26 if( !$this->scriptDirUrl ) {
27 // hack for description fetches
28 $this->scriptDirUrl = dirname( $this->mApiBase );
29 }
30 }
31
32 function storeBatch( $triplets, $flags = 0 ) {
33 return false;
34 }
35
36 function storeTemp( $originalName, $srcPath ) {
37 return false;
38 }
39 function publishBatch( $triplets, $flags = 0 ) {
40 return false;
41 }
42 function deleteBatch( $sourceDestPairs ) {
43 return false;
44 }
45 function getFileProps( $virtualUrl ) {
46 return false;
47 }
48
49 protected function queryImage( $query ) {
50 $data = $this->fetchImageQuery( $query );
51
52 if( isset( $data['query']['pages'] ) ) {
53 foreach( $data['query']['pages'] as $pageid => $info ) {
54 if( isset( $info['imageinfo'][0] ) ) {
55 return $info['imageinfo'][0];
56 }
57 }
58 }
59 return false;
60 }
61
62 protected function fetchImageQuery( $query ) {
63 global $wgMemc;
64
65 $url = $this->mApiBase .
66 '?' .
67 wfArrayToCgi(
68 array_merge( $query,
69 array(
70 'format' => 'json',
71 'action' => 'query',
72 'prop' => 'imageinfo' ) ) );
73
74 if( !isset( $this->mQueryCache[$url] ) ) {
75 $key = wfMemcKey( 'ForeignAPIRepo', $url );
76 $data = $wgMemc->get( $key );
77 if( !$data ) {
78 $data = Http::get( $url );
79 $wgMemc->set( $key, $data, 3600 );
80 }
81
82 if( count( $this->mQueryCache ) > 100 ) {
83 // Keep the cache from growing infinitely
84 $this->mQueryCache = array();
85 }
86 $this->mQueryCache[$url] = $data;
87 }
88 return json_decode( $this->mQueryCache[$url], true );
89 }
90
91 function getImageInfo( $title, $time = false ) {
92 return $this->queryImage( array(
93 'titles' => 'Image:' . $title->getText(),
94 'iiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime' ) );
95 }
96
97 function getThumbUrl( $name, $width=-1, $height=-1 ) {
98 $info = $this->queryImage( array(
99 'titles' => 'Image:' . $name,
100 'iiprop' => 'url',
101 'iiurlwidth' => $width,
102 'iiurlheight' => $height ) );
103 if( $info ) {
104 return $info['thumburl'];
105 } else {
106 return false;
107 }
108 }
109 }