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