* (bug 20336) changed json_decode json_encode to static class in global functions
[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 * 'descriptionCacheExpiry' => 3600,
16 * );
17 *
18 * @ingroup FileRepo
19 */
20 class ForeignAPIRepo extends FileRepo {
21 var $fileFactory = array( 'ForeignAPIFile', 'newFromTitle' );
22 var $apiThumbCacheExpiry = 0;
23 protected $mQueryCache = array();
24 protected $mFileExists = array();
25
26 function __construct( $info ) {
27 parent::__construct( $info );
28 $this->mApiBase = $info['apibase']; // http://commons.wikimedia.org/w/api.php
29 if( !$this->scriptDirUrl ) {
30 // hack for description fetches
31 $this->scriptDirUrl = dirname( $this->mApiBase );
32 }
33 }
34
35 /**
36 * Per docs in FileRepo, this needs to return false if we don't support versioned
37 * files. Well, we don't.
38 */
39 function newFile( $title, $time = false ) {
40 if ( $time ) {
41 return false;
42 }
43 return parent::newFile( $title, $time );
44 }
45
46 /**
47 * No-ops
48 */
49 function storeBatch( $triplets, $flags = 0 ) {
50 return false;
51 }
52 function storeTemp( $originalName, $srcPath ) {
53 return false;
54 }
55 function publishBatch( $triplets, $flags = 0 ) {
56 return false;
57 }
58 function deleteBatch( $sourceDestPairs ) {
59 return false;
60 }
61
62
63 function fileExistsBatch( $files, $flags = 0 ) {
64 $results = array();
65 foreach ( $files as $k => $f ) {
66 if ( isset( $this->mFileExists[$k] ) ) {
67 $results[$k] = true;
68 unset( $files[$k] );
69 } elseif( self::isVirtualUrl( $f ) ) {
70 # TODO! FIXME! We need to be able to handle virtual
71 # URLs better, at least when we know they refer to the
72 # same repo.
73 $results[$k] = false;
74 unset( $files[$k] );
75 }
76 }
77
78 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
79 'prop' => 'imageinfo' ) );
80 if( isset( $data['query']['pages'] ) ) {
81 $i = 0;
82 foreach( $files as $key => $file ) {
83 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
84 $i++;
85 }
86 }
87 }
88 function getFileProps( $virtualUrl ) {
89 return false;
90 }
91
92 protected function queryImage( $query ) {
93 $data = $this->fetchImageQuery( $query );
94
95 if( isset( $data['query']['pages'] ) ) {
96 foreach( $data['query']['pages'] as $pageid => $info ) {
97 if( isset( $info['imageinfo'][0] ) ) {
98 return $info['imageinfo'][0];
99 }
100 }
101 }
102 return false;
103 }
104
105 protected function fetchImageQuery( $query ) {
106 global $wgMemc;
107
108 $url = $this->mApiBase .
109 '?' .
110 wfArrayToCgi(
111 array_merge( $query,
112 array(
113 'format' => 'json',
114 'action' => 'query' ) ) );
115
116 if( !isset( $this->mQueryCache[$url] ) ) {
117 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
118 $data = $wgMemc->get( $key );
119 if( !$data ) {
120 $data = Http::get( $url );
121 if ( !$data ) {
122 return null;
123 }
124 $wgMemc->set( $key, $data, 3600 );
125 }
126
127 if( count( $this->mQueryCache ) > 100 ) {
128 // Keep the cache from growing infinitely
129 $this->mQueryCache = array();
130 }
131 $this->mQueryCache[$url] = $data;
132 }
133 return FormatJson::decode( $this->mQueryCache[$url], true );
134 }
135
136 function getImageInfo( $title, $time = false ) {
137 return $this->queryImage( array(
138 'titles' => 'Image:' . $title->getText(),
139 'iiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
140 'prop' => 'imageinfo' ) );
141 }
142
143 function findBySha1( $hash ) {
144 $results = $this->fetchImageQuery( array(
145 'aisha1base36' => $hash,
146 'aiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
147 'list' => 'allimages', ) );
148 $ret = array();
149 if ( isset( $results['query']['allimages'] ) ) {
150 foreach ( $results['query']['allimages'] as $img ) {
151 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
152 }
153 }
154 return $ret;
155 }
156
157 function getThumbUrl( $name, $width=-1, $height=-1 ) {
158 $info = $this->queryImage( array(
159 'titles' => 'Image:' . $name,
160 'iiprop' => 'url',
161 'iiurlwidth' => $width,
162 'iiurlheight' => $height,
163 'prop' => 'imageinfo' ) );
164 if( $info ) {
165 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
166 return $info['thumburl'];
167 } else {
168 return false;
169 }
170 }
171
172 function getThumbUrlFromCache( $name, $width, $height ) {
173 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
174
175 if ( !$this->canCacheThumbs() ) {
176 return $this->getThumbUrl( $name, $width, $height );
177 }
178
179 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
180 if ( $thumbUrl = $wgMemc->get($key) ) {
181 wfDebug("Got thumb from local cache. $thumbUrl \n");
182 return $thumbUrl;
183 }
184 else {
185 $foreignUrl = $this->getThumbUrl( $name, $width, $height );
186
187 // We need the same filename as the remote one :)
188 $fileName = ltrim( substr( $foreignUrl, strrpos( $foreignUrl, '/' ) ), '/' );
189 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
190 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
191 wfMkdirParents($wgUploadDirectory . '/' . $path);
192 }
193 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
194 $thumb = Http::get( $foreignUrl );
195 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
196 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
197 wfDebug( __METHOD__ . " could not write to thumb path\n" );
198 return $foreignUrl;
199 }
200 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
201 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
202 return $localUrl;
203 }
204 }
205
206 /**
207 * Are we locally caching the thumbnails?
208 * @return bool
209 */
210 public function canCacheThumbs() {
211 return ( $this->apiThumbCacheExpiry > 0 );
212 }
213 }