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