Merge "[FileRepo] Locking and transaction fixes."
[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 'overwrite' => true
857 );
858 $this->backend->prepare( array( 'dir' => dirname( $dst ) ) );
859 }
860 $status->merge( $this->backend->doOperations( $operations,
861 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
862 ) );
863
864 return $status;
865 }
866
867 /**
868 * Purge a batch of files from the repo.
869 * This function can be used to write to otherwise read-only foreign repos.
870 * This does no locking nor journaling and is intended for purging thumbnails.
871 *
872 * @param $path Array List of virtual URLs or storage paths
873 * @return FileRepoStatus
874 */
875 public function quickPurgeBatch( array $paths ) {
876 $status = $this->newGood();
877 $operations = array();
878 foreach ( $paths as $path ) {
879 $operations[] = array(
880 'op' => 'delete',
881 'src' => $this->resolveToStoragePath( $path ),
882 'ignoreMissingSource' => true
883 );
884 }
885 $status->merge( $this->backend->doOperations( $operations,
886 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
887 ) );
888
889 return $status;
890 }
891
892 /**
893 * Pick a random name in the temp zone and store a file to it.
894 * Returns a FileRepoStatus object with the file Virtual URL in the value,
895 * file can later be disposed using FileRepo::freeTemp().
896 *
897 * @param $originalName String: the base name of the file as specified
898 * by the user. The file extension will be maintained.
899 * @param $srcPath String: the current location of the file.
900 * @return FileRepoStatus object with the URL in the value.
901 */
902 public function storeTemp( $originalName, $srcPath ) {
903 $this->assertWritableRepo(); // fail out if read-only
904
905 $date = gmdate( "YmdHis" );
906 $hashPath = $this->getHashPath( $originalName );
907 $dstRel = "{$hashPath}{$date}!{$originalName}";
908 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
909
910 $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
911 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
912
913 return $result;
914 }
915
916 /**
917 * Concatenate a list of files into a target file location.
918 *
919 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
920 * @param $dstPath String Target file system path
921 * @param $flags Integer: bitwise combination of the following flags:
922 * self::DELETE_SOURCE Delete the source files
923 * @return FileRepoStatus
924 */
925 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
926 $this->assertWritableRepo(); // fail out if read-only
927
928 $status = $this->newGood();
929
930 $sources = array();
931 $deleteOperations = array(); // post-concatenate ops
932 foreach ( $srcPaths as $srcPath ) {
933 // Resolve source to a storage path if virtual
934 $source = $this->resolveToStoragePath( $srcPath );
935 $sources[] = $source; // chunk to merge
936 if ( $flags & self::DELETE_SOURCE ) {
937 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
938 }
939 }
940
941 // Concatenate the chunks into one FS file
942 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
943 $status->merge( $this->backend->concatenate( $params ) );
944 if ( !$status->isOK() ) {
945 return $status;
946 }
947
948 // Delete the sources if required
949 if ( $deleteOperations ) {
950 $opts = array( 'force' => true );
951 $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
952 }
953
954 // Make sure status is OK, despite any $deleteOperations fatals
955 $status->setResult( true );
956
957 return $status;
958 }
959
960 /**
961 * Remove a temporary file or mark it for garbage collection
962 *
963 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
964 * @return Boolean: true on success, false on failure
965 */
966 public function freeTemp( $virtualUrl ) {
967 $this->assertWritableRepo(); // fail out if read-only
968
969 $temp = "mwrepo://{$this->name}/temp";
970 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
971 wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
972 return false;
973 }
974 $path = $this->resolveVirtualUrl( $virtualUrl );
975
976 return $this->cleanupBatch( array( $path ), self::SKIP_LOCKING )->isOK();
977 }
978
979 /**
980 * Copy or move a file either from a storage path, virtual URL,
981 * or FS path, into this repository at the specified destination location.
982 *
983 * Returns a FileRepoStatus object. On success, the value contains "new" or
984 * "archived", to indicate whether the file was new with that name.
985 *
986 * @param $srcPath String: the source FS path, storage path, or URL
987 * @param $dstRel String: the destination relative path
988 * @param $archiveRel String: the relative path where the existing file is to
989 * be archived, if there is one. Relative to the public zone root.
990 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
991 * that the source file should be deleted if possible
992 * @return FileRepoStatus
993 */
994 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
995 $this->assertWritableRepo(); // fail out if read-only
996
997 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
998 if ( $status->successCount == 0 ) {
999 $status->ok = false;
1000 }
1001 if ( isset( $status->value[0] ) ) {
1002 $status->value = $status->value[0];
1003 } else {
1004 $status->value = false;
1005 }
1006
1007 return $status;
1008 }
1009
1010 /**
1011 * Publish a batch of files
1012 *
1013 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1014 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1015 * that the source files should be deleted if possible
1016 * @return FileRepoStatus
1017 */
1018 public function publishBatch( array $triplets, $flags = 0 ) {
1019 $this->assertWritableRepo(); // fail out if read-only
1020
1021 $backend = $this->backend; // convenience
1022 // Try creating directories
1023 $status = $this->initZones( 'public' );
1024 if ( !$status->isOK() ) {
1025 return $status;
1026 }
1027
1028 $status = $this->newGood( array() );
1029
1030 $operations = array();
1031 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1032 // Validate each triplet and get the store operation...
1033 foreach ( $triplets as $i => $triplet ) {
1034 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1035 // Resolve source to a storage path if virtual
1036 $srcPath = $this->resolveToStoragePath( $srcPath );
1037 if ( !$this->validateFilename( $dstRel ) ) {
1038 throw new MWException( 'Validation error in $dstRel' );
1039 }
1040 if ( !$this->validateFilename( $archiveRel ) ) {
1041 throw new MWException( 'Validation error in $archiveRel' );
1042 }
1043
1044 $publicRoot = $this->getZonePath( 'public' );
1045 $dstPath = "$publicRoot/$dstRel";
1046 $archivePath = "$publicRoot/$archiveRel";
1047
1048 $dstDir = dirname( $dstPath );
1049 $archiveDir = dirname( $archivePath );
1050 // Abort immediately on directory creation errors since they're likely to be repetitive
1051 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1052 return $this->newFatal( 'directorycreateerror', $dstDir );
1053 }
1054 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1055 return $this->newFatal( 'directorycreateerror', $archiveDir );
1056 }
1057
1058 // Archive destination file if it exists
1059 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1060 // Check if the archive file exists
1061 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1062 // unlinks the destination file if it exists. DB-based synchronisation in
1063 // publishBatch's caller should prevent races. In Windows there's no
1064 // problem because the rename primitive fails if the destination exists.
1065 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1066 $operations[] = array( 'op' => 'null' );
1067 continue;
1068 } else {
1069 $operations[] = array(
1070 'op' => 'move',
1071 'src' => $dstPath,
1072 'dst' => $archivePath
1073 );
1074 }
1075 $status->value[$i] = 'archived';
1076 } else {
1077 $status->value[$i] = 'new';
1078 }
1079 // Copy (or move) the source file to the destination
1080 if ( FileBackend::isStoragePath( $srcPath ) ) {
1081 if ( $flags & self::DELETE_SOURCE ) {
1082 $operations[] = array(
1083 'op' => 'move',
1084 'src' => $srcPath,
1085 'dst' => $dstPath
1086 );
1087 } else {
1088 $operations[] = array(
1089 'op' => 'copy',
1090 'src' => $srcPath,
1091 'dst' => $dstPath
1092 );
1093 }
1094 } else { // FS source path
1095 $operations[] = array(
1096 'op' => 'store',
1097 'src' => $srcPath,
1098 'dst' => $dstPath
1099 );
1100 if ( $flags & self::DELETE_SOURCE ) {
1101 $sourceFSFilesToDelete[] = $srcPath;
1102 }
1103 }
1104 }
1105
1106 // Execute the operations for each triplet
1107 $opts = array( 'force' => true );
1108 $status->merge( $backend->doOperations( $operations, $opts ) );
1109 // Cleanup for disk source files...
1110 foreach ( $sourceFSFilesToDelete as $file ) {
1111 wfSuppressWarnings();
1112 unlink( $file ); // FS cleanup
1113 wfRestoreWarnings();
1114 }
1115
1116 return $status;
1117 }
1118
1119 /**
1120 * Deletes a directory if empty.
1121 *
1122 * @param $dir string Virtual URL (or storage path) of directory to clean
1123 * @return Status
1124 */
1125 public function cleanDir( $dir ) {
1126 $this->assertWritableRepo(); // fail out if read-only
1127
1128 $status = $this->newGood();
1129 $status->merge( $this->backend->clean(
1130 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1131
1132 return $status;
1133 }
1134
1135 /**
1136 * Checks existence of a a file
1137 *
1138 * @param $file string Virtual URL (or storage path) of file to check
1139 * @return bool
1140 */
1141 public function fileExists( $file ) {
1142 $result = $this->fileExistsBatch( array( $file ) );
1143 return $result[0];
1144 }
1145
1146 /**
1147 * Checks existence of an array of files.
1148 *
1149 * @param $files Array: Virtual URLs (or storage paths) of files to check
1150 * @return array|bool Either array of files and existence flags, or false
1151 */
1152 public function fileExistsBatch( array $files ) {
1153 $result = array();
1154 foreach ( $files as $key => $file ) {
1155 $file = $this->resolveToStoragePath( $file );
1156 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1157 }
1158 return $result;
1159 }
1160
1161 /**
1162 * Move a file to the deletion archive.
1163 * If no valid deletion archive exists, this may either delete the file
1164 * or throw an exception, depending on the preference of the repository
1165 *
1166 * @param $srcRel Mixed: relative path for the file to be deleted
1167 * @param $archiveRel Mixed: relative path for the archive location.
1168 * Relative to a private archive directory.
1169 * @return FileRepoStatus object
1170 */
1171 public function delete( $srcRel, $archiveRel ) {
1172 $this->assertWritableRepo(); // fail out if read-only
1173
1174 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1175 }
1176
1177 /**
1178 * Move a group of files to the deletion archive.
1179 *
1180 * If no valid deletion archive is configured, this may either delete the
1181 * file or throw an exception, depending on the preference of the repository.
1182 *
1183 * The overwrite policy is determined by the repository -- currently LocalRepo
1184 * assumes a naming scheme in the deleted zone based on content hash, as
1185 * opposed to the public zone which is assumed to be unique.
1186 *
1187 * @param $sourceDestPairs Array of source/destination pairs. Each element
1188 * is a two-element array containing the source file path relative to the
1189 * public root in the first element, and the archive file path relative
1190 * to the deleted zone root in the second element.
1191 * @return FileRepoStatus
1192 */
1193 public function deleteBatch( array $sourceDestPairs ) {
1194 $this->assertWritableRepo(); // fail out if read-only
1195
1196 // Try creating directories
1197 $status = $this->initZones( array( 'public', 'deleted' ) );
1198 if ( !$status->isOK() ) {
1199 return $status;
1200 }
1201
1202 $status = $this->newGood();
1203
1204 $backend = $this->backend; // convenience
1205 $operations = array();
1206 // Validate filenames and create archive directories
1207 foreach ( $sourceDestPairs as $pair ) {
1208 list( $srcRel, $archiveRel ) = $pair;
1209 if ( !$this->validateFilename( $srcRel ) ) {
1210 throw new MWException( __METHOD__.':Validation error in $srcRel' );
1211 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1212 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
1213 }
1214
1215 $publicRoot = $this->getZonePath( 'public' );
1216 $srcPath = "{$publicRoot}/$srcRel";
1217
1218 $deletedRoot = $this->getZonePath( 'deleted' );
1219 $archivePath = "{$deletedRoot}/{$archiveRel}";
1220 $archiveDir = dirname( $archivePath ); // does not touch FS
1221
1222 // Create destination directories
1223 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1224 return $this->newFatal( 'directorycreateerror', $archiveDir );
1225 }
1226 $this->initDeletedDir( $archiveDir );
1227
1228 $operations[] = array(
1229 'op' => 'move',
1230 'src' => $srcPath,
1231 'dst' => $archivePath,
1232 // We may have 2+ identical files being deleted,
1233 // all of which will map to the same destination file
1234 'overwriteSame' => true // also see bug 31792
1235 );
1236 }
1237
1238 // Move the files by execute the operations for each pair.
1239 // We're now committed to returning an OK result, which will
1240 // lead to the files being moved in the DB also.
1241 $opts = array( 'force' => true );
1242 $status->merge( $backend->doOperations( $operations, $opts ) );
1243
1244 return $status;
1245 }
1246
1247 /**
1248 * Delete files in the deleted directory if they are not referenced in the filearchive table
1249 *
1250 * STUB
1251 */
1252 public function cleanupDeletedBatch( array $storageKeys ) {
1253 $this->assertWritableRepo();
1254 }
1255
1256 /**
1257 * Get a relative path for a deletion archive key,
1258 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1259 *
1260 * @return string
1261 */
1262 public function getDeletedHashPath( $key ) {
1263 $path = '';
1264 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1265 $path .= $key[$i] . '/';
1266 }
1267 return $path;
1268 }
1269
1270 /**
1271 * If a path is a virtual URL, resolve it to a storage path.
1272 * Otherwise, just return the path as it is.
1273 *
1274 * @param $path string
1275 * @return string
1276 * @throws MWException
1277 */
1278 protected function resolveToStoragePath( $path ) {
1279 if ( $this->isVirtualUrl( $path ) ) {
1280 return $this->resolveVirtualUrl( $path );
1281 }
1282 return $path;
1283 }
1284
1285 /**
1286 * Get a local FS copy of a file with a given virtual URL/storage path.
1287 * Temporary files may be purged when the file object falls out of scope.
1288 *
1289 * @param $virtualUrl string
1290 * @return TempFSFile|null Returns null on failure
1291 */
1292 public function getLocalCopy( $virtualUrl ) {
1293 $path = $this->resolveToStoragePath( $virtualUrl );
1294 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1295 }
1296
1297 /**
1298 * Get a local FS file with a given virtual URL/storage path.
1299 * The file is either an original or a copy. It should not be changed.
1300 * Temporary files may be purged when the file object falls out of scope.
1301 *
1302 * @param $virtualUrl string
1303 * @return FSFile|null Returns null on failure.
1304 */
1305 public function getLocalReference( $virtualUrl ) {
1306 $path = $this->resolveToStoragePath( $virtualUrl );
1307 return $this->backend->getLocalReference( array( 'src' => $path ) );
1308 }
1309
1310 /**
1311 * Get properties of a file with a given virtual URL/storage path.
1312 * Properties should ultimately be obtained via FSFile::getProps().
1313 *
1314 * @param $virtualUrl string
1315 * @return Array
1316 */
1317 public function getFileProps( $virtualUrl ) {
1318 $path = $this->resolveToStoragePath( $virtualUrl );
1319 return $this->backend->getFileProps( array( 'src' => $path ) );
1320 }
1321
1322 /**
1323 * Get the timestamp of a file with a given virtual URL/storage path
1324 *
1325 * @param $virtualUrl string
1326 * @return string|bool False on failure
1327 */
1328 public function getFileTimestamp( $virtualUrl ) {
1329 $path = $this->resolveToStoragePath( $virtualUrl );
1330 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1331 }
1332
1333 /**
1334 * Get the sha1 of a file with a given virtual URL/storage path
1335 *
1336 * @param $virtualUrl string
1337 * @return string|bool
1338 */
1339 public function getFileSha1( $virtualUrl ) {
1340 $path = $this->resolveToStoragePath( $virtualUrl );
1341 $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
1342 if ( !$tmpFile ) {
1343 return false;
1344 }
1345 return $tmpFile->getSha1Base36();
1346 }
1347
1348 /**
1349 * Attempt to stream a file with the given virtual URL/storage path
1350 *
1351 * @param $virtualUrl string
1352 * @param $headers Array Additional HTTP headers to send on success
1353 * @return bool Success
1354 */
1355 public function streamFile( $virtualUrl, $headers = array() ) {
1356 $path = $this->resolveToStoragePath( $virtualUrl );
1357 $params = array( 'src' => $path, 'headers' => $headers );
1358 return $this->backend->streamFile( $params )->isOK();
1359 }
1360
1361 /**
1362 * Call a callback function for every public regular file in the repository.
1363 * This only acts on the current version of files, not any old versions.
1364 * May use either the database or the filesystem.
1365 *
1366 * @param $callback Array|string
1367 * @return void
1368 */
1369 public function enumFiles( $callback ) {
1370 $this->enumFilesInStorage( $callback );
1371 }
1372
1373 /**
1374 * Call a callback function for every public file in the repository.
1375 * May use either the database or the filesystem.
1376 *
1377 * @param $callback Array|string
1378 * @return void
1379 */
1380 protected function enumFilesInStorage( $callback ) {
1381 $publicRoot = $this->getZonePath( 'public' );
1382 $numDirs = 1 << ( $this->hashLevels * 4 );
1383 // Use a priori assumptions about directory structure
1384 // to reduce the tree height of the scanning process.
1385 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1386 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1387 $path = $publicRoot;
1388 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1389 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1390 }
1391 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1392 foreach ( $iterator as $name ) {
1393 // Each item returned is a public file
1394 call_user_func( $callback, "{$path}/{$name}" );
1395 }
1396 }
1397 }
1398
1399 /**
1400 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1401 *
1402 * @param $filename string
1403 * @return bool
1404 */
1405 public function validateFilename( $filename ) {
1406 if ( strval( $filename ) == '' ) {
1407 return false;
1408 }
1409 return FileBackend::isPathTraversalFree( $filename );
1410 }
1411
1412 /**
1413 * Get a callback function to use for cleaning error message parameters
1414 *
1415 * @return Array
1416 */
1417 function getErrorCleanupFunction() {
1418 switch ( $this->pathDisclosureProtection ) {
1419 case 'none':
1420 case 'simple': // b/c
1421 $callback = array( $this, 'passThrough' );
1422 break;
1423 default: // 'paranoid'
1424 $callback = array( $this, 'paranoidClean' );
1425 }
1426 return $callback;
1427 }
1428
1429 /**
1430 * Path disclosure protection function
1431 *
1432 * @param $param string
1433 * @return string
1434 */
1435 function paranoidClean( $param ) {
1436 return '[hidden]';
1437 }
1438
1439 /**
1440 * Path disclosure protection function
1441 *
1442 * @param $param string
1443 * @return string
1444 */
1445 function passThrough( $param ) {
1446 return $param;
1447 }
1448
1449 /**
1450 * Create a new fatal error
1451 *
1452 * @return FileRepoStatus
1453 */
1454 public function newFatal( $message /*, parameters...*/ ) {
1455 $params = func_get_args();
1456 array_unshift( $params, $this );
1457 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1458 }
1459
1460 /**
1461 * Create a new good result
1462 *
1463 * @return FileRepoStatus
1464 */
1465 public function newGood( $value = null ) {
1466 return FileRepoStatus::newGood( $this, $value );
1467 }
1468
1469 /**
1470 * Checks if there is a redirect named as $title. If there is, return the
1471 * title object. If not, return false.
1472 * STUB
1473 *
1474 * @param $title Title of image
1475 * @return Bool
1476 */
1477 public function checkRedirect( Title $title ) {
1478 return false;
1479 }
1480
1481 /**
1482 * Invalidates image redirect cache related to that image
1483 * Doesn't do anything for repositories that don't support image redirects.
1484 *
1485 * STUB
1486 * @param $title Title of image
1487 */
1488 public function invalidateImageRedirect( Title $title ) {}
1489
1490 /**
1491 * Get the human-readable name of the repo
1492 *
1493 * @return string
1494 */
1495 public function getDisplayName() {
1496 // We don't name our own repo, return nothing
1497 if ( $this->isLocal() ) {
1498 return null;
1499 }
1500 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1501 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1502 }
1503
1504 /**
1505 * Returns true if this the local file repository.
1506 *
1507 * @return bool
1508 */
1509 public function isLocal() {
1510 return $this->getName() == 'local';
1511 }
1512
1513 /**
1514 * Get a key on the primary cache for this repository.
1515 * Returns false if the repository's cache is not accessible at this site.
1516 * The parameters are the parts of the key, as for wfMemcKey().
1517 *
1518 * STUB
1519 * @return bool
1520 */
1521 public function getSharedCacheKey( /*...*/ ) {
1522 return false;
1523 }
1524
1525 /**
1526 * Get a key for this repo in the local cache domain. These cache keys are
1527 * not shared with remote instances of the repo.
1528 * The parameters are the parts of the key, as for wfMemcKey().
1529 *
1530 * @return string
1531 */
1532 public function getLocalCacheKey( /*...*/ ) {
1533 $args = func_get_args();
1534 array_unshift( $args, 'filerepo', $this->getName() );
1535 return call_user_func_array( 'wfMemcKey', $args );
1536 }
1537
1538 /**
1539 * Get an temporary FileRepo associated with this repo.
1540 * Files will be created in the temp zone of this repo and
1541 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1542 * It will have the same backend as this repo.
1543 *
1544 * @return TempFileRepo
1545 */
1546 public function getTempRepo() {
1547 return new TempFileRepo( array(
1548 'name' => "{$this->name}-temp",
1549 'backend' => $this->backend,
1550 'zones' => array(
1551 'public' => array(
1552 'container' => $this->zones['temp']['container'],
1553 'directory' => $this->zones['temp']['directory']
1554 ),
1555 'thumb' => array(
1556 'container' => $this->zones['thumb']['container'],
1557 'directory' => ( $this->zones['thumb']['directory'] == '' )
1558 ? 'temp'
1559 : $this->zones['thumb']['directory'] . '/temp'
1560 )
1561 ),
1562 'url' => $this->getZoneUrl( 'temp' ),
1563 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1564 'hashLevels' => $this->hashLevels // performance
1565 ) );
1566 }
1567
1568 /**
1569 * Get an UploadStash associated with this repo.
1570 *
1571 * @return UploadStash
1572 */
1573 public function getUploadStash() {
1574 return new UploadStash( $this );
1575 }
1576
1577 /**
1578 * Throw an exception if this repo is read-only by design.
1579 * This does not and should not check getReadOnlyReason().
1580 *
1581 * @return void
1582 * @throws MWException
1583 */
1584 protected function assertWritableRepo() {}
1585 }
1586
1587 /**
1588 * FileRepo for temporary files created via FileRepo::getTempRepo()
1589 */
1590 class TempFileRepo extends FileRepo {
1591 public function getTempRepo() {
1592 throw new MWException( "Cannot get a temp repo from a temp repo." );
1593 }
1594 }