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