give path when not able to write the thumb
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2 /**
3 * @defgroup FileRepo File Repository
4 *
5 * @brief This module handles how MediaWiki interacts with filesystems.
6 *
7 * @details
8 */
9
10 /**
11 * Base code for file repositories.
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
27 *
28 * @file
29 * @ingroup FileRepo
30 */
31
32 /**
33 * Base class for file repositories
34 *
35 * @ingroup FileRepo
36 */
37 class FileRepo {
38 const DELETE_SOURCE = 1;
39 const OVERWRITE = 2;
40 const OVERWRITE_SAME = 4;
41 const SKIP_LOCKING = 8;
42
43 /** @var FileBackend */
44 protected $backend;
45 /** @var Array Map of zones to config */
46 protected $zones = array();
47
48 var $thumbScriptUrl, $transformVia404;
49 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
50 var $fetchDescription, $initialCapital;
51 var $pathDisclosureProtection = 'simple'; // 'paranoid'
52 var $descriptionCacheExpiry, $url, $thumbUrl;
53 var $hashLevels, $deletedHashLevels;
54
55 /**
56 * Factory functions for creating new files
57 * Override these in the base class
58 */
59 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
60 var $oldFileFactory = false;
61 var $fileFactoryKey = false, $oldFileFactoryKey = false;
62
63 function __construct( array $info = null ) {
64 // Verify required settings presence
65 if(
66 $info === null
67 || !array_key_exists( 'name', $info )
68 || !array_key_exists( 'backend', $info )
69 ) {
70 throw new MWException( __CLASS__ . " requires an array of options having both 'name' and 'backend' keys.\n" );
71 }
72
73 // Required settings
74 $this->name = $info['name'];
75 if ( $info['backend'] instanceof FileBackend ) {
76 $this->backend = $info['backend']; // useful for testing
77 } else {
78 $this->backend = FileBackendGroup::singleton()->get( $info['backend'] );
79 }
80
81 // Optional settings that can have no value
82 $optionalSettings = array(
83 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
84 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
85 'scriptExtension'
86 );
87 foreach ( $optionalSettings as $var ) {
88 if ( isset( $info[$var] ) ) {
89 $this->$var = $info[$var];
90 }
91 }
92
93 // Optional settings that have a default
94 $this->initialCapital = isset( $info['initialCapital'] )
95 ? $info['initialCapital']
96 : MWNamespace::isCapitalized( NS_FILE );
97 $this->url = isset( $info['url'] )
98 ? $info['url']
99 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
100 if ( isset( $info['thumbUrl'] ) ) {
101 $this->thumbUrl = $info['thumbUrl'];
102 } else {
103 $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
104 }
105 $this->hashLevels = isset( $info['hashLevels'] )
106 ? $info['hashLevels']
107 : 2;
108 $this->deletedHashLevels = isset( $info['deletedHashLevels'] )
109 ? $info['deletedHashLevels']
110 : $this->hashLevels;
111 $this->transformVia404 = !empty( $info['transformVia404'] );
112 $this->zones = isset( $info['zones'] )
113 ? $info['zones']
114 : array();
115 // Give defaults for the basic zones...
116 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
117 if ( !isset( $this->zones[$zone] ) ) {
118 $this->zones[$zone] = array(
119 'container' => "{$this->name}-{$zone}",
120 'directory' => '' // container root
121 );
122 }
123 }
124 }
125
126 /**
127 * Get the file backend instance. Use this function wisely.
128 *
129 * @return FileBackend
130 */
131 public function getBackend() {
132 return $this->backend;
133 }
134
135 /**
136 * Get an explanatory message if this repo is read-only.
137 * This checks if an administrator disabled writes to the backend.
138 *
139 * @return string|bool Returns false if the repo is not read-only
140 */
141 public function getReadOnlyReason() {
142 return $this->backend->getReadOnlyReason();
143 }
144
145 /**
146 * Check if a single zone or list of zones is defined for usage
147 *
148 * @param $doZones Array Only do a particular zones
149 * @return Status
150 */
151 protected function initZones( $doZones = array() ) {
152 $status = $this->newGood();
153 foreach ( (array)$doZones as $zone ) {
154 $root = $this->getZonePath( $zone );
155 if ( $root === null ) {
156 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
157 }
158 }
159 return $status;
160 }
161
162 /**
163 * Take all available measures to prevent web accessibility of new deleted
164 * directories, in case the user has not configured offline storage
165 *
166 * @param $dir string
167 * @return void
168 */
169 protected function initDeletedDir( $dir ) {
170 $this->backend->secure( // prevent web access & dir listings
171 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
172 }
173
174 /**
175 * Determine if a string is an mwrepo:// URL
176 *
177 * @param $url string
178 * @return bool
179 */
180 public static function isVirtualUrl( $url ) {
181 return substr( $url, 0, 9 ) == 'mwrepo://';
182 }
183
184 /**
185 * Get a URL referring to this repository, with the private mwrepo protocol.
186 * The suffix, if supplied, is considered to be unencoded, and will be
187 * URL-encoded before being returned.
188 *
189 * @param $suffix string
190 * @return string
191 */
192 public function getVirtualUrl( $suffix = false ) {
193 $path = 'mwrepo://' . $this->name;
194 if ( $suffix !== false ) {
195 $path .= '/' . rawurlencode( $suffix );
196 }
197 return $path;
198 }
199
200 /**
201 * Get the URL corresponding to one of the four basic zones
202 *
203 * @param $zone String: one of: public, deleted, temp, thumb
204 * @return String or false
205 */
206 public function getZoneUrl( $zone ) {
207 switch ( $zone ) {
208 case 'public':
209 return $this->url;
210 case 'temp':
211 return "{$this->url}/temp";
212 case 'deleted':
213 return false; // no public URL
214 case 'thumb':
215 return $this->thumbUrl;
216 default:
217 return false;
218 }
219 }
220
221 /**
222 * Get the backend storage path corresponding to a virtual URL.
223 * Use this function wisely.
224 *
225 * @param $url string
226 * @return string
227 */
228 public function resolveVirtualUrl( $url ) {
229 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
230 throw new MWException( __METHOD__.': unknown protocol' );
231 }
232 $bits = explode( '/', substr( $url, 9 ), 3 );
233 if ( count( $bits ) != 3 ) {
234 throw new MWException( __METHOD__.": invalid mwrepo URL: $url" );
235 }
236 list( $repo, $zone, $rel ) = $bits;
237 if ( $repo !== $this->name ) {
238 throw new MWException( __METHOD__.": fetching from a foreign repo is not supported" );
239 }
240 $base = $this->getZonePath( $zone );
241 if ( !$base ) {
242 throw new MWException( __METHOD__.": invalid zone: $zone" );
243 }
244 return $base . '/' . rawurldecode( $rel );
245 }
246
247 /**
248 * The the storage container and base path of a zone
249 *
250 * @param $zone string
251 * @return Array (container, base path) or (null, null)
252 */
253 protected function getZoneLocation( $zone ) {
254 if ( !isset( $this->zones[$zone] ) ) {
255 return array( null, null ); // bogus
256 }
257 return array( $this->zones[$zone]['container'], $this->zones[$zone]['directory'] );
258 }
259
260 /**
261 * Get the storage path corresponding to one of the zones
262 *
263 * @param $zone string
264 * @return string|null Returns null if the zone is not defined
265 */
266 public function getZonePath( $zone ) {
267 list( $container, $base ) = $this->getZoneLocation( $zone );
268 if ( $container === null || $base === null ) {
269 return null;
270 }
271 $backendName = $this->backend->getName();
272 if ( $base != '' ) { // may not be set
273 $base = "/{$base}";
274 }
275 return "mwstore://$backendName/{$container}{$base}";
276 }
277
278 /**
279 * Create a new File object from the local repository
280 *
281 * @param $title Mixed: Title object or string
282 * @param $time Mixed: Time at which the image was uploaded.
283 * If this is specified, the returned object will be an
284 * instance of the repository's old file class instead of a
285 * current file. Repositories not supporting version control
286 * should return false if this parameter is set.
287 * @return File|null A File, or null if passed an invalid Title
288 */
289 public function newFile( $title, $time = false ) {
290 $title = File::normalizeTitle( $title );
291 if ( !$title ) {
292 return null;
293 }
294 if ( $time ) {
295 if ( $this->oldFileFactory ) {
296 return call_user_func( $this->oldFileFactory, $title, $this, $time );
297 } else {
298 return false;
299 }
300 } else {
301 return call_user_func( $this->fileFactory, $title, $this );
302 }
303 }
304
305 /**
306 * Find an instance of the named file created at the specified time
307 * Returns false if the file does not exist. Repositories not supporting
308 * version control should return false if the time is specified.
309 *
310 * @param $title Mixed: Title object or string
311 * @param $options array Associative array of options:
312 * time: requested time for a specific file version, or false for the
313 * current version. An image object will be returned which was
314 * created at the specified time (which may be archived or current).
315 *
316 * ignoreRedirect: If true, do not follow file redirects
317 *
318 * private: If true, return restricted (deleted) files if the current
319 * user is allowed to view them. Otherwise, such files will not
320 * be found.
321 * @return File|bool False on failure
322 */
323 public function findFile( $title, $options = array() ) {
324 $title = File::normalizeTitle( $title );
325 if ( !$title ) {
326 return false;
327 }
328 $time = isset( $options['time'] ) ? $options['time'] : false;
329 # First try the current version of the file to see if it precedes the timestamp
330 $img = $this->newFile( $title );
331 if ( !$img ) {
332 return false;
333 }
334 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
335 return $img;
336 }
337 # Now try an old version of the file
338 if ( $time !== false ) {
339 $img = $this->newFile( $title, $time );
340 if ( $img && $img->exists() ) {
341 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
342 return $img; // always OK
343 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
344 return $img;
345 }
346 }
347 }
348
349 # Now try redirects
350 if ( !empty( $options['ignoreRedirect'] ) ) {
351 return false;
352 }
353 $redir = $this->checkRedirect( $title );
354 if ( $redir && $title->getNamespace() == NS_FILE) {
355 $img = $this->newFile( $redir );
356 if ( !$img ) {
357 return false;
358 }
359 if ( $img->exists() ) {
360 $img->redirectedFrom( $title->getDBkey() );
361 return $img;
362 }
363 }
364 return false;
365 }
366
367 /**
368 * Find many files at once.
369 *
370 * @param $items array An array of titles, or an array of findFile() options with
371 * the "title" option giving the title. Example:
372 *
373 * $findItem = array( 'title' => $title, 'private' => true );
374 * $findBatch = array( $findItem );
375 * $repo->findFiles( $findBatch );
376 * @return array
377 */
378 public function findFiles( array $items ) {
379 $result = array();
380 foreach ( $items as $item ) {
381 if ( is_array( $item ) ) {
382 $title = $item['title'];
383 $options = $item;
384 unset( $options['title'] );
385 } else {
386 $title = $item;
387 $options = array();
388 }
389 $file = $this->findFile( $title, $options );
390 if ( $file ) {
391 $result[$file->getTitle()->getDBkey()] = $file;
392 }
393 }
394 return $result;
395 }
396
397 /**
398 * Find an instance of the file with this key, created at the specified time
399 * Returns false if the file does not exist. Repositories not supporting
400 * version control should return false if the time is specified.
401 *
402 * @param $sha1 String base 36 SHA-1 hash
403 * @param $options array Option array, same as findFile().
404 * @return File|bool False on failure
405 */
406 public function findFileFromKey( $sha1, $options = array() ) {
407 $time = isset( $options['time'] ) ? $options['time'] : false;
408 # First try to find a matching current version of a file...
409 if ( $this->fileFactoryKey ) {
410 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
411 } else {
412 return false; // find-by-sha1 not supported
413 }
414 if ( $img && $img->exists() ) {
415 return $img;
416 }
417 # Now try to find a matching old version of a file...
418 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
419 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
420 if ( $img && $img->exists() ) {
421 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
422 return $img; // always OK
423 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
424 return $img;
425 }
426 }
427 }
428 return false;
429 }
430
431 /**
432 * Get an array or iterator of file objects for files that have a given
433 * SHA-1 content hash.
434 *
435 * STUB
436 * @return array
437 */
438 public function findBySha1( $hash ) {
439 return array();
440 }
441
442 /**
443 * Get the public root URL of the repository
444 *
445 * @return string
446 */
447 public function getRootUrl() {
448 return $this->url;
449 }
450
451 /**
452 * Get the URL of thumb.php
453 *
454 * @return string
455 */
456 public function getThumbScriptUrl() {
457 return $this->thumbScriptUrl;
458 }
459
460 /**
461 * Returns true if the repository can transform files via a 404 handler
462 *
463 * @return bool
464 */
465 public function canTransformVia404() {
466 return $this->transformVia404;
467 }
468
469 /**
470 * Get the name of an image from its title object
471 *
472 * @param $title Title
473 * @return String
474 */
475 public function getNameFromTitle( Title $title ) {
476 global $wgContLang;
477 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
478 $name = $title->getUserCaseDBKey();
479 if ( $this->initialCapital ) {
480 $name = $wgContLang->ucfirst( $name );
481 }
482 } else {
483 $name = $title->getDBkey();
484 }
485 return $name;
486 }
487
488 /**
489 * Get the public zone root storage directory of the repository
490 *
491 * @return string
492 */
493 public function getRootDirectory() {
494 return $this->getZonePath( 'public' );
495 }
496
497 /**
498 * Get a relative path including trailing slash, e.g. f/fa/
499 * If the repo is not hashed, returns an empty string
500 *
501 * @param $name string Name of file
502 * @return string
503 */
504 public function getHashPath( $name ) {
505 return self::getHashPathForLevel( $name, $this->hashLevels );
506 }
507
508 /**
509 * Get a relative path including trailing slash, e.g. f/fa/
510 * If the repo is not hashed, returns an empty string
511 *
512 * @param $suffix string Basename of file from FileRepo::storeTemp()
513 * @return string
514 */
515 public function getTempHashPath( $suffix ) {
516 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
517 $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp
518 return self::getHashPathForLevel( $name, $this->hashLevels );
519 }
520
521 /**
522 * @param $name
523 * @param $levels
524 * @return string
525 */
526 protected static function getHashPathForLevel( $name, $levels ) {
527 if ( $levels == 0 ) {
528 return '';
529 } else {
530 $hash = md5( $name );
531 $path = '';
532 for ( $i = 1; $i <= $levels; $i++ ) {
533 $path .= substr( $hash, 0, $i ) . '/';
534 }
535 return $path;
536 }
537 }
538
539 /**
540 * Get the number of hash directory levels
541 *
542 * @return integer
543 */
544 public function getHashLevels() {
545 return $this->hashLevels;
546 }
547
548 /**
549 * Get the name of this repository, as specified by $info['name]' to the constructor
550 *
551 * @return string
552 */
553 public function getName() {
554 return $this->name;
555 }
556
557 /**
558 * Make an url to this repo
559 *
560 * @param $query mixed Query string to append
561 * @param $entry string Entry point; defaults to index
562 * @return string|bool False on failure
563 */
564 public function makeUrl( $query = '', $entry = 'index' ) {
565 if ( isset( $this->scriptDirUrl ) ) {
566 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
567 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
568 }
569 return false;
570 }
571
572 /**
573 * Get the URL of an image description page. May return false if it is
574 * unknown or not applicable. In general this should only be called by the
575 * File class, since it may return invalid results for certain kinds of
576 * repositories. Use File::getDescriptionUrl() in user code.
577 *
578 * In particular, it uses the article paths as specified to the repository
579 * constructor, whereas local repositories use the local Title functions.
580 *
581 * @param $name string
582 * @return string
583 */
584 public function getDescriptionUrl( $name ) {
585 $encName = wfUrlencode( $name );
586 if ( !is_null( $this->descBaseUrl ) ) {
587 # "http://example.com/wiki/Image:"
588 return $this->descBaseUrl . $encName;
589 }
590 if ( !is_null( $this->articleUrl ) ) {
591 # "http://example.com/wiki/$1"
592 #
593 # We use "Image:" as the canonical namespace for
594 # compatibility across all MediaWiki versions.
595 return str_replace( '$1',
596 "Image:$encName", $this->articleUrl );
597 }
598 if ( !is_null( $this->scriptDirUrl ) ) {
599 # "http://example.com/w"
600 #
601 # We use "Image:" as the canonical namespace for
602 # compatibility across all MediaWiki versions,
603 # and just sort of hope index.php is right. ;)
604 return $this->makeUrl( "title=Image:$encName" );
605 }
606 return false;
607 }
608
609 /**
610 * Get the URL of the content-only fragment of the description page. For
611 * MediaWiki this means action=render. This should only be called by the
612 * repository's file class, since it may return invalid results. User code
613 * should use File::getDescriptionText().
614 *
615 * @param $name String: name of image to fetch
616 * @param $lang String: language to fetch it in, if any.
617 * @return string
618 */
619 public function getDescriptionRenderUrl( $name, $lang = null ) {
620 $query = 'action=render';
621 if ( !is_null( $lang ) ) {
622 $query .= '&uselang=' . $lang;
623 }
624 if ( isset( $this->scriptDirUrl ) ) {
625 return $this->makeUrl(
626 'title=' .
627 wfUrlencode( 'Image:' . $name ) .
628 "&$query" );
629 } else {
630 $descUrl = $this->getDescriptionUrl( $name );
631 if ( $descUrl ) {
632 return wfAppendQuery( $descUrl, $query );
633 } else {
634 return false;
635 }
636 }
637 }
638
639 /**
640 * Get the URL of the stylesheet to apply to description pages
641 *
642 * @return string|bool False on failure
643 */
644 public function getDescriptionStylesheetUrl() {
645 if ( isset( $this->scriptDirUrl ) ) {
646 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
647 wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
648 }
649 return false;
650 }
651
652 /**
653 * Store a file to a given destination.
654 *
655 * @param $srcPath String: source FS path, storage path, or virtual URL
656 * @param $dstZone String: destination zone
657 * @param $dstRel String: destination relative path
658 * @param $flags Integer: bitwise combination of the following flags:
659 * self::DELETE_SOURCE Delete the source file after upload
660 * self::OVERWRITE Overwrite an existing destination file instead of failing
661 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
662 * same contents as the source
663 * self::SKIP_LOCKING Skip any file locking when doing the store
664 * @return FileRepoStatus
665 */
666 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
667 $this->assertWritableRepo(); // fail out if read-only
668
669 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
670 if ( $status->successCount == 0 ) {
671 $status->ok = false;
672 }
673
674 return $status;
675 }
676
677 /**
678 * Store a batch of files
679 *
680 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
681 * @param $flags Integer: bitwise combination of the following flags:
682 * self::DELETE_SOURCE Delete the source file after upload
683 * self::OVERWRITE Overwrite an existing destination file instead of failing
684 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
685 * same contents as the source
686 * self::SKIP_LOCKING Skip any file locking when doing the store
687 * @return FileRepoStatus
688 */
689 public function storeBatch( array $triplets, $flags = 0 ) {
690 $this->assertWritableRepo(); // fail out if read-only
691
692 $status = $this->newGood();
693 $backend = $this->backend; // convenience
694
695 $operations = array();
696 $sourceFSFilesToDelete = array(); // cleanup for disk source files
697 // Validate each triplet and get the store operation...
698 foreach ( $triplets as $triplet ) {
699 list( $srcPath, $dstZone, $dstRel ) = $triplet;
700 wfDebug( __METHOD__
701 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
702 );
703
704 // Resolve destination path
705 $root = $this->getZonePath( $dstZone );
706 if ( !$root ) {
707 throw new MWException( "Invalid zone: $dstZone" );
708 }
709 if ( !$this->validateFilename( $dstRel ) ) {
710 throw new MWException( 'Validation error in $dstRel' );
711 }
712 $dstPath = "$root/$dstRel";
713 $dstDir = dirname( $dstPath );
714 // Create destination directories for this triplet
715 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
716 return $this->newFatal( 'directorycreateerror', $dstDir );
717 }
718
719 if ( $dstZone == 'deleted' ) {
720 $this->initDeletedDir( $dstDir );
721 }
722
723 // Resolve source to a storage path if virtual
724 $srcPath = $this->resolveToStoragePath( $srcPath );
725
726 // Get the appropriate file operation
727 if ( FileBackend::isStoragePath( $srcPath ) ) {
728 $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
729 } else {
730 $opName = 'store';
731 if ( $flags & self::DELETE_SOURCE ) {
732 $sourceFSFilesToDelete[] = $srcPath;
733 }
734 }
735 $operations[] = array(
736 'op' => $opName,
737 'src' => $srcPath,
738 'dst' => $dstPath,
739 'overwrite' => $flags & self::OVERWRITE,
740 'overwriteSame' => $flags & self::OVERWRITE_SAME,
741 );
742 }
743
744 // Execute the store operation for each triplet
745 $opts = array( 'force' => true );
746 if ( $flags & self::SKIP_LOCKING ) {
747 $opts['nonLocking'] = true;
748 }
749 $status->merge( $backend->doOperations( $operations, $opts ) );
750 // Cleanup for disk source files...
751 foreach ( $sourceFSFilesToDelete as $file ) {
752 wfSuppressWarnings();
753 unlink( $file ); // FS cleanup
754 wfRestoreWarnings();
755 }
756
757 return $status;
758 }
759
760 /**
761 * Deletes a batch of files.
762 * Each file can be a (zone, rel) pair, virtual url, storage path.
763 * It will try to delete each file, but ignores any errors that may occur.
764 *
765 * @param $pairs array List of files to delete
766 * @param $flags Integer: bitwise combination of the following flags:
767 * self::SKIP_LOCKING Skip any file locking when doing the deletions
768 * @return FileRepoStatus
769 */
770 public function cleanupBatch( array $files, $flags = 0 ) {
771 $this->assertWritableRepo(); // fail out if read-only
772
773 $status = $this->newGood();
774
775 $operations = array();
776 foreach ( $files as $path ) {
777 if ( is_array( $path ) ) {
778 // This is a pair, extract it
779 list( $zone, $rel ) = $path;
780 $path = $this->getZonePath( $zone ) . "/$rel";
781 } else {
782 // Resolve source to a storage path if virtual
783 $path = $this->resolveToStoragePath( $path );
784 }
785 $operations[] = array( 'op' => 'delete', 'src' => $path );
786 }
787 // Actually delete files from storage...
788 $opts = array( 'force' => true );
789 if ( $flags & self::SKIP_LOCKING ) {
790 $opts['nonLocking'] = true;
791 }
792 $status->merge( $this->backend->doOperations( $operations, $opts ) );
793
794 return $status;
795 }
796
797 /**
798 * Import a file from the local file system into the repo.
799 * This does no locking nor journaling and overrides existing files.
800 * This function can be used to write to otherwise read-only foreign repos.
801 * This is intended for copying generated thumbnails into the repo.
802 *
803 * @param $src string File system path
804 * @param $dst string Virtual URL or storage path
805 * @return FileRepoStatus
806 */
807 final public function quickImport( $src, $dst ) {
808 return $this->quickImportBatch( array( array( $src, $dst ) ) );
809 }
810
811 /**
812 * Purge a file from the repo. This does no locking nor journaling.
813 * This function can be used to write to otherwise read-only foreign repos.
814 * This is intended for purging thumbnails.
815 *
816 * @param $path string Virtual URL or storage path
817 * @return FileRepoStatus
818 */
819 final public function quickPurge( $path ) {
820 return $this->quickPurgeBatch( array( $path ) );
821 }
822
823 /**
824 * Deletes a directory if empty.
825 * This function can be used to write to otherwise read-only foreign repos.
826 *
827 * @param $dir string Virtual URL (or storage path) of directory to clean
828 * @return Status
829 */
830 public function quickCleanDir( $dir ) {
831 $status = $this->newGood();
832 $status->merge( $this->backend->clean(
833 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
834
835 return $status;
836 }
837
838 /**
839 * Import a batch of files from the local file system into the repo.
840 * This does no locking nor journaling and overrides existing files.
841 * This function can be used to write to otherwise read-only foreign repos.
842 * This is intended for copying generated thumbnails into the repo.
843 *
844 * @param $src Array List of tuples (file system path, virtual URL or storage path)
845 * @return FileRepoStatus
846 */
847 public function quickImportBatch( array $pairs ) {
848 $status = $this->newGood();
849 $operations = array();
850 foreach ( $pairs as $pair ) {
851 list ( $src, $dst ) = $pair;
852 $operations[] = array(
853 'op' => 'store',
854 'src' => $src,
855 'dst' => $this->resolveToStoragePath( $dst )
856 );
857 $this->backend->prepare( array( 'dir' => dirname( $dst ) ) );
858 }
859 $status->merge( $this->backend->doQuickOperations( $operations ) );
860
861 return $status;
862 }
863
864 /**
865 * Purge a batch of files from the repo.
866 * This function can be used to write to otherwise read-only foreign repos.
867 * This does no locking nor journaling and is intended for purging thumbnails.
868 *
869 * @param $path Array List of virtual URLs or storage paths
870 * @return FileRepoStatus
871 */
872 public function quickPurgeBatch( array $paths ) {
873 $status = $this->newGood();
874 $operations = array();
875 foreach ( $paths as $path ) {
876 $operations[] = array(
877 'op' => 'delete',
878 'src' => $this->resolveToStoragePath( $path ),
879 'ignoreMissingSource' => true
880 );
881 }
882 $status->merge( $this->backend->doQuickOperations( $operations ) );
883
884 return $status;
885 }
886
887 /**
888 * Pick a random name in the temp zone and store a file to it.
889 * Returns a FileRepoStatus object with the file Virtual URL in the value,
890 * file can later be disposed using FileRepo::freeTemp().
891 *
892 * @param $originalName String: the base name of the file as specified
893 * by the user. The file extension will be maintained.
894 * @param $srcPath String: the current location of the file.
895 * @return FileRepoStatus object with the URL in the value.
896 */
897 public function storeTemp( $originalName, $srcPath ) {
898 $this->assertWritableRepo(); // fail out if read-only
899
900 $date = gmdate( "YmdHis" );
901 $hashPath = $this->getHashPath( $originalName );
902 $dstRel = "{$hashPath}{$date}!{$originalName}";
903 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
904
905 $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
906 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
907
908 return $result;
909 }
910
911 /**
912 * Concatenate a list of files into a target file location.
913 *
914 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
915 * @param $dstPath String Target file system path
916 * @param $flags Integer: bitwise combination of the following flags:
917 * self::DELETE_SOURCE Delete the source files
918 * @return FileRepoStatus
919 */
920 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
921 $this->assertWritableRepo(); // fail out if read-only
922
923 $status = $this->newGood();
924
925 $sources = array();
926 $deleteOperations = array(); // post-concatenate ops
927 foreach ( $srcPaths as $srcPath ) {
928 // Resolve source to a storage path if virtual
929 $source = $this->resolveToStoragePath( $srcPath );
930 $sources[] = $source; // chunk to merge
931 if ( $flags & self::DELETE_SOURCE ) {
932 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
933 }
934 }
935
936 // Concatenate the chunks into one FS file
937 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
938 $status->merge( $this->backend->concatenate( $params ) );
939 if ( !$status->isOK() ) {
940 return $status;
941 }
942
943 // Delete the sources if required
944 if ( $deleteOperations ) {
945 $opts = array( 'force' => true );
946 $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
947 }
948
949 // Make sure status is OK, despite any $deleteOperations fatals
950 $status->setResult( true );
951
952 return $status;
953 }
954
955 /**
956 * Remove a temporary file or mark it for garbage collection
957 *
958 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
959 * @return Boolean: true on success, false on failure
960 */
961 public function freeTemp( $virtualUrl ) {
962 $this->assertWritableRepo(); // fail out if read-only
963
964 $temp = "mwrepo://{$this->name}/temp";
965 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
966 wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
967 return false;
968 }
969 $path = $this->resolveVirtualUrl( $virtualUrl );
970
971 return $this->cleanupBatch( array( $path ), self::SKIP_LOCKING )->isOK();
972 }
973
974 /**
975 * Copy or move a file either from a storage path, virtual URL,
976 * or FS path, into this repository at the specified destination location.
977 *
978 * Returns a FileRepoStatus object. On success, the value contains "new" or
979 * "archived", to indicate whether the file was new with that name.
980 *
981 * @param $srcPath String: the source FS path, storage path, or URL
982 * @param $dstRel String: the destination relative path
983 * @param $archiveRel String: the relative path where the existing file is to
984 * be archived, if there is one. Relative to the public zone root.
985 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
986 * that the source file should be deleted if possible
987 * @return FileRepoStatus
988 */
989 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
990 $this->assertWritableRepo(); // fail out if read-only
991
992 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
993 if ( $status->successCount == 0 ) {
994 $status->ok = false;
995 }
996 if ( isset( $status->value[0] ) ) {
997 $status->value = $status->value[0];
998 } else {
999 $status->value = false;
1000 }
1001
1002 return $status;
1003 }
1004
1005 /**
1006 * Publish a batch of files
1007 *
1008 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1009 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1010 * that the source files should be deleted if possible
1011 * @return FileRepoStatus
1012 */
1013 public function publishBatch( array $triplets, $flags = 0 ) {
1014 $this->assertWritableRepo(); // fail out if read-only
1015
1016 $backend = $this->backend; // convenience
1017 // Try creating directories
1018 $status = $this->initZones( 'public' );
1019 if ( !$status->isOK() ) {
1020 return $status;
1021 }
1022
1023 $status = $this->newGood( array() );
1024
1025 $operations = array();
1026 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1027 // Validate each triplet and get the store operation...
1028 foreach ( $triplets as $i => $triplet ) {
1029 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1030 // Resolve source to a storage path if virtual
1031 $srcPath = $this->resolveToStoragePath( $srcPath );
1032 if ( !$this->validateFilename( $dstRel ) ) {
1033 throw new MWException( 'Validation error in $dstRel' );
1034 }
1035 if ( !$this->validateFilename( $archiveRel ) ) {
1036 throw new MWException( 'Validation error in $archiveRel' );
1037 }
1038
1039 $publicRoot = $this->getZonePath( 'public' );
1040 $dstPath = "$publicRoot/$dstRel";
1041 $archivePath = "$publicRoot/$archiveRel";
1042
1043 $dstDir = dirname( $dstPath );
1044 $archiveDir = dirname( $archivePath );
1045 // Abort immediately on directory creation errors since they're likely to be repetitive
1046 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1047 return $this->newFatal( 'directorycreateerror', $dstDir );
1048 }
1049 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1050 return $this->newFatal( 'directorycreateerror', $archiveDir );
1051 }
1052
1053 // Archive destination file if it exists
1054 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1055 // Check if the archive file exists
1056 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1057 // unlinks the destination file if it exists. DB-based synchronisation in
1058 // publishBatch's caller should prevent races. In Windows there's no
1059 // problem because the rename primitive fails if the destination exists.
1060 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1061 $operations[] = array( 'op' => 'null' );
1062 continue;
1063 } else {
1064 $operations[] = array(
1065 'op' => 'move',
1066 'src' => $dstPath,
1067 'dst' => $archivePath
1068 );
1069 }
1070 $status->value[$i] = 'archived';
1071 } else {
1072 $status->value[$i] = 'new';
1073 }
1074 // Copy (or move) the source file to the destination
1075 if ( FileBackend::isStoragePath( $srcPath ) ) {
1076 if ( $flags & self::DELETE_SOURCE ) {
1077 $operations[] = array(
1078 'op' => 'move',
1079 'src' => $srcPath,
1080 'dst' => $dstPath
1081 );
1082 } else {
1083 $operations[] = array(
1084 'op' => 'copy',
1085 'src' => $srcPath,
1086 'dst' => $dstPath
1087 );
1088 }
1089 } else { // FS source path
1090 $operations[] = array(
1091 'op' => 'store',
1092 'src' => $srcPath,
1093 'dst' => $dstPath
1094 );
1095 if ( $flags & self::DELETE_SOURCE ) {
1096 $sourceFSFilesToDelete[] = $srcPath;
1097 }
1098 }
1099 }
1100
1101 // Execute the operations for each triplet
1102 $opts = array( 'force' => true );
1103 $status->merge( $backend->doOperations( $operations, $opts ) );
1104 // Cleanup for disk source files...
1105 foreach ( $sourceFSFilesToDelete as $file ) {
1106 wfSuppressWarnings();
1107 unlink( $file ); // FS cleanup
1108 wfRestoreWarnings();
1109 }
1110
1111 return $status;
1112 }
1113
1114 /**
1115 * Deletes a directory if empty.
1116 *
1117 * @param $dir string Virtual URL (or storage path) of directory to clean
1118 * @return Status
1119 */
1120 public function cleanDir( $dir ) {
1121 $this->assertWritableRepo(); // fail out if read-only
1122
1123 $status = $this->newGood();
1124 $status->merge( $this->backend->clean(
1125 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1126
1127 return $status;
1128 }
1129
1130 /**
1131 * Checks existence of a a file
1132 *
1133 * @param $file string Virtual URL (or storage path) of file to check
1134 * @return bool
1135 */
1136 public function fileExists( $file ) {
1137 $result = $this->fileExistsBatch( array( $file ) );
1138 return $result[0];
1139 }
1140
1141 /**
1142 * Checks existence of an array of files.
1143 *
1144 * @param $files Array: Virtual URLs (or storage paths) of files to check
1145 * @return array|bool Either array of files and existence flags, or false
1146 */
1147 public function fileExistsBatch( array $files ) {
1148 $result = array();
1149 foreach ( $files as $key => $file ) {
1150 $file = $this->resolveToStoragePath( $file );
1151 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1152 }
1153 return $result;
1154 }
1155
1156 /**
1157 * Move a file to the deletion archive.
1158 * If no valid deletion archive exists, this may either delete the file
1159 * or throw an exception, depending on the preference of the repository
1160 *
1161 * @param $srcRel Mixed: relative path for the file to be deleted
1162 * @param $archiveRel Mixed: relative path for the archive location.
1163 * Relative to a private archive directory.
1164 * @return FileRepoStatus object
1165 */
1166 public function delete( $srcRel, $archiveRel ) {
1167 $this->assertWritableRepo(); // fail out if read-only
1168
1169 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1170 }
1171
1172 /**
1173 * Move a group of files to the deletion archive.
1174 *
1175 * If no valid deletion archive is configured, this may either delete the
1176 * file or throw an exception, depending on the preference of the repository.
1177 *
1178 * The overwrite policy is determined by the repository -- currently LocalRepo
1179 * assumes a naming scheme in the deleted zone based on content hash, as
1180 * opposed to the public zone which is assumed to be unique.
1181 *
1182 * @param $sourceDestPairs Array of source/destination pairs. Each element
1183 * is a two-element array containing the source file path relative to the
1184 * public root in the first element, and the archive file path relative
1185 * to the deleted zone root in the second element.
1186 * @return FileRepoStatus
1187 */
1188 public function deleteBatch( array $sourceDestPairs ) {
1189 $this->assertWritableRepo(); // fail out if read-only
1190
1191 // Try creating directories
1192 $status = $this->initZones( array( 'public', 'deleted' ) );
1193 if ( !$status->isOK() ) {
1194 return $status;
1195 }
1196
1197 $status = $this->newGood();
1198
1199 $backend = $this->backend; // convenience
1200 $operations = array();
1201 // Validate filenames and create archive directories
1202 foreach ( $sourceDestPairs as $pair ) {
1203 list( $srcRel, $archiveRel ) = $pair;
1204 if ( !$this->validateFilename( $srcRel ) ) {
1205 throw new MWException( __METHOD__.':Validation error in $srcRel' );
1206 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1207 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
1208 }
1209
1210 $publicRoot = $this->getZonePath( 'public' );
1211 $srcPath = "{$publicRoot}/$srcRel";
1212
1213 $deletedRoot = $this->getZonePath( 'deleted' );
1214 $archivePath = "{$deletedRoot}/{$archiveRel}";
1215 $archiveDir = dirname( $archivePath ); // does not touch FS
1216
1217 // Create destination directories
1218 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1219 return $this->newFatal( 'directorycreateerror', $archiveDir );
1220 }
1221 $this->initDeletedDir( $archiveDir );
1222
1223 $operations[] = array(
1224 'op' => 'move',
1225 'src' => $srcPath,
1226 'dst' => $archivePath,
1227 // We may have 2+ identical files being deleted,
1228 // all of which will map to the same destination file
1229 'overwriteSame' => true // also see bug 31792
1230 );
1231 }
1232
1233 // Move the files by execute the operations for each pair.
1234 // We're now committed to returning an OK result, which will
1235 // lead to the files being moved in the DB also.
1236 $opts = array( 'force' => true );
1237 $status->merge( $backend->doOperations( $operations, $opts ) );
1238
1239 return $status;
1240 }
1241
1242 /**
1243 * Delete files in the deleted directory if they are not referenced in the filearchive table
1244 *
1245 * STUB
1246 */
1247 public function cleanupDeletedBatch( array $storageKeys ) {
1248 $this->assertWritableRepo();
1249 }
1250
1251 /**
1252 * Get a relative path for a deletion archive key,
1253 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1254 *
1255 * @return string
1256 */
1257 public function getDeletedHashPath( $key ) {
1258 $path = '';
1259 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1260 $path .= $key[$i] . '/';
1261 }
1262 return $path;
1263 }
1264
1265 /**
1266 * If a path is a virtual URL, resolve it to a storage path.
1267 * Otherwise, just return the path as it is.
1268 *
1269 * @param $path string
1270 * @return string
1271 * @throws MWException
1272 */
1273 protected function resolveToStoragePath( $path ) {
1274 if ( $this->isVirtualUrl( $path ) ) {
1275 return $this->resolveVirtualUrl( $path );
1276 }
1277 return $path;
1278 }
1279
1280 /**
1281 * Get a local FS copy of a file with a given virtual URL/storage path.
1282 * Temporary files may be purged when the file object falls out of scope.
1283 *
1284 * @param $virtualUrl string
1285 * @return TempFSFile|null Returns null on failure
1286 */
1287 public function getLocalCopy( $virtualUrl ) {
1288 $path = $this->resolveToStoragePath( $virtualUrl );
1289 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1290 }
1291
1292 /**
1293 * Get a local FS file with a given virtual URL/storage path.
1294 * The file is either an original or a copy. It should not be changed.
1295 * Temporary files may be purged when the file object falls out of scope.
1296 *
1297 * @param $virtualUrl string
1298 * @return FSFile|null Returns null on failure.
1299 */
1300 public function getLocalReference( $virtualUrl ) {
1301 $path = $this->resolveToStoragePath( $virtualUrl );
1302 return $this->backend->getLocalReference( array( 'src' => $path ) );
1303 }
1304
1305 /**
1306 * Get properties of a file with a given virtual URL/storage path.
1307 * Properties should ultimately be obtained via FSFile::getProps().
1308 *
1309 * @param $virtualUrl string
1310 * @return Array
1311 */
1312 public function getFileProps( $virtualUrl ) {
1313 $path = $this->resolveToStoragePath( $virtualUrl );
1314 return $this->backend->getFileProps( array( 'src' => $path ) );
1315 }
1316
1317 /**
1318 * Get the timestamp of a file with a given virtual URL/storage path
1319 *
1320 * @param $virtualUrl string
1321 * @return string|bool False on failure
1322 */
1323 public function getFileTimestamp( $virtualUrl ) {
1324 $path = $this->resolveToStoragePath( $virtualUrl );
1325 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1326 }
1327
1328 /**
1329 * Get the sha1 of a file with a given virtual URL/storage path
1330 *
1331 * @param $virtualUrl string
1332 * @return string|bool
1333 */
1334 public function getFileSha1( $virtualUrl ) {
1335 $path = $this->resolveToStoragePath( $virtualUrl );
1336 $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
1337 if ( !$tmpFile ) {
1338 return false;
1339 }
1340 return $tmpFile->getSha1Base36();
1341 }
1342
1343 /**
1344 * Attempt to stream a file with the given virtual URL/storage path
1345 *
1346 * @param $virtualUrl string
1347 * @param $headers Array Additional HTTP headers to send on success
1348 * @return bool Success
1349 */
1350 public function streamFile( $virtualUrl, $headers = array() ) {
1351 $path = $this->resolveToStoragePath( $virtualUrl );
1352 $params = array( 'src' => $path, 'headers' => $headers );
1353 return $this->backend->streamFile( $params )->isOK();
1354 }
1355
1356 /**
1357 * Call a callback function for every public regular file in the repository.
1358 * This only acts on the current version of files, not any old versions.
1359 * May use either the database or the filesystem.
1360 *
1361 * @param $callback Array|string
1362 * @return void
1363 */
1364 public function enumFiles( $callback ) {
1365 $this->enumFilesInStorage( $callback );
1366 }
1367
1368 /**
1369 * Call a callback function for every public file in the repository.
1370 * May use either the database or the filesystem.
1371 *
1372 * @param $callback Array|string
1373 * @return void
1374 */
1375 protected function enumFilesInStorage( $callback ) {
1376 $publicRoot = $this->getZonePath( 'public' );
1377 $numDirs = 1 << ( $this->hashLevels * 4 );
1378 // Use a priori assumptions about directory structure
1379 // to reduce the tree height of the scanning process.
1380 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1381 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1382 $path = $publicRoot;
1383 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1384 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1385 }
1386 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1387 foreach ( $iterator as $name ) {
1388 // Each item returned is a public file
1389 call_user_func( $callback, "{$path}/{$name}" );
1390 }
1391 }
1392 }
1393
1394 /**
1395 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1396 *
1397 * @param $filename string
1398 * @return bool
1399 */
1400 public function validateFilename( $filename ) {
1401 if ( strval( $filename ) == '' ) {
1402 return false;
1403 }
1404 return FileBackend::isPathTraversalFree( $filename );
1405 }
1406
1407 /**
1408 * Get a callback function to use for cleaning error message parameters
1409 *
1410 * @return Array
1411 */
1412 function getErrorCleanupFunction() {
1413 switch ( $this->pathDisclosureProtection ) {
1414 case 'none':
1415 case 'simple': // b/c
1416 $callback = array( $this, 'passThrough' );
1417 break;
1418 default: // 'paranoid'
1419 $callback = array( $this, 'paranoidClean' );
1420 }
1421 return $callback;
1422 }
1423
1424 /**
1425 * Path disclosure protection function
1426 *
1427 * @param $param string
1428 * @return string
1429 */
1430 function paranoidClean( $param ) {
1431 return '[hidden]';
1432 }
1433
1434 /**
1435 * Path disclosure protection function
1436 *
1437 * @param $param string
1438 * @return string
1439 */
1440 function passThrough( $param ) {
1441 return $param;
1442 }
1443
1444 /**
1445 * Create a new fatal error
1446 *
1447 * @return FileRepoStatus
1448 */
1449 public function newFatal( $message /*, parameters...*/ ) {
1450 $params = func_get_args();
1451 array_unshift( $params, $this );
1452 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1453 }
1454
1455 /**
1456 * Create a new good result
1457 *
1458 * @return FileRepoStatus
1459 */
1460 public function newGood( $value = null ) {
1461 return FileRepoStatus::newGood( $this, $value );
1462 }
1463
1464 /**
1465 * Checks if there is a redirect named as $title. If there is, return the
1466 * title object. If not, return false.
1467 * STUB
1468 *
1469 * @param $title Title of image
1470 * @return Bool
1471 */
1472 public function checkRedirect( Title $title ) {
1473 return false;
1474 }
1475
1476 /**
1477 * Invalidates image redirect cache related to that image
1478 * Doesn't do anything for repositories that don't support image redirects.
1479 *
1480 * STUB
1481 * @param $title Title of image
1482 */
1483 public function invalidateImageRedirect( Title $title ) {}
1484
1485 /**
1486 * Get the human-readable name of the repo
1487 *
1488 * @return string
1489 */
1490 public function getDisplayName() {
1491 // We don't name our own repo, return nothing
1492 if ( $this->isLocal() ) {
1493 return null;
1494 }
1495 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1496 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1497 }
1498
1499 /**
1500 * Returns true if this the local file repository.
1501 *
1502 * @return bool
1503 */
1504 public function isLocal() {
1505 return $this->getName() == 'local';
1506 }
1507
1508 /**
1509 * Get a key on the primary cache for this repository.
1510 * Returns false if the repository's cache is not accessible at this site.
1511 * The parameters are the parts of the key, as for wfMemcKey().
1512 *
1513 * STUB
1514 * @return bool
1515 */
1516 public function getSharedCacheKey( /*...*/ ) {
1517 return false;
1518 }
1519
1520 /**
1521 * Get a key for this repo in the local cache domain. These cache keys are
1522 * not shared with remote instances of the repo.
1523 * The parameters are the parts of the key, as for wfMemcKey().
1524 *
1525 * @return string
1526 */
1527 public function getLocalCacheKey( /*...*/ ) {
1528 $args = func_get_args();
1529 array_unshift( $args, 'filerepo', $this->getName() );
1530 return call_user_func_array( 'wfMemcKey', $args );
1531 }
1532
1533 /**
1534 * Get an temporary FileRepo associated with this repo.
1535 * Files will be created in the temp zone of this repo and
1536 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1537 * It will have the same backend as this repo.
1538 *
1539 * @return TempFileRepo
1540 */
1541 public function getTempRepo() {
1542 return new TempFileRepo( array(
1543 'name' => "{$this->name}-temp",
1544 'backend' => $this->backend,
1545 'zones' => array(
1546 'public' => array(
1547 'container' => $this->zones['temp']['container'],
1548 'directory' => $this->zones['temp']['directory']
1549 ),
1550 'thumb' => array(
1551 'container' => $this->zones['thumb']['container'],
1552 'directory' => ( $this->zones['thumb']['directory'] == '' )
1553 ? 'temp'
1554 : $this->zones['thumb']['directory'] . '/temp'
1555 )
1556 ),
1557 'url' => $this->getZoneUrl( 'temp' ),
1558 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1559 'hashLevels' => $this->hashLevels // performance
1560 ) );
1561 }
1562
1563 /**
1564 * Get an UploadStash associated with this repo.
1565 *
1566 * @return UploadStash
1567 */
1568 public function getUploadStash() {
1569 return new UploadStash( $this );
1570 }
1571
1572 /**
1573 * Throw an exception if this repo is read-only by design.
1574 * This does not and should not check getReadOnlyReason().
1575 *
1576 * @return void
1577 * @throws MWException
1578 */
1579 protected function assertWritableRepo() {}
1580 }
1581
1582 /**
1583 * FileRepo for temporary files created via FileRepo::getTempRepo()
1584 */
1585 class TempFileRepo extends FileRepo {
1586 public function getTempRepo() {
1587 throw new MWException( "Cannot get a temp repo from a temp repo." );
1588 }
1589 }