Set default thumb cache to 24hrs, rather than disabled
[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 = 86400;
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 append( $srcPath, $toAppendPath ){
56 return false;
57 }
58 function publishBatch( $triplets, $flags = 0 ) {
59 return false;
60 }
61 function deleteBatch( $sourceDestPairs ) {
62 return false;
63 }
64
65
66 function fileExistsBatch( $files, $flags = 0 ) {
67 $results = array();
68 foreach ( $files as $k => $f ) {
69 if ( isset( $this->mFileExists[$k] ) ) {
70 $results[$k] = true;
71 unset( $files[$k] );
72 } elseif( self::isVirtualUrl( $f ) ) {
73 # TODO! FIXME! We need to be able to handle virtual
74 # URLs better, at least when we know they refer to the
75 # same repo.
76 $results[$k] = false;
77 unset( $files[$k] );
78 }
79 }
80
81 $results = $this->fetchImageQuery( array( 'titles' => implode( $files, '|' ),
82 'prop' => 'imageinfo' ) );
83 if( isset( $data['query']['pages'] ) ) {
84 $i = 0;
85 foreach( $files as $key => $file ) {
86 $results[$key] = $this->mFileExists[$key] = !isset( $data['query']['pages'][$i]['missing'] );
87 $i++;
88 }
89 }
90 }
91 function getFileProps( $virtualUrl ) {
92 return false;
93 }
94
95 protected function queryImage( $query ) {
96 $data = $this->fetchImageQuery( $query );
97
98 if( isset( $data['query']['pages'] ) ) {
99 foreach( $data['query']['pages'] as $pageid => $info ) {
100 if( isset( $info['imageinfo'][0] ) ) {
101 return $info['imageinfo'][0];
102 }
103 }
104 }
105 return false;
106 }
107
108 protected function fetchImageQuery( $query ) {
109 global $wgMemc;
110
111 $url = $this->mApiBase .
112 '?' .
113 wfArrayToCgi(
114 array_merge( $query,
115 array(
116 'format' => 'json',
117 'action' => 'query' ) ) );
118
119 if( !isset( $this->mQueryCache[$url] ) ) {
120 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'Metadata', md5( $url ) );
121 $data = $wgMemc->get( $key );
122 if( !$data ) {
123 $data = Http::get( $url );
124 if ( !$data ) {
125 return null;
126 }
127 $wgMemc->set( $key, $data, 3600 );
128 }
129
130 if( count( $this->mQueryCache ) > 100 ) {
131 // Keep the cache from growing infinitely
132 $this->mQueryCache = array();
133 }
134 $this->mQueryCache[$url] = $data;
135 }
136 return FormatJson::decode( $this->mQueryCache[$url], true );
137 }
138
139 function getImageInfo( $title, $time = false ) {
140 return $this->queryImage( array(
141 'titles' => 'Image:' . $title->getText(),
142 'iiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
143 'prop' => 'imageinfo' ) );
144 }
145
146 function findBySha1( $hash ) {
147 $results = $this->fetchImageQuery( array(
148 'aisha1base36' => $hash,
149 'aiprop' => 'timestamp|user|comment|url|size|sha1|metadata|mime',
150 'list' => 'allimages', ) );
151 $ret = array();
152 if ( isset( $results['query']['allimages'] ) ) {
153 foreach ( $results['query']['allimages'] as $img ) {
154 $ret[] = new ForeignAPIFile( Title::makeTitle( NS_FILE, $img['name'] ), $this, $img );
155 }
156 }
157 return $ret;
158 }
159
160 function getThumbUrl( $name, $width=-1, $height=-1 ) {
161 $info = $this->queryImage( array(
162 'titles' => 'Image:' . $name,
163 'iiprop' => 'url',
164 'iiurlwidth' => $width,
165 'iiurlheight' => $height,
166 'prop' => 'imageinfo' ) );
167 if( $info ) {
168 wfDebug( __METHOD__ . " got remote thumb " . $info['thumburl'] . "\n" );
169 return $info['thumburl'];
170 } else {
171 return false;
172 }
173 }
174
175 function getThumbUrlFromCache( $name, $width, $height ) {
176 global $wgMemc, $wgUploadPath, $wgServer, $wgUploadDirectory;
177
178 if ( !$this->canCacheThumbs() ) {
179 return $this->getThumbUrl( $name, $width, $height );
180 }
181
182 $key = $this->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $name );
183 if ( $thumbUrl = $wgMemc->get($key) ) {
184 wfDebug("Got thumb from local cache. $thumbUrl \n");
185 return $thumbUrl;
186 }
187 else {
188 $foreignUrl = $this->getThumbUrl( $name, $width, $height );
189
190 // We need the same filename as the remote one :)
191 $fileName = rawurldecode( pathinfo( $foreignUrl, PATHINFO_BASENAME ) );
192 $path = 'thumb/' . $this->getHashPath( $name ) . $name . "/";
193 if ( !is_dir($wgUploadDirectory . '/' . $path) ) {
194 wfMkdirParents($wgUploadDirectory . '/' . $path);
195 }
196 $localUrl = $wgServer . $wgUploadPath . '/' . $path . $fileName;
197 $thumb = Http::get( $foreignUrl );
198 # FIXME: Delete old thumbs that aren't being used. Maintenance script?
199 if( !file_put_contents($wgUploadDirectory . '/' . $path . $fileName, $thumb ) ) {
200 wfDebug( __METHOD__ . " could not write to thumb path\n" );
201 return $foreignUrl;
202 }
203 $wgMemc->set( $key, $localUrl, $this->apiThumbCacheExpiry );
204 wfDebug( __METHOD__ . " got local thumb $localUrl, saving to cache \n" );
205 return $localUrl;
206 }
207 }
208
209 /**
210 * Are we locally caching the thumbnails?
211 * @return bool
212 */
213 public function canCacheThumbs() {
214 return ( $this->apiThumbCacheExpiry > 0 );
215 }
216 }