(bug 27567) Add file repo support to prop=duplicatefiles
[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 an array of arrays or iterators of file objects for files that
444 * have the given SHA-1 content hashes.
445 *
446 * @param $hashes array An array of hashes
447 * @return array An Array of arrays or iterators of file objects and the hash as key
448 */
449 public function findBySha1s( array $hashes ) {
450 $result = array();
451 foreach ( $hashes as $hash ) {
452 $files = $this->findBySha1( $hash );
453 if ( count( $files ) ) {
454 $result[$hash] = $files;
455 }
456 }
457 return $result;
458 }
459
460 /**
461 * Get the public root URL of the repository
462 *
463 * @deprecated since 1.20
464 * @return string
465 */
466 public function getRootUrl() {
467 return $this->getZoneUrl( 'public' );
468 }
469
470 /**
471 * Get the URL of thumb.php
472 *
473 * @return string
474 */
475 public function getThumbScriptUrl() {
476 return $this->thumbScriptUrl;
477 }
478
479 /**
480 * Returns true if the repository can transform files via a 404 handler
481 *
482 * @return bool
483 */
484 public function canTransformVia404() {
485 return $this->transformVia404;
486 }
487
488 /**
489 * Get the name of an image from its title object
490 *
491 * @param $title Title
492 * @return String
493 */
494 public function getNameFromTitle( Title $title ) {
495 global $wgContLang;
496 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
497 $name = $title->getUserCaseDBKey();
498 if ( $this->initialCapital ) {
499 $name = $wgContLang->ucfirst( $name );
500 }
501 } else {
502 $name = $title->getDBkey();
503 }
504 return $name;
505 }
506
507 /**
508 * Get the public zone root storage directory of the repository
509 *
510 * @return string
511 */
512 public function getRootDirectory() {
513 return $this->getZonePath( 'public' );
514 }
515
516 /**
517 * Get a relative path including trailing slash, e.g. f/fa/
518 * If the repo is not hashed, returns an empty string
519 *
520 * @param $name string Name of file
521 * @return string
522 */
523 public function getHashPath( $name ) {
524 return self::getHashPathForLevel( $name, $this->hashLevels );
525 }
526
527 /**
528 * Get a relative path including trailing slash, e.g. f/fa/
529 * If the repo is not hashed, returns an empty string
530 *
531 * @param $suffix string Basename of file from FileRepo::storeTemp()
532 * @return string
533 */
534 public function getTempHashPath( $suffix ) {
535 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
536 $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp
537 return self::getHashPathForLevel( $name, $this->hashLevels );
538 }
539
540 /**
541 * @param $name
542 * @param $levels
543 * @return string
544 */
545 protected static function getHashPathForLevel( $name, $levels ) {
546 if ( $levels == 0 ) {
547 return '';
548 } else {
549 $hash = md5( $name );
550 $path = '';
551 for ( $i = 1; $i <= $levels; $i++ ) {
552 $path .= substr( $hash, 0, $i ) . '/';
553 }
554 return $path;
555 }
556 }
557
558 /**
559 * Get the number of hash directory levels
560 *
561 * @return integer
562 */
563 public function getHashLevels() {
564 return $this->hashLevels;
565 }
566
567 /**
568 * Get the name of this repository, as specified by $info['name]' to the constructor
569 *
570 * @return string
571 */
572 public function getName() {
573 return $this->name;
574 }
575
576 /**
577 * Make an url to this repo
578 *
579 * @param $query mixed Query string to append
580 * @param $entry string Entry point; defaults to index
581 * @return string|bool False on failure
582 */
583 public function makeUrl( $query = '', $entry = 'index' ) {
584 if ( isset( $this->scriptDirUrl ) ) {
585 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
586 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
587 }
588 return false;
589 }
590
591 /**
592 * Get the URL of an image description page. May return false if it is
593 * unknown or not applicable. In general this should only be called by the
594 * File class, since it may return invalid results for certain kinds of
595 * repositories. Use File::getDescriptionUrl() in user code.
596 *
597 * In particular, it uses the article paths as specified to the repository
598 * constructor, whereas local repositories use the local Title functions.
599 *
600 * @param $name string
601 * @return string
602 */
603 public function getDescriptionUrl( $name ) {
604 $encName = wfUrlencode( $name );
605 if ( !is_null( $this->descBaseUrl ) ) {
606 # "http://example.com/wiki/Image:"
607 return $this->descBaseUrl . $encName;
608 }
609 if ( !is_null( $this->articleUrl ) ) {
610 # "http://example.com/wiki/$1"
611 #
612 # We use "Image:" as the canonical namespace for
613 # compatibility across all MediaWiki versions.
614 return str_replace( '$1',
615 "Image:$encName", $this->articleUrl );
616 }
617 if ( !is_null( $this->scriptDirUrl ) ) {
618 # "http://example.com/w"
619 #
620 # We use "Image:" as the canonical namespace for
621 # compatibility across all MediaWiki versions,
622 # and just sort of hope index.php is right. ;)
623 return $this->makeUrl( "title=Image:$encName" );
624 }
625 return false;
626 }
627
628 /**
629 * Get the URL of the content-only fragment of the description page. For
630 * MediaWiki this means action=render. This should only be called by the
631 * repository's file class, since it may return invalid results. User code
632 * should use File::getDescriptionText().
633 *
634 * @param $name String: name of image to fetch
635 * @param $lang String: language to fetch it in, if any.
636 * @return string
637 */
638 public function getDescriptionRenderUrl( $name, $lang = null ) {
639 $query = 'action=render';
640 if ( !is_null( $lang ) ) {
641 $query .= '&uselang=' . $lang;
642 }
643 if ( isset( $this->scriptDirUrl ) ) {
644 return $this->makeUrl(
645 'title=' .
646 wfUrlencode( 'Image:' . $name ) .
647 "&$query" );
648 } else {
649 $descUrl = $this->getDescriptionUrl( $name );
650 if ( $descUrl ) {
651 return wfAppendQuery( $descUrl, $query );
652 } else {
653 return false;
654 }
655 }
656 }
657
658 /**
659 * Get the URL of the stylesheet to apply to description pages
660 *
661 * @return string|bool False on failure
662 */
663 public function getDescriptionStylesheetUrl() {
664 if ( isset( $this->scriptDirUrl ) ) {
665 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
666 wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
667 }
668 return false;
669 }
670
671 /**
672 * Store a file to a given destination.
673 *
674 * @param $srcPath String: source FS path, storage path, or virtual URL
675 * @param $dstZone String: destination zone
676 * @param $dstRel String: destination relative path
677 * @param $flags Integer: bitwise combination of the following flags:
678 * self::DELETE_SOURCE Delete the source file after upload
679 * self::OVERWRITE Overwrite an existing destination file instead of failing
680 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
681 * same contents as the source
682 * self::SKIP_LOCKING Skip any file locking when doing the store
683 * @return FileRepoStatus
684 */
685 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
686 $this->assertWritableRepo(); // fail out if read-only
687
688 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
689 if ( $status->successCount == 0 ) {
690 $status->ok = false;
691 }
692
693 return $status;
694 }
695
696 /**
697 * Store a batch of files
698 *
699 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
700 * @param $flags Integer: bitwise combination of the following flags:
701 * self::DELETE_SOURCE Delete the source file after upload
702 * self::OVERWRITE Overwrite an existing destination file instead of failing
703 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
704 * same contents as the source
705 * self::SKIP_LOCKING Skip any file locking when doing the store
706 * @throws MWException
707 * @return FileRepoStatus
708 */
709 public function storeBatch( array $triplets, $flags = 0 ) {
710 $this->assertWritableRepo(); // fail out if read-only
711
712 $status = $this->newGood();
713 $backend = $this->backend; // convenience
714
715 $operations = array();
716 $sourceFSFilesToDelete = array(); // cleanup for disk source files
717 // Validate each triplet and get the store operation...
718 foreach ( $triplets as $triplet ) {
719 list( $srcPath, $dstZone, $dstRel ) = $triplet;
720 wfDebug( __METHOD__
721 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
722 );
723
724 // Resolve destination path
725 $root = $this->getZonePath( $dstZone );
726 if ( !$root ) {
727 throw new MWException( "Invalid zone: $dstZone" );
728 }
729 if ( !$this->validateFilename( $dstRel ) ) {
730 throw new MWException( 'Validation error in $dstRel' );
731 }
732 $dstPath = "$root/$dstRel";
733 $dstDir = dirname( $dstPath );
734 // Create destination directories for this triplet
735 if ( !$this->initDirectory( $dstDir )->isOK() ) {
736 return $this->newFatal( 'directorycreateerror', $dstDir );
737 }
738
739 // Resolve source to a storage path if virtual
740 $srcPath = $this->resolveToStoragePath( $srcPath );
741
742 // Get the appropriate file operation
743 if ( FileBackend::isStoragePath( $srcPath ) ) {
744 $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
745 } else {
746 $opName = 'store';
747 if ( $flags & self::DELETE_SOURCE ) {
748 $sourceFSFilesToDelete[] = $srcPath;
749 }
750 }
751 $operations[] = array(
752 'op' => $opName,
753 'src' => $srcPath,
754 'dst' => $dstPath,
755 'overwrite' => $flags & self::OVERWRITE,
756 'overwriteSame' => $flags & self::OVERWRITE_SAME,
757 );
758 }
759
760 // Execute the store operation for each triplet
761 $opts = array( 'force' => true );
762 if ( $flags & self::SKIP_LOCKING ) {
763 $opts['nonLocking'] = true;
764 }
765 $status->merge( $backend->doOperations( $operations, $opts ) );
766 // Cleanup for disk source files...
767 foreach ( $sourceFSFilesToDelete as $file ) {
768 wfSuppressWarnings();
769 unlink( $file ); // FS cleanup
770 wfRestoreWarnings();
771 }
772
773 return $status;
774 }
775
776 /**
777 * Deletes a batch of files.
778 * Each file can be a (zone, rel) pair, virtual url, storage path.
779 * It will try to delete each file, but ignores any errors that may occur.
780 *
781 * @param $files array List of files to delete
782 * @param $flags Integer: bitwise combination of the following flags:
783 * self::SKIP_LOCKING Skip any file locking when doing the deletions
784 * @return FileRepoStatus
785 */
786 public function cleanupBatch( array $files, $flags = 0 ) {
787 $this->assertWritableRepo(); // fail out if read-only
788
789 $status = $this->newGood();
790
791 $operations = array();
792 foreach ( $files as $path ) {
793 if ( is_array( $path ) ) {
794 // This is a pair, extract it
795 list( $zone, $rel ) = $path;
796 $path = $this->getZonePath( $zone ) . "/$rel";
797 } else {
798 // Resolve source to a storage path if virtual
799 $path = $this->resolveToStoragePath( $path );
800 }
801 $operations[] = array( 'op' => 'delete', 'src' => $path );
802 }
803 // Actually delete files from storage...
804 $opts = array( 'force' => true );
805 if ( $flags & self::SKIP_LOCKING ) {
806 $opts['nonLocking'] = true;
807 }
808 $status->merge( $this->backend->doOperations( $operations, $opts ) );
809
810 return $status;
811 }
812
813 /**
814 * Import a file from the local file system into the repo.
815 * This does no locking nor journaling and overrides existing files.
816 * This function can be used to write to otherwise read-only foreign repos.
817 * This is intended for copying generated thumbnails into the repo.
818 *
819 * @param $src string File system path
820 * @param $dst string Virtual URL or storage path
821 * @return FileRepoStatus
822 */
823 final public function quickImport( $src, $dst ) {
824 return $this->quickImportBatch( array( array( $src, $dst ) ) );
825 }
826
827 /**
828 * Purge a file from the repo. This does no locking nor journaling.
829 * This function can be used to write to otherwise read-only foreign repos.
830 * This is intended for purging thumbnails.
831 *
832 * @param $path string Virtual URL or storage path
833 * @return FileRepoStatus
834 */
835 final public function quickPurge( $path ) {
836 return $this->quickPurgeBatch( array( $path ) );
837 }
838
839 /**
840 * Deletes a directory if empty.
841 * This function can be used to write to otherwise read-only foreign repos.
842 *
843 * @param $dir string Virtual URL (or storage path) of directory to clean
844 * @return Status
845 */
846 public function quickCleanDir( $dir ) {
847 $status = $this->newGood();
848 $status->merge( $this->backend->clean(
849 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
850
851 return $status;
852 }
853
854 /**
855 * Import a batch of files from the local file system into the repo.
856 * This does no locking nor journaling and overrides existing files.
857 * This function can be used to write to otherwise read-only foreign repos.
858 * This is intended for copying generated thumbnails into the repo.
859 *
860 * @param $pairs Array List of tuples (file system path, virtual URL or storage path)
861 * @return FileRepoStatus
862 */
863 public function quickImportBatch( array $pairs ) {
864 $status = $this->newGood();
865 $operations = array();
866 foreach ( $pairs as $pair ) {
867 list ( $src, $dst ) = $pair;
868 $dst = $this->resolveToStoragePath( $dst );
869 $operations[] = array(
870 'op' => 'store',
871 'src' => $src,
872 'dst' => $dst
873 );
874 $status->merge( $this->initDirectory( dirname( $dst ) ) );
875 }
876 $status->merge( $this->backend->doQuickOperations( $operations ) );
877
878 return $status;
879 }
880
881 /**
882 * Purge a batch of files from the repo.
883 * This function can be used to write to otherwise read-only foreign repos.
884 * This does no locking nor journaling and is intended for purging thumbnails.
885 *
886 * @param $paths Array List of virtual URLs or storage paths
887 * @return FileRepoStatus
888 */
889 public function quickPurgeBatch( array $paths ) {
890 $status = $this->newGood();
891 $operations = array();
892 foreach ( $paths as $path ) {
893 $operations[] = array(
894 'op' => 'delete',
895 'src' => $this->resolveToStoragePath( $path ),
896 'ignoreMissingSource' => true
897 );
898 }
899 $status->merge( $this->backend->doQuickOperations( $operations ) );
900
901 return $status;
902 }
903
904 /**
905 * Pick a random name in the temp zone and store a file to it.
906 * Returns a FileRepoStatus object with the file Virtual URL in the value,
907 * file can later be disposed using FileRepo::freeTemp().
908 *
909 * @param $originalName String: the base name of the file as specified
910 * by the user. The file extension will be maintained.
911 * @param $srcPath String: the current location of the file.
912 * @return FileRepoStatus object with the URL in the value.
913 */
914 public function storeTemp( $originalName, $srcPath ) {
915 $this->assertWritableRepo(); // fail out if read-only
916
917 $date = gmdate( "YmdHis" );
918 $hashPath = $this->getHashPath( $originalName );
919 $dstRel = "{$hashPath}{$date}!{$originalName}";
920 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
921
922 $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
923 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
924
925 return $result;
926 }
927
928 /**
929 * Concatenate a list of files into a target file location.
930 *
931 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
932 * @param $dstPath String Target file system path
933 * @param $flags Integer: bitwise combination of the following flags:
934 * self::DELETE_SOURCE Delete the source files
935 * @return FileRepoStatus
936 */
937 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
938 $this->assertWritableRepo(); // fail out if read-only
939
940 $status = $this->newGood();
941
942 $sources = array();
943 $deleteOperations = array(); // post-concatenate ops
944 foreach ( $srcPaths as $srcPath ) {
945 // Resolve source to a storage path if virtual
946 $source = $this->resolveToStoragePath( $srcPath );
947 $sources[] = $source; // chunk to merge
948 if ( $flags & self::DELETE_SOURCE ) {
949 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
950 }
951 }
952
953 // Concatenate the chunks into one FS file
954 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
955 $status->merge( $this->backend->concatenate( $params ) );
956 if ( !$status->isOK() ) {
957 return $status;
958 }
959
960 // Delete the sources if required
961 if ( $deleteOperations ) {
962 $opts = array( 'force' => true );
963 $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
964 }
965
966 // Make sure status is OK, despite any $deleteOperations fatals
967 $status->setResult( true );
968
969 return $status;
970 }
971
972 /**
973 * Remove a temporary file or mark it for garbage collection
974 *
975 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
976 * @return Boolean: true on success, false on failure
977 */
978 public function freeTemp( $virtualUrl ) {
979 $this->assertWritableRepo(); // fail out if read-only
980
981 $temp = "mwrepo://{$this->name}/temp";
982 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
983 wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
984 return false;
985 }
986 $path = $this->resolveVirtualUrl( $virtualUrl );
987
988 return $this->cleanupBatch( array( $path ), self::SKIP_LOCKING )->isOK();
989 }
990
991 /**
992 * Copy or move a file either from a storage path, virtual URL,
993 * or FS path, into this repository at the specified destination location.
994 *
995 * Returns a FileRepoStatus object. On success, the value contains "new" or
996 * "archived", to indicate whether the file was new with that name.
997 *
998 * @param $srcPath String: the source FS path, storage path, or URL
999 * @param $dstRel String: the destination relative path
1000 * @param $archiveRel String: the relative path where the existing file is to
1001 * be archived, if there is one. Relative to the public zone root.
1002 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1003 * that the source file should be deleted if possible
1004 * @return FileRepoStatus
1005 */
1006 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
1007 $this->assertWritableRepo(); // fail out if read-only
1008
1009 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1010 if ( $status->successCount == 0 ) {
1011 $status->ok = false;
1012 }
1013 if ( isset( $status->value[0] ) ) {
1014 $status->value = $status->value[0];
1015 } else {
1016 $status->value = false;
1017 }
1018
1019 return $status;
1020 }
1021
1022 /**
1023 * Publish a batch of files
1024 *
1025 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1026 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1027 * that the source files should be deleted if possible
1028 * @throws MWException
1029 * @return FileRepoStatus
1030 */
1031 public function publishBatch( array $triplets, $flags = 0 ) {
1032 $this->assertWritableRepo(); // fail out if read-only
1033
1034 $backend = $this->backend; // convenience
1035 // Try creating directories
1036 $status = $this->initZones( 'public' );
1037 if ( !$status->isOK() ) {
1038 return $status;
1039 }
1040
1041 $status = $this->newGood( array() );
1042
1043 $operations = array();
1044 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1045 // Validate each triplet and get the store operation...
1046 foreach ( $triplets as $i => $triplet ) {
1047 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1048 // Resolve source to a storage path if virtual
1049 $srcPath = $this->resolveToStoragePath( $srcPath );
1050 if ( !$this->validateFilename( $dstRel ) ) {
1051 throw new MWException( 'Validation error in $dstRel' );
1052 }
1053 if ( !$this->validateFilename( $archiveRel ) ) {
1054 throw new MWException( 'Validation error in $archiveRel' );
1055 }
1056
1057 $publicRoot = $this->getZonePath( 'public' );
1058 $dstPath = "$publicRoot/$dstRel";
1059 $archivePath = "$publicRoot/$archiveRel";
1060
1061 $dstDir = dirname( $dstPath );
1062 $archiveDir = dirname( $archivePath );
1063 // Abort immediately on directory creation errors since they're likely to be repetitive
1064 if ( !$this->initDirectory( $dstDir )->isOK() ) {
1065 return $this->newFatal( 'directorycreateerror', $dstDir );
1066 }
1067 if ( !$this->initDirectory($archiveDir )->isOK() ) {
1068 return $this->newFatal( 'directorycreateerror', $archiveDir );
1069 }
1070
1071 // Archive destination file if it exists
1072 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1073 // Check if the archive file exists
1074 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1075 // unlinks the destination file if it exists. DB-based synchronisation in
1076 // publishBatch's caller should prevent races. In Windows there's no
1077 // problem because the rename primitive fails if the destination exists.
1078 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1079 $operations[] = array( 'op' => 'null' );
1080 continue;
1081 } else {
1082 $operations[] = array(
1083 'op' => 'move',
1084 'src' => $dstPath,
1085 'dst' => $archivePath
1086 );
1087 }
1088 $status->value[$i] = 'archived';
1089 } else {
1090 $status->value[$i] = 'new';
1091 }
1092 // Copy (or move) the source file to the destination
1093 if ( FileBackend::isStoragePath( $srcPath ) ) {
1094 if ( $flags & self::DELETE_SOURCE ) {
1095 $operations[] = array(
1096 'op' => 'move',
1097 'src' => $srcPath,
1098 'dst' => $dstPath
1099 );
1100 } else {
1101 $operations[] = array(
1102 'op' => 'copy',
1103 'src' => $srcPath,
1104 'dst' => $dstPath
1105 );
1106 }
1107 } else { // FS source path
1108 $operations[] = array(
1109 'op' => 'store',
1110 'src' => $srcPath,
1111 'dst' => $dstPath
1112 );
1113 if ( $flags & self::DELETE_SOURCE ) {
1114 $sourceFSFilesToDelete[] = $srcPath;
1115 }
1116 }
1117 }
1118
1119 // Execute the operations for each triplet
1120 $opts = array( 'force' => true );
1121 $status->merge( $backend->doOperations( $operations, $opts ) );
1122 // Cleanup for disk source files...
1123 foreach ( $sourceFSFilesToDelete as $file ) {
1124 wfSuppressWarnings();
1125 unlink( $file ); // FS cleanup
1126 wfRestoreWarnings();
1127 }
1128
1129 return $status;
1130 }
1131
1132 /**
1133 * Creates a directory with the appropriate zone permissions.
1134 * Callers are responsible for doing read-only and "writable repo" checks.
1135 *
1136 * @param $dir string Virtual URL (or storage path) of directory to clean
1137 * @return Status
1138 */
1139 protected function initDirectory( $dir ) {
1140 $path = $this->resolveToStoragePath( $dir );
1141 list( $b, $container, $r ) = FileBackend::splitStoragePath( $path );
1142
1143 $params = array( 'dir' => $path );
1144 if ( $container === $this->zones['deleted']['container'] ) {
1145 # Take all available measures to prevent web accessibility of new deleted
1146 # directories, in case the user has not configured offline storage
1147 $params = array( 'noAccess' => true, 'noListing' => true ) + $params;
1148 }
1149
1150 return $this->backend->prepare( $params );
1151 }
1152
1153 /**
1154 * Deletes a directory if empty.
1155 *
1156 * @param $dir string Virtual URL (or storage path) of directory to clean
1157 * @return Status
1158 */
1159 public function cleanDir( $dir ) {
1160 $this->assertWritableRepo(); // fail out if read-only
1161
1162 $status = $this->newGood();
1163 $status->merge( $this->backend->clean(
1164 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1165
1166 return $status;
1167 }
1168
1169 /**
1170 * Checks existence of a a file
1171 *
1172 * @param $file string Virtual URL (or storage path) of file to check
1173 * @return bool
1174 */
1175 public function fileExists( $file ) {
1176 $result = $this->fileExistsBatch( array( $file ) );
1177 return $result[0];
1178 }
1179
1180 /**
1181 * Checks existence of an array of files.
1182 *
1183 * @param $files Array: Virtual URLs (or storage paths) of files to check
1184 * @return array|bool Either array of files and existence flags, or false
1185 */
1186 public function fileExistsBatch( array $files ) {
1187 $result = array();
1188 foreach ( $files as $key => $file ) {
1189 $file = $this->resolveToStoragePath( $file );
1190 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1191 }
1192 return $result;
1193 }
1194
1195 /**
1196 * Move a file to the deletion archive.
1197 * If no valid deletion archive exists, this may either delete the file
1198 * or throw an exception, depending on the preference of the repository
1199 *
1200 * @param $srcRel Mixed: relative path for the file to be deleted
1201 * @param $archiveRel Mixed: relative path for the archive location.
1202 * Relative to a private archive directory.
1203 * @return FileRepoStatus object
1204 */
1205 public function delete( $srcRel, $archiveRel ) {
1206 $this->assertWritableRepo(); // fail out if read-only
1207
1208 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1209 }
1210
1211 /**
1212 * Move a group of files to the deletion archive.
1213 *
1214 * If no valid deletion archive is configured, this may either delete the
1215 * file or throw an exception, depending on the preference of the repository.
1216 *
1217 * The overwrite policy is determined by the repository -- currently LocalRepo
1218 * assumes a naming scheme in the deleted zone based on content hash, as
1219 * opposed to the public zone which is assumed to be unique.
1220 *
1221 * @param $sourceDestPairs Array of source/destination pairs. Each element
1222 * is a two-element array containing the source file path relative to the
1223 * public root in the first element, and the archive file path relative
1224 * to the deleted zone root in the second element.
1225 * @throws MWException
1226 * @return FileRepoStatus
1227 */
1228 public function deleteBatch( array $sourceDestPairs ) {
1229 $this->assertWritableRepo(); // fail out if read-only
1230
1231 // Try creating directories
1232 $status = $this->initZones( array( 'public', 'deleted' ) );
1233 if ( !$status->isOK() ) {
1234 return $status;
1235 }
1236
1237 $status = $this->newGood();
1238
1239 $backend = $this->backend; // convenience
1240 $operations = array();
1241 // Validate filenames and create archive directories
1242 foreach ( $sourceDestPairs as $pair ) {
1243 list( $srcRel, $archiveRel ) = $pair;
1244 if ( !$this->validateFilename( $srcRel ) ) {
1245 throw new MWException( __METHOD__.':Validation error in $srcRel' );
1246 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1247 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
1248 }
1249
1250 $publicRoot = $this->getZonePath( 'public' );
1251 $srcPath = "{$publicRoot}/$srcRel";
1252
1253 $deletedRoot = $this->getZonePath( 'deleted' );
1254 $archivePath = "{$deletedRoot}/{$archiveRel}";
1255 $archiveDir = dirname( $archivePath ); // does not touch FS
1256
1257 // Create destination directories
1258 if ( !$this->initDirectory( $archiveDir )->isOK() ) {
1259 return $this->newFatal( 'directorycreateerror', $archiveDir );
1260 }
1261
1262 $operations[] = array(
1263 'op' => 'move',
1264 'src' => $srcPath,
1265 'dst' => $archivePath,
1266 // We may have 2+ identical files being deleted,
1267 // all of which will map to the same destination file
1268 'overwriteSame' => true // also see bug 31792
1269 );
1270 }
1271
1272 // Move the files by execute the operations for each pair.
1273 // We're now committed to returning an OK result, which will
1274 // lead to the files being moved in the DB also.
1275 $opts = array( 'force' => true );
1276 $status->merge( $backend->doOperations( $operations, $opts ) );
1277
1278 return $status;
1279 }
1280
1281 /**
1282 * Delete files in the deleted directory if they are not referenced in the filearchive table
1283 *
1284 * STUB
1285 */
1286 public function cleanupDeletedBatch( array $storageKeys ) {
1287 $this->assertWritableRepo();
1288 }
1289
1290 /**
1291 * Get a relative path for a deletion archive key,
1292 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1293 *
1294 * @param $key string
1295 * @return string
1296 */
1297 public function getDeletedHashPath( $key ) {
1298 $path = '';
1299 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1300 $path .= $key[$i] . '/';
1301 }
1302 return $path;
1303 }
1304
1305 /**
1306 * If a path is a virtual URL, resolve it to a storage path.
1307 * Otherwise, just return the path as it is.
1308 *
1309 * @param $path string
1310 * @return string
1311 * @throws MWException
1312 */
1313 protected function resolveToStoragePath( $path ) {
1314 if ( $this->isVirtualUrl( $path ) ) {
1315 return $this->resolveVirtualUrl( $path );
1316 }
1317 return $path;
1318 }
1319
1320 /**
1321 * Get a local FS copy of a file with a given virtual URL/storage path.
1322 * Temporary files may be purged when the file object falls out of scope.
1323 *
1324 * @param $virtualUrl string
1325 * @return TempFSFile|null Returns null on failure
1326 */
1327 public function getLocalCopy( $virtualUrl ) {
1328 $path = $this->resolveToStoragePath( $virtualUrl );
1329 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1330 }
1331
1332 /**
1333 * Get a local FS file with a given virtual URL/storage path.
1334 * The file is either an original or a copy. It should not be changed.
1335 * Temporary files may be purged when the file object falls out of scope.
1336 *
1337 * @param $virtualUrl string
1338 * @return FSFile|null Returns null on failure.
1339 */
1340 public function getLocalReference( $virtualUrl ) {
1341 $path = $this->resolveToStoragePath( $virtualUrl );
1342 return $this->backend->getLocalReference( array( 'src' => $path ) );
1343 }
1344
1345 /**
1346 * Get properties of a file with a given virtual URL/storage path.
1347 * Properties should ultimately be obtained via FSFile::getProps().
1348 *
1349 * @param $virtualUrl string
1350 * @return Array
1351 */
1352 public function getFileProps( $virtualUrl ) {
1353 $path = $this->resolveToStoragePath( $virtualUrl );
1354 return $this->backend->getFileProps( array( 'src' => $path ) );
1355 }
1356
1357 /**
1358 * Get the timestamp of a file with a given virtual URL/storage path
1359 *
1360 * @param $virtualUrl string
1361 * @return string|bool False on failure
1362 */
1363 public function getFileTimestamp( $virtualUrl ) {
1364 $path = $this->resolveToStoragePath( $virtualUrl );
1365 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1366 }
1367
1368 /**
1369 * Get the sha1 of a file with a given virtual URL/storage path
1370 *
1371 * @param $virtualUrl string
1372 * @return string|bool
1373 */
1374 public function getFileSha1( $virtualUrl ) {
1375 $path = $this->resolveToStoragePath( $virtualUrl );
1376 $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
1377 if ( !$tmpFile ) {
1378 return false;
1379 }
1380 return $tmpFile->getSha1Base36();
1381 }
1382
1383 /**
1384 * Attempt to stream a file with the given virtual URL/storage path
1385 *
1386 * @param $virtualUrl string
1387 * @param $headers Array Additional HTTP headers to send on success
1388 * @return bool Success
1389 */
1390 public function streamFile( $virtualUrl, $headers = array() ) {
1391 $path = $this->resolveToStoragePath( $virtualUrl );
1392 $params = array( 'src' => $path, 'headers' => $headers );
1393 return $this->backend->streamFile( $params )->isOK();
1394 }
1395
1396 /**
1397 * Call a callback function for every public regular file in the repository.
1398 * This only acts on the current version of files, not any old versions.
1399 * May use either the database or the filesystem.
1400 *
1401 * @param $callback Array|string
1402 * @return void
1403 */
1404 public function enumFiles( $callback ) {
1405 $this->enumFilesInStorage( $callback );
1406 }
1407
1408 /**
1409 * Call a callback function for every public file in the repository.
1410 * May use either the database or the filesystem.
1411 *
1412 * @param $callback Array|string
1413 * @return void
1414 */
1415 protected function enumFilesInStorage( $callback ) {
1416 $publicRoot = $this->getZonePath( 'public' );
1417 $numDirs = 1 << ( $this->hashLevels * 4 );
1418 // Use a priori assumptions about directory structure
1419 // to reduce the tree height of the scanning process.
1420 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1421 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1422 $path = $publicRoot;
1423 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1424 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1425 }
1426 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1427 foreach ( $iterator as $name ) {
1428 // Each item returned is a public file
1429 call_user_func( $callback, "{$path}/{$name}" );
1430 }
1431 }
1432 }
1433
1434 /**
1435 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1436 *
1437 * @param $filename string
1438 * @return bool
1439 */
1440 public function validateFilename( $filename ) {
1441 if ( strval( $filename ) == '' ) {
1442 return false;
1443 }
1444 return FileBackend::isPathTraversalFree( $filename );
1445 }
1446
1447 /**
1448 * Get a callback function to use for cleaning error message parameters
1449 *
1450 * @return Array
1451 */
1452 function getErrorCleanupFunction() {
1453 switch ( $this->pathDisclosureProtection ) {
1454 case 'none':
1455 case 'simple': // b/c
1456 $callback = array( $this, 'passThrough' );
1457 break;
1458 default: // 'paranoid'
1459 $callback = array( $this, 'paranoidClean' );
1460 }
1461 return $callback;
1462 }
1463
1464 /**
1465 * Path disclosure protection function
1466 *
1467 * @param $param string
1468 * @return string
1469 */
1470 function paranoidClean( $param ) {
1471 return '[hidden]';
1472 }
1473
1474 /**
1475 * Path disclosure protection function
1476 *
1477 * @param $param string
1478 * @return string
1479 */
1480 function passThrough( $param ) {
1481 return $param;
1482 }
1483
1484 /**
1485 * Create a new fatal error
1486 *
1487 * @return FileRepoStatus
1488 */
1489 public function newFatal( $message /*, parameters...*/ ) {
1490 $params = func_get_args();
1491 array_unshift( $params, $this );
1492 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1493 }
1494
1495 /**
1496 * Create a new good result
1497 *
1498 * @param $value null|string
1499 * @return FileRepoStatus
1500 */
1501 public function newGood( $value = null ) {
1502 return FileRepoStatus::newGood( $this, $value );
1503 }
1504
1505 /**
1506 * Checks if there is a redirect named as $title. If there is, return the
1507 * title object. If not, return false.
1508 * STUB
1509 *
1510 * @param $title Title of image
1511 * @return Bool
1512 */
1513 public function checkRedirect( Title $title ) {
1514 return false;
1515 }
1516
1517 /**
1518 * Invalidates image redirect cache related to that image
1519 * Doesn't do anything for repositories that don't support image redirects.
1520 *
1521 * STUB
1522 * @param $title Title of image
1523 */
1524 public function invalidateImageRedirect( Title $title ) {}
1525
1526 /**
1527 * Get the human-readable name of the repo
1528 *
1529 * @return string
1530 */
1531 public function getDisplayName() {
1532 // We don't name our own repo, return nothing
1533 if ( $this->isLocal() ) {
1534 return null;
1535 }
1536 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1537 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1538 }
1539
1540 /**
1541 * Returns true if this the local file repository.
1542 *
1543 * @return bool
1544 */
1545 public function isLocal() {
1546 return $this->getName() == 'local';
1547 }
1548
1549 /**
1550 * Get a key on the primary cache for this repository.
1551 * Returns false if the repository's cache is not accessible at this site.
1552 * The parameters are the parts of the key, as for wfMemcKey().
1553 *
1554 * STUB
1555 * @return bool
1556 */
1557 public function getSharedCacheKey( /*...*/ ) {
1558 return false;
1559 }
1560
1561 /**
1562 * Get a key for this repo in the local cache domain. These cache keys are
1563 * not shared with remote instances of the repo.
1564 * The parameters are the parts of the key, as for wfMemcKey().
1565 *
1566 * @return string
1567 */
1568 public function getLocalCacheKey( /*...*/ ) {
1569 $args = func_get_args();
1570 array_unshift( $args, 'filerepo', $this->getName() );
1571 return call_user_func_array( 'wfMemcKey', $args );
1572 }
1573
1574 /**
1575 * Get an temporary FileRepo associated with this repo.
1576 * Files will be created in the temp zone of this repo and
1577 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1578 * It will have the same backend as this repo.
1579 *
1580 * @return TempFileRepo
1581 */
1582 public function getTempRepo() {
1583 return new TempFileRepo( array(
1584 'name' => "{$this->name}-temp",
1585 'backend' => $this->backend,
1586 'zones' => array(
1587 'public' => array(
1588 'container' => $this->zones['temp']['container'],
1589 'directory' => $this->zones['temp']['directory']
1590 ),
1591 'thumb' => array(
1592 'container' => $this->zones['thumb']['container'],
1593 'directory' => ( $this->zones['thumb']['directory'] == '' )
1594 ? 'temp'
1595 : $this->zones['thumb']['directory'] . '/temp'
1596 )
1597 ),
1598 'url' => $this->getZoneUrl( 'temp' ),
1599 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1600 'hashLevels' => $this->hashLevels // performance
1601 ) );
1602 }
1603
1604 /**
1605 * Get an UploadStash associated with this repo.
1606 *
1607 * @return UploadStash
1608 */
1609 public function getUploadStash() {
1610 return new UploadStash( $this );
1611 }
1612
1613 /**
1614 * Throw an exception if this repo is read-only by design.
1615 * This does not and should not check getReadOnlyReason().
1616 *
1617 * @return void
1618 * @throws MWException
1619 */
1620 protected function assertWritableRepo() {}
1621 }
1622
1623 /**
1624 * FileRepo for temporary files created via FileRepo::getTempRepo()
1625 */
1626 class TempFileRepo extends FileRepo {
1627 public function getTempRepo() {
1628 throw new MWException( "Cannot get a temp repo from a temp repo." );
1629 }
1630 }