Merge "mediawiki.mixins: Remove -o and -moz vendor prefixes for transition"
[lhc/web/wiklou.git] / includes / filerepo / RepoGroup.php
1 <?php
2 /**
3 * Prioritized list of file repositories.
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
24 /**
25 * Prioritized list of file repositories
26 *
27 * @ingroup FileRepo
28 */
29 class RepoGroup {
30 /** @var LocalRepo */
31 protected $localRepo;
32
33 /** @var FileRepo[] */
34 protected $foreignRepos;
35
36 /** @var bool */
37 protected $reposInitialised = false;
38
39 /** @var array */
40 protected $localInfo;
41
42 /** @var array */
43 protected $foreignInfo;
44
45 /** @var array */
46 protected $cache;
47
48 /** @var RepoGroup */
49 protected static $instance;
50
51 /** Maximum number of cache items */
52 const MAX_CACHE_SIZE = 500;
53
54 /**
55 * Get a RepoGroup instance. At present only one instance of RepoGroup is
56 * needed in a MediaWiki invocation, this may change in the future.
57 * @return RepoGroup
58 */
59 static function singleton() {
60 if ( self::$instance ) {
61 return self::$instance;
62 }
63 global $wgLocalFileRepo, $wgForeignFileRepos;
64 self::$instance = new RepoGroup( $wgLocalFileRepo, $wgForeignFileRepos );
65
66 return self::$instance;
67 }
68
69 /**
70 * Destroy the singleton instance, so that a new one will be created next
71 * time singleton() is called.
72 */
73 static function destroySingleton() {
74 self::$instance = null;
75 }
76
77 /**
78 * Set the singleton instance to a given object
79 * Used by extensions which hook into the Repo chain.
80 * It's not enough to just create a superclass ... you have
81 * to get people to call into it even though all they know is RepoGroup::singleton()
82 *
83 * @param RepoGroup $instance
84 */
85 static function setSingleton( $instance ) {
86 self::$instance = $instance;
87 }
88
89 /**
90 * Construct a group of file repositories.
91 *
92 * @param array $localInfo Associative array for local repo's info
93 * @param array $foreignInfo of repository info arrays.
94 * Each info array is an associative array with the 'class' member
95 * giving the class name. The entire array is passed to the repository
96 * constructor as the first parameter.
97 */
98 function __construct( $localInfo, $foreignInfo ) {
99 $this->localInfo = $localInfo;
100 $this->foreignInfo = $foreignInfo;
101 $this->cache = array();
102 }
103
104 /**
105 * Search repositories for an image.
106 * You can also use wfFindFile() to do this.
107 *
108 * @param $title Title|string Title object or string
109 * @param array $options Associative array of options:
110 * time: requested time for an archived image, or false for the
111 * current version. An image object will be returned which was
112 * created at the specified time.
113 * ignoreRedirect: If true, do not follow file redirects
114 * private: If true, return restricted (deleted) files if the current
115 * user is allowed to view them. Otherwise, such files will not
116 * be found.
117 * bypassCache: If true, do not use the process-local cache of File objects
118 * @return File|bool False if title is not found
119 */
120 function findFile( $title, $options = array() ) {
121 if ( !is_array( $options ) ) {
122 // MW 1.15 compat
123 $options = array( 'time' => $options );
124 }
125 if ( !$this->reposInitialised ) {
126 $this->initialiseRepos();
127 }
128 $title = File::normalizeTitle( $title );
129 if ( !$title ) {
130 return false;
131 }
132
133 # Check the cache
134 if ( empty( $options['ignoreRedirect'] )
135 && empty( $options['private'] )
136 && empty( $options['bypassCache'] )
137 ) {
138 $time = isset( $options['time'] ) ? $options['time'] : '';
139 $dbkey = $title->getDBkey();
140 if ( isset( $this->cache[$dbkey][$time] ) ) {
141 wfDebug( __METHOD__ . ": got File:$dbkey from process cache\n" );
142 # Move it to the end of the list so that we can delete the LRU entry later
143 $this->pingCache( $dbkey );
144
145 # Return the entry
146 return $this->cache[$dbkey][$time];
147 }
148 $useCache = true;
149 } else {
150 $useCache = false;
151 }
152
153 # Check the local repo
154 $image = $this->localRepo->findFile( $title, $options );
155
156 # Check the foreign repos
157 if ( !$image ) {
158 foreach ( $this->foreignRepos as $repo ) {
159 $image = $repo->findFile( $title, $options );
160 if ( $image ) {
161 break;
162 }
163 }
164 }
165
166 $image = $image ? $image : false; // type sanity
167 # Cache file existence or non-existence
168 if ( $useCache && ( !$image || $image->isCacheable() ) ) {
169 $this->trimCache();
170 $this->cache[$dbkey][$time] = $image;
171 }
172
173 return $image;
174 }
175
176 /**
177 * Search repositories for many files at once.
178 *
179 * @param array $items An array of titles, or an array of findFile() options with
180 * the "title" option giving the title. Example:
181 *
182 * $findItem = array( 'title' => $title, 'private' => true );
183 * $findBatch = array( $findItem );
184 * $repo->findFiles( $findBatch );
185 *
186 * No title should appear in $items twice, as the result use titles as keys
187 * @param int $flags Supports:
188 * - FileRepo::NAME_AND_TIME_ONLY : return a (search title => (title,timestamp)) map.
189 * The search title uses the input titles; the other is the final post-redirect title.
190 * All titles are returned as string DB keys and the inner array is associative.
191 * @return array Map of (file name => File objects) for matches
192 *
193 * @param array $inputItems
194 * @param integer $flags
195 * @return array
196 */
197 function findFiles( array $inputItems, $flags = 0 ) {
198 if ( !$this->reposInitialised ) {
199 $this->initialiseRepos();
200 }
201
202 $items = array();
203 foreach ( $inputItems as $item ) {
204 if ( !is_array( $item ) ) {
205 $item = array( 'title' => $item );
206 }
207 $item['title'] = File::normalizeTitle( $item['title'] );
208 if ( $item['title'] ) {
209 $items[$item['title']->getDBkey()] = $item;
210 }
211 }
212
213 $images = $this->localRepo->findFiles( $items, $flags );
214
215 foreach ( $this->foreignRepos as $repo ) {
216 // Remove found files from $items
217 foreach ( $images as $name => $image ) {
218 unset( $items[$name] );
219 }
220
221 $images = array_merge( $images, $repo->findFiles( $items, $flags ) );
222 }
223
224 return $images;
225 }
226
227 /**
228 * Interface for FileRepo::checkRedirect()
229 * @param $title Title
230 * @return bool
231 */
232 function checkRedirect( Title $title ) {
233 if ( !$this->reposInitialised ) {
234 $this->initialiseRepos();
235 }
236
237 $redir = $this->localRepo->checkRedirect( $title );
238 if ( $redir ) {
239 return $redir;
240 }
241
242 foreach ( $this->foreignRepos as $repo ) {
243 $redir = $repo->checkRedirect( $title );
244 if ( $redir ) {
245 return $redir;
246 }
247 }
248
249 return false;
250 }
251
252 /**
253 * Find an instance of the file with this key, created at the specified time
254 * Returns false if the file does not exist.
255 *
256 * @param string $hash base 36 SHA-1 hash
257 * @param array $options Option array, same as findFile()
258 * @return File object or false if it is not found
259 */
260 function findFileFromKey( $hash, $options = array() ) {
261 if ( !$this->reposInitialised ) {
262 $this->initialiseRepos();
263 }
264
265 $file = $this->localRepo->findFileFromKey( $hash, $options );
266 if ( !$file ) {
267 foreach ( $this->foreignRepos as $repo ) {
268 $file = $repo->findFileFromKey( $hash, $options );
269 if ( $file ) {
270 break;
271 }
272 }
273 }
274
275 return $file;
276 }
277
278 /**
279 * Find all instances of files with this key
280 *
281 * @param string $hash base 36 SHA-1 hash
282 * @return Array of File objects
283 */
284 function findBySha1( $hash ) {
285 if ( !$this->reposInitialised ) {
286 $this->initialiseRepos();
287 }
288
289 $result = $this->localRepo->findBySha1( $hash );
290 foreach ( $this->foreignRepos as $repo ) {
291 $result = array_merge( $result, $repo->findBySha1( $hash ) );
292 }
293 usort( $result, 'File::compare' );
294
295 return $result;
296 }
297
298 /**
299 * Find all instances of files with this keys
300 *
301 * @param array $hashes base 36 SHA-1 hashes
302 * @return array of array of File objects
303 */
304 function findBySha1s( array $hashes ) {
305 if ( !$this->reposInitialised ) {
306 $this->initialiseRepos();
307 }
308
309 $result = $this->localRepo->findBySha1s( $hashes );
310 foreach ( $this->foreignRepos as $repo ) {
311 $result = array_merge_recursive( $result, $repo->findBySha1s( $hashes ) );
312 }
313 //sort the merged (and presorted) sublist of each hash
314 foreach ( $result as $hash => $files ) {
315 usort( $result[$hash], 'File::compare' );
316 }
317
318 return $result;
319 }
320
321 /**
322 * Get the repo instance with a given key.
323 * @param string|int $index
324 * @return bool|LocalRepo
325 */
326 function getRepo( $index ) {
327 if ( !$this->reposInitialised ) {
328 $this->initialiseRepos();
329 }
330 if ( $index === 'local' ) {
331 return $this->localRepo;
332 } elseif ( isset( $this->foreignRepos[$index] ) ) {
333 return $this->foreignRepos[$index];
334 } else {
335 return false;
336 }
337 }
338
339 /**
340 * Get the repo instance by its name
341 * @param string $name
342 * @return bool
343 */
344 function getRepoByName( $name ) {
345 if ( !$this->reposInitialised ) {
346 $this->initialiseRepos();
347 }
348 foreach ( $this->foreignRepos as $repo ) {
349 if ( $repo->name == $name ) {
350 return $repo;
351 }
352 }
353
354 return false;
355 }
356
357 /**
358 * Get the local repository, i.e. the one corresponding to the local image
359 * table. Files are typically uploaded to the local repository.
360 *
361 * @return LocalRepo
362 */
363 function getLocalRepo() {
364 return $this->getRepo( 'local' );
365 }
366
367 /**
368 * Call a function for each foreign repo, with the repo object as the
369 * first parameter.
370 *
371 * @param callable $callback The function to call
372 * @param array $params Optional additional parameters to pass to the function
373 * @return bool
374 */
375 function forEachForeignRepo( $callback, $params = array() ) {
376 foreach ( $this->foreignRepos as $repo ) {
377 $args = array_merge( array( $repo ), $params );
378 if ( call_user_func_array( $callback, $args ) ) {
379 return true;
380 }
381 }
382
383 return false;
384 }
385
386 /**
387 * Does the installation have any foreign repos set up?
388 * @return bool
389 */
390 function hasForeignRepos() {
391 return (bool)$this->foreignRepos;
392 }
393
394 /**
395 * Initialise the $repos array
396 */
397 function initialiseRepos() {
398 if ( $this->reposInitialised ) {
399 return;
400 }
401 $this->reposInitialised = true;
402
403 $this->localRepo = $this->newRepo( $this->localInfo );
404 $this->foreignRepos = array();
405 foreach ( $this->foreignInfo as $key => $info ) {
406 $this->foreignRepos[$key] = $this->newRepo( $info );
407 }
408 }
409
410 /**
411 * Create a repo class based on an info structure
412 */
413 protected function newRepo( $info ) {
414 $class = $info['class'];
415
416 return new $class( $info );
417 }
418
419 /**
420 * Split a virtual URL into repo, zone and rel parts
421 * @param string $url
422 * @throws MWException
423 * @return array containing repo, zone and rel
424 */
425 function splitVirtualUrl( $url ) {
426 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
427 throw new MWException( __METHOD__ . ': unknown protocol' );
428 }
429
430 $bits = explode( '/', substr( $url, 9 ), 3 );
431 if ( count( $bits ) != 3 ) {
432 throw new MWException( __METHOD__ . ": invalid mwrepo URL: $url" );
433 }
434
435 return $bits;
436 }
437
438 /**
439 * @param string $fileName
440 * @return array
441 */
442 function getFileProps( $fileName ) {
443 if ( FileRepo::isVirtualUrl( $fileName ) ) {
444 list( $repoName, /* $zone */, /* $rel */ ) = $this->splitVirtualUrl( $fileName );
445 if ( $repoName === '' ) {
446 $repoName = 'local';
447 }
448 $repo = $this->getRepo( $repoName );
449
450 return $repo->getFileProps( $fileName );
451 } else {
452 return FSFile::getPropsFromPath( $fileName );
453 }
454 }
455
456 /**
457 * Move a cache entry to the top (such as when accessed)
458 */
459 protected function pingCache( $key ) {
460 if ( isset( $this->cache[$key] ) ) {
461 $tmp = $this->cache[$key];
462 unset( $this->cache[$key] );
463 $this->cache[$key] = $tmp;
464 }
465 }
466
467 /**
468 * Limit cache memory
469 */
470 protected function trimCache() {
471 while ( count( $this->cache ) >= self::MAX_CACHE_SIZE ) {
472 reset( $this->cache );
473 $key = key( $this->cache );
474 wfDebug( __METHOD__ . ": evicting $key\n" );
475 unset( $this->cache[$key] );
476 }
477 }
478
479 /**
480 * Clear RepoGroup process cache used for finding a file
481 * @param Title|null $title Title of the file or null to clear all files
482 */
483 public function clearCache( Title $title = null ) {
484 if ( $title == null ) {
485 $this->cache = array();
486 } else {
487 $dbKey = $title->getDBkey();
488 if ( isset( $this->cache[$dbKey] ) ) {
489 unset( $this->cache[$dbKey] );
490 }
491 }
492 }
493 }