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