Make the instantiation tests actually work.
[lhc/web/wiklou.git] / includes / filerepo / FSRepo.php
1 <?php
2
3 /**
4 * A repository for files accessible via the local filesystem. Does not support
5 * database access or registration.
6 * @ingroup FileRepo
7 */
8 class FSRepo extends FileRepo {
9 var $directory, $deletedDir, $deletedHashLevels, $fileMode;
10 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
11 var $oldFileFactory = false;
12 var $pathDisclosureProtection = 'simple';
13
14 function __construct( $info ) {
15 parent::__construct( $info );
16
17 // Required settings
18 $this->directory = $info['directory'];
19 $this->url = $info['url'];
20
21 // Optional settings
22 $this->hashLevels = isset( $info['hashLevels'] ) ? $info['hashLevels'] : 2;
23 $this->deletedHashLevels = isset( $info['deletedHashLevels'] ) ?
24 $info['deletedHashLevels'] : $this->hashLevels;
25 $this->deletedDir = isset( $info['deletedDir'] ) ? $info['deletedDir'] : false;
26 $this->fileMode = isset( $info['fileMode'] ) ? $info['fileMode'] : 0644;
27 if ( isset( $info['thumbDir'] ) ) {
28 $this->thumbDir = $info['thumbDir'];
29 } else {
30 $this->thumbDir = "{$this->directory}/thumb";
31 }
32 if ( isset( $info['thumbUrl'] ) ) {
33 $this->thumbUrl = $info['thumbUrl'];
34 } else {
35 $this->thumbUrl = "{$this->url}/thumb";
36 }
37 }
38
39 /**
40 * Get the public root directory of the repository.
41 */
42 function getRootDirectory() {
43 return $this->directory;
44 }
45
46 /**
47 * Get the public root URL of the repository
48 */
49 function getRootUrl() {
50 return $this->url;
51 }
52
53 /**
54 * Returns true if the repository uses a multi-level directory structure
55 */
56 function isHashed() {
57 return (bool)$this->hashLevels;
58 }
59
60 /**
61 * Get the local directory corresponding to one of the three basic zones
62 */
63 function getZonePath( $zone ) {
64 switch ( $zone ) {
65 case 'public':
66 return $this->directory;
67 case 'temp':
68 return "{$this->directory}/temp";
69 case 'deleted':
70 return $this->deletedDir;
71 case 'thumb':
72 return $this->thumbDir;
73 default:
74 return false;
75 }
76 }
77
78 /**
79 * @see FileRepo::getZoneUrl()
80 */
81 function getZoneUrl( $zone ) {
82 switch ( $zone ) {
83 case 'public':
84 return $this->url;
85 case 'temp':
86 return "{$this->url}/temp";
87 case 'deleted':
88 return parent::getZoneUrl( $zone ); // no public URL
89 case 'thumb':
90 return $this->thumbUrl;
91 default:
92 return parent::getZoneUrl( $zone );
93 }
94 }
95
96 /**
97 * Get a URL referring to this repository, with the private mwrepo protocol.
98 * The suffix, if supplied, is considered to be unencoded, and will be
99 * URL-encoded before being returned.
100 */
101 function getVirtualUrl( $suffix = false ) {
102 $path = 'mwrepo://' . $this->name;
103 if ( $suffix !== false ) {
104 $path .= '/' . rawurlencode( $suffix );
105 }
106 return $path;
107 }
108
109 /**
110 * Get the local path corresponding to a virtual URL
111 */
112 function resolveVirtualUrl( $url ) {
113 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
114 throw new MWException( __METHOD__.': unknown protoocl' );
115 }
116
117 $bits = explode( '/', substr( $url, 9 ), 3 );
118 if ( count( $bits ) != 3 ) {
119 throw new MWException( __METHOD__.": invalid mwrepo URL: $url" );
120 }
121 list( $repo, $zone, $rel ) = $bits;
122 if ( $repo !== $this->name ) {
123 throw new MWException( __METHOD__.": fetching from a foreign repo is not supported" );
124 }
125 $base = $this->getZonePath( $zone );
126 if ( !$base ) {
127 throw new MWException( __METHOD__.": invalid zone: $zone" );
128 }
129 return $base . '/' . rawurldecode( $rel );
130 }
131
132 /**
133 * Store a batch of files
134 *
135 * @param array $triplets (src,zone,dest) triplets as per store()
136 * @param integer $flags Bitwise combination of the following flags:
137 * self::DELETE_SOURCE Delete the source file after upload
138 * self::OVERWRITE Overwrite an existing destination file instead of failing
139 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
140 * same contents as the source
141 */
142 function storeBatch( $triplets, $flags = 0 ) {
143 if ( !wfMkdirParents( $this->directory ) ) {
144 return $this->newFatal( 'upload_directory_missing', $this->directory );
145 }
146 if ( !is_writable( $this->directory ) ) {
147 return $this->newFatal( 'upload_directory_read_only', $this->directory );
148 }
149 $status = $this->newGood();
150 foreach ( $triplets as $i => $triplet ) {
151 list( $srcPath, $dstZone, $dstRel ) = $triplet;
152
153 $root = $this->getZonePath( $dstZone );
154 if ( !$root ) {
155 throw new MWException( "Invalid zone: $dstZone" );
156 }
157 if ( !$this->validateFilename( $dstRel ) ) {
158 throw new MWException( 'Validation error in $dstRel' );
159 }
160 $dstPath = "$root/$dstRel";
161 $dstDir = dirname( $dstPath );
162
163 if ( !is_dir( $dstDir ) ) {
164 if ( !wfMkdirParents( $dstDir ) ) {
165 return $this->newFatal( 'directorycreateerror', $dstDir );
166 }
167 if ( $dstZone == 'deleted' ) {
168 $this->initDeletedDir( $dstDir );
169 }
170 }
171
172 if ( self::isVirtualUrl( $srcPath ) ) {
173 $srcPath = $triplets[$i][0] = $this->resolveVirtualUrl( $srcPath );
174 }
175 if ( !is_file( $srcPath ) ) {
176 // Make a list of files that don't exist for return to the caller
177 $status->fatal( 'filenotfound', $srcPath );
178 continue;
179 }
180 if ( !( $flags & self::OVERWRITE ) && file_exists( $dstPath ) ) {
181 if ( $flags & self::OVERWRITE_SAME ) {
182 $hashSource = sha1_file( $srcPath );
183 $hashDest = sha1_file( $dstPath );
184 if ( $hashSource != $hashDest ) {
185 $status->fatal( 'fileexistserror', $dstPath );
186 }
187 } else {
188 $status->fatal( 'fileexistserror', $dstPath );
189 }
190 }
191 }
192
193 $deleteDest = wfIsWindows() && ( $flags & self::OVERWRITE );
194
195 // Abort now on failure
196 if ( !$status->ok ) {
197 return $status;
198 }
199
200 foreach ( $triplets as $triplet ) {
201 list( $srcPath, $dstZone, $dstRel ) = $triplet;
202 $root = $this->getZonePath( $dstZone );
203 $dstPath = "$root/$dstRel";
204 $good = true;
205
206 if ( $flags & self::DELETE_SOURCE ) {
207 if ( $deleteDest ) {
208 unlink( $dstPath );
209 }
210 if ( !rename( $srcPath, $dstPath ) ) {
211 $status->error( 'filerenameerror', $srcPath, $dstPath );
212 $good = false;
213 }
214 } else {
215 if ( !copy( $srcPath, $dstPath ) ) {
216 $status->error( 'filecopyerror', $srcPath, $dstPath );
217 $good = false;
218 }
219 }
220 if ( $good ) {
221 $this->chmod( $dstPath );
222 $status->successCount++;
223 } else {
224 $status->failCount++;
225 }
226 }
227 return $status;
228 }
229
230 /**
231 * Checks existence of specified array of files.
232 *
233 * @param array $files URLs of files to check
234 * @param integer $flags Bitwise combination of the following flags:
235 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
236 * @return Either array of files and existence flags, or false
237 */
238 function fileExistsBatch( $files, $flags = 0 ) {
239 if ( !file_exists( $this->directory ) || !is_readable( $this->directory ) ) {
240 return false;
241 }
242 $result = array();
243 foreach ( $files as $key => $file ) {
244 if ( self::isVirtualUrl( $file ) ) {
245 $file = $this->resolveVirtualUrl( $file );
246 }
247 if( $flags & self::FILES_ONLY ) {
248 $result[$key] = is_file( $file );
249 } else {
250 $result[$key] = file_exists( $file );
251 }
252 }
253
254 return $result;
255 }
256
257 /**
258 * Take all available measures to prevent web accessibility of new deleted
259 * directories, in case the user has not configured offline storage
260 */
261 protected function initDeletedDir( $dir ) {
262 // Add a .htaccess file to the root of the deleted zone
263 $root = $this->getZonePath( 'deleted' );
264 if ( !file_exists( "$root/.htaccess" ) ) {
265 file_put_contents( "$root/.htaccess", "Deny from all\n" );
266 }
267 // Seed new directories with a blank index.html, to prevent crawling
268 file_put_contents( "$dir/index.html", '' );
269 }
270
271 /**
272 * Pick a random name in the temp zone and store a file to it.
273 * @param string $originalName The base name of the file as specified
274 * by the user. The file extension will be maintained.
275 * @param string $srcPath The current location of the file.
276 * @return FileRepoStatus object with the URL in the value.
277 */
278 function storeTemp( $originalName, $srcPath ) {
279 $date = gmdate( "YmdHis" );
280 $hashPath = $this->getHashPath( $originalName );
281 $dstRel = "$hashPath$date!$originalName";
282 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
283
284 $result = $this->store( $srcPath, 'temp', $dstRel );
285 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
286 return $result;
287 }
288
289 /**
290 * Remove a temporary file or mark it for garbage collection
291 * @param string $virtualUrl The virtual URL returned by storeTemp
292 * @return boolean True on success, false on failure
293 */
294 function freeTemp( $virtualUrl ) {
295 $temp = "mwrepo://{$this->name}/temp";
296 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
297 wfDebug( __METHOD__.": Invalid virtual URL\n" );
298 return false;
299 }
300 $path = $this->resolveVirtualUrl( $virtualUrl );
301 wfSuppressWarnings();
302 $success = unlink( $path );
303 wfRestoreWarnings();
304 return $success;
305 }
306
307 /**
308 * Publish a batch of files
309 * @param array $triplets (source,dest,archive) triplets as per publish()
310 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
311 * that the source files should be deleted if possible
312 */
313 function publishBatch( $triplets, $flags = 0 ) {
314 // Perform initial checks
315 if ( !wfMkdirParents( $this->directory ) ) {
316 return $this->newFatal( 'upload_directory_missing', $this->directory );
317 }
318 if ( !is_writable( $this->directory ) ) {
319 return $this->newFatal( 'upload_directory_read_only', $this->directory );
320 }
321 $status = $this->newGood( array() );
322 foreach ( $triplets as $i => $triplet ) {
323 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
324
325 if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
326 $triplets[$i][0] = $srcPath = $this->resolveVirtualUrl( $srcPath );
327 }
328 if ( !$this->validateFilename( $dstRel ) ) {
329 throw new MWException( 'Validation error in $dstRel' );
330 }
331 if ( !$this->validateFilename( $archiveRel ) ) {
332 throw new MWException( 'Validation error in $archiveRel' );
333 }
334 $dstPath = "{$this->directory}/$dstRel";
335 $archivePath = "{$this->directory}/$archiveRel";
336
337 $dstDir = dirname( $dstPath );
338 $archiveDir = dirname( $archivePath );
339 // Abort immediately on directory creation errors since they're likely to be repetitive
340 if ( !is_dir( $dstDir ) && !wfMkdirParents( $dstDir ) ) {
341 return $this->newFatal( 'directorycreateerror', $dstDir );
342 }
343 if ( !is_dir( $archiveDir ) && !wfMkdirParents( $archiveDir ) ) {
344 return $this->newFatal( 'directorycreateerror', $archiveDir );
345 }
346 if ( !is_file( $srcPath ) ) {
347 // Make a list of files that don't exist for return to the caller
348 $status->fatal( 'filenotfound', $srcPath );
349 }
350 }
351
352 if ( !$status->ok ) {
353 return $status;
354 }
355
356 foreach ( $triplets as $i => $triplet ) {
357 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
358 $dstPath = "{$this->directory}/$dstRel";
359 $archivePath = "{$this->directory}/$archiveRel";
360
361 // Archive destination file if it exists
362 if( is_file( $dstPath ) ) {
363 // Check if the archive file exists
364 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
365 // unlinks the destination file if it exists. DB-based synchronisation in
366 // publishBatch's caller should prevent races. In Windows there's no
367 // problem because the rename primitive fails if the destination exists.
368 if ( is_file( $archivePath ) ) {
369 $success = false;
370 } else {
371 wfSuppressWarnings();
372 $success = rename( $dstPath, $archivePath );
373 wfRestoreWarnings();
374 }
375
376 if( !$success ) {
377 $status->error( 'filerenameerror',$dstPath, $archivePath );
378 $status->failCount++;
379 continue;
380 } else {
381 wfDebug(__METHOD__.": moved file $dstPath to $archivePath\n");
382 }
383 $status->value[$i] = 'archived';
384 } else {
385 $status->value[$i] = 'new';
386 }
387
388 $good = true;
389 wfSuppressWarnings();
390 if ( $flags & self::DELETE_SOURCE ) {
391 if ( !rename( $srcPath, $dstPath ) ) {
392 $status->error( 'filerenameerror', $srcPath, $dstPath );
393 $good = false;
394 }
395 } else {
396 if ( !copy( $srcPath, $dstPath ) ) {
397 $status->error( 'filecopyerror', $srcPath, $dstPath );
398 $good = false;
399 }
400 }
401 wfRestoreWarnings();
402
403 if ( $good ) {
404 $status->successCount++;
405 wfDebug(__METHOD__.": wrote tempfile $srcPath to $dstPath\n");
406 // Thread-safe override for umask
407 $this->chmod( $dstPath );
408 } else {
409 $status->failCount++;
410 }
411 }
412 return $status;
413 }
414
415 /**
416 * Move a group of files to the deletion archive.
417 * If no valid deletion archive is configured, this may either delete the
418 * file or throw an exception, depending on the preference of the repository.
419 *
420 * @param array $sourceDestPairs Array of source/destination pairs. Each element
421 * is a two-element array containing the source file path relative to the
422 * public root in the first element, and the archive file path relative
423 * to the deleted zone root in the second element.
424 * @return FileRepoStatus
425 */
426 function deleteBatch( $sourceDestPairs ) {
427 $status = $this->newGood();
428 if ( !$this->deletedDir ) {
429 throw new MWException( __METHOD__.': no valid deletion archive directory' );
430 }
431
432 /**
433 * Validate filenames and create archive directories
434 */
435 foreach ( $sourceDestPairs as $pair ) {
436 list( $srcRel, $archiveRel ) = $pair;
437 if ( !$this->validateFilename( $srcRel ) ) {
438 throw new MWException( __METHOD__.':Validation error in $srcRel' );
439 }
440 if ( !$this->validateFilename( $archiveRel ) ) {
441 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
442 }
443 $archivePath = "{$this->deletedDir}/$archiveRel";
444 $archiveDir = dirname( $archivePath );
445 if ( !is_dir( $archiveDir ) ) {
446 if ( !wfMkdirParents( $archiveDir ) ) {
447 $status->fatal( 'directorycreateerror', $archiveDir );
448 continue;
449 }
450 $this->initDeletedDir( $archiveDir );
451 }
452 // Check if the archive directory is writable
453 // This doesn't appear to work on NTFS
454 if ( !is_writable( $archiveDir ) ) {
455 $status->fatal( 'filedelete-archive-read-only', $archiveDir );
456 }
457 }
458 if ( !$status->ok ) {
459 // Abort early
460 return $status;
461 }
462
463 /**
464 * Move the files
465 * We're now committed to returning an OK result, which will lead to
466 * the files being moved in the DB also.
467 */
468 foreach ( $sourceDestPairs as $pair ) {
469 list( $srcRel, $archiveRel ) = $pair;
470 $srcPath = "{$this->directory}/$srcRel";
471 $archivePath = "{$this->deletedDir}/$archiveRel";
472 $good = true;
473 if ( file_exists( $archivePath ) ) {
474 # A file with this content hash is already archived
475 if ( !@unlink( $srcPath ) ) {
476 $status->error( 'filedeleteerror', $srcPath );
477 $good = false;
478 }
479 } else{
480 if ( !@rename( $srcPath, $archivePath ) ) {
481 $status->error( 'filerenameerror', $srcPath, $archivePath );
482 $good = false;
483 } else {
484 $this->chmod( $archivePath );
485 }
486 }
487 if ( $good ) {
488 $status->successCount++;
489 } else {
490 $status->failCount++;
491 }
492 }
493 return $status;
494 }
495
496 /**
497 * Get a relative path for a deletion archive key,
498 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
499 */
500 function getDeletedHashPath( $key ) {
501 $path = '';
502 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
503 $path .= $key[$i] . '/';
504 }
505 return $path;
506 }
507
508 /**
509 * Call a callback function for every file in the repository.
510 * Uses the filesystem even in child classes.
511 */
512 function enumFilesInFS( $callback ) {
513 $numDirs = 1 << ( $this->hashLevels * 4 );
514 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
515 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
516 $path = $this->directory;
517 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
518 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
519 }
520 if ( !file_exists( $path ) || !is_dir( $path ) ) {
521 continue;
522 }
523 $dir = opendir( $path );
524 while ( false !== ( $name = readdir( $dir ) ) ) {
525 call_user_func( $callback, $path . '/' . $name );
526 }
527 }
528 }
529
530 /**
531 * Call a callback function for every file in the repository
532 * May use either the database or the filesystem
533 */
534 function enumFiles( $callback ) {
535 $this->enumFilesInFS( $callback );
536 }
537
538 /**
539 * Get properties of a file with a given virtual URL
540 * The virtual URL must refer to this repo
541 */
542 function getFileProps( $virtualUrl ) {
543 $path = $this->resolveVirtualUrl( $virtualUrl );
544 return File::getPropsFromPath( $path );
545 }
546
547 /**
548 * Path disclosure protection functions
549 *
550 * Get a callback function to use for cleaning error message parameters
551 */
552 function getErrorCleanupFunction() {
553 switch ( $this->pathDisclosureProtection ) {
554 case 'simple':
555 $callback = array( $this, 'simpleClean' );
556 break;
557 default:
558 $callback = parent::getErrorCleanupFunction();
559 }
560 return $callback;
561 }
562
563 function simpleClean( $param ) {
564 if ( !isset( $this->simpleCleanPairs ) ) {
565 global $IP;
566 $this->simpleCleanPairs = array(
567 $this->directory => 'public',
568 "{$this->directory}/temp" => 'temp',
569 $IP => '$IP',
570 dirname( __FILE__ ) => '$IP/extensions/WebStore',
571 );
572 if ( $this->deletedDir ) {
573 $this->simpleCleanPairs[$this->deletedDir] = 'deleted';
574 }
575 }
576 return strtr( $param, $this->simpleCleanPairs );
577 }
578
579 /**
580 * Chmod a file, supressing the warnings.
581 * @param String $path The path to change
582 */
583 protected function chmod( $path ) {
584 wfSuppressWarnings();
585 chmod( $path, $this->fileMode );
586 wfRestoreWarnings();
587 }
588
589 }