findFileFromKey, newFileFromKey, $fileFactoryKey, and $oldFileFactoryKey weren't...
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2 /**
3 * Base code for file repositories.
4 *
5 * @file
6 * @ingroup FileRepo
7 */
8
9 /**
10 * Base class for file repositories.
11 * Do not instantiate, use a derived class.
12 *
13 * @ingroup FileRepo
14 */
15 abstract class FileRepo {
16 const FILES_ONLY = 1;
17 const DELETE_SOURCE = 1;
18 const OVERWRITE = 2;
19 const OVERWRITE_SAME = 4;
20 const SKIP_VALIDATION = 8;
21
22 var $thumbScriptUrl, $transformVia404;
23 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
24 var $fetchDescription, $initialCapital;
25 var $pathDisclosureProtection = 'paranoid';
26 var $descriptionCacheExpiry, $hashLevels, $url, $thumbUrl;
27
28 /**
29 * Factory functions for creating new files
30 * Override these in the base class
31 */
32 var $fileFactory = false, $oldFileFactory = false;
33
34 function __construct( $info ) {
35 // Required settings
36 $this->name = $info['name'];
37
38 // Optional settings
39 $this->initialCapital = MWNamespace::isCapitalized( NS_FILE );
40 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
41 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection',
42 'descriptionCacheExpiry', 'hashLevels', 'url', 'thumbUrl', 'scriptExtension' )
43 as $var )
44 {
45 if ( isset( $info[$var] ) ) {
46 $this->$var = $info[$var];
47 }
48 }
49 $this->transformVia404 = !empty( $info['transformVia404'] );
50 }
51
52 /**
53 * Determine if a string is an mwrepo:// URL
54 */
55 static function isVirtualUrl( $url ) {
56 return substr( $url, 0, 9 ) == 'mwrepo://';
57 }
58
59 /**
60 * Create a new File object from the local repository
61 *
62 * @param $title Mixed: Title object or string
63 * @param $time Mixed: Time at which the image was uploaded.
64 * If this is specified, the returned object will be an
65 * instance of the repository's old file class instead of a
66 * current file. Repositories not supporting version control
67 * should return false if this parameter is set.
68 *
69 * @return File
70 */
71 function newFile( $title, $time = false ) {
72 if ( !($title instanceof Title) ) {
73 $title = Title::makeTitleSafe( NS_FILE, $title );
74 if ( !is_object( $title ) ) {
75 return null;
76 }
77 }
78 if ( $time ) {
79 if ( $this->oldFileFactory ) {
80 return call_user_func( $this->oldFileFactory, $title, $this, $time );
81 } else {
82 return false;
83 }
84 } else {
85 return call_user_func( $this->fileFactory, $title, $this );
86 }
87 }
88
89 /**
90 * Find an instance of the named file created at the specified time
91 * Returns false if the file does not exist. Repositories not supporting
92 * version control should return false if the time is specified.
93 *
94 * @param $title Mixed: Title object or string
95 * @param $options Associative array of options:
96 * time: requested time for an archived image, or false for the
97 * current version. An image object will be returned which was
98 * created at the specified time.
99 *
100 * ignoreRedirect: If true, do not follow file redirects
101 *
102 * private: If true, return restricted (deleted) files if the current
103 * user is allowed to view them. Otherwise, such files will not
104 * be found.
105 */
106 function findFile( $title, $options = array() ) {
107 $time = isset( $options['time'] ) ? $options['time'] : false;
108 if ( !($title instanceof Title) ) {
109 $title = Title::makeTitleSafe( NS_FILE, $title );
110 if ( !is_object( $title ) ) {
111 return false;
112 }
113 }
114 # First try the current version of the file to see if it precedes the timestamp
115 $img = $this->newFile( $title );
116 if ( !$img ) {
117 return false;
118 }
119 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
120 return $img;
121 }
122 # Now try an old version of the file
123 if ( $time !== false ) {
124 $img = $this->newFile( $title, $time );
125 if ( $img && $img->exists() ) {
126 if ( !$img->isDeleted(File::DELETED_FILE) ) {
127 return $img;
128 } else if ( !empty( $options['private'] ) && $img->userCan(File::DELETED_FILE) ) {
129 return $img;
130 }
131 }
132 }
133
134 # Now try redirects
135 if ( !empty( $options['ignoreRedirect'] ) ) {
136 return false;
137 }
138 $redir = $this->checkRedirect( $title );
139 if( $redir && $title->getNamespace() == NS_FILE) {
140 $img = $this->newFile( $redir );
141 if( !$img ) {
142 return false;
143 }
144 if( $img->exists() ) {
145 $img->redirectedFrom( $title->getDBkey() );
146 return $img;
147 }
148 }
149 return false;
150 }
151
152 /*
153 * Find many files at once.
154 * @param $items An array of titles, or an array of findFile() options with
155 * the "title" option giving the title. Example:
156 *
157 * $findItem = array( 'title' => $title, 'private' => true );
158 * $findBatch = array( $findItem );
159 * $repo->findFiles( $findBatch );
160 */
161 function findFiles( $items ) {
162 $result = array();
163 foreach ( $items as $item ) {
164 if ( is_array( $item ) ) {
165 $title = $item['title'];
166 $options = $item;
167 unset( $options['title'] );
168 } else {
169 $title = $item;
170 $options = array();
171 }
172 $file = $this->findFile( $title, $options );
173 if ( $file ) {
174 $result[$file->getTitle()->getDBkey()] = $file;
175 }
176 }
177 return $result;
178 }
179
180 /**
181 * Get the URL of thumb.php
182 */
183 function getThumbScriptUrl() {
184 return $this->thumbScriptUrl;
185 }
186
187 /**
188 * Get the URL corresponding to one of the four basic zones
189 * @param $zone String: one of: public, deleted, temp, thumb
190 * @return String or false
191 */
192 function getZoneUrl( $zone ) {
193 return false;
194 }
195
196 /**
197 * Returns true if the repository can transform files via a 404 handler
198 */
199 function canTransformVia404() {
200 return $this->transformVia404;
201 }
202
203 /**
204 * Get the name of an image from its title object
205 * @param $title Title
206 */
207 function getNameFromTitle( $title ) {
208 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
209 global $wgContLang;
210 $name = $title->getUserCaseDBKey();
211 if ( $this->initialCapital ) {
212 $name = $wgContLang->ucfirst( $name );
213 }
214 } else {
215 $name = $title->getDBkey();
216 }
217 return $name;
218 }
219
220 static function getHashPathForLevel( $name, $levels ) {
221 if ( $levels == 0 ) {
222 return '';
223 } else {
224 $hash = md5( $name );
225 $path = '';
226 for ( $i = 1; $i <= $levels; $i++ ) {
227 $path .= substr( $hash, 0, $i ) . '/';
228 }
229 return $path;
230 }
231 }
232
233 /**
234 * Get a relative path including trailing slash, e.g. f/fa/
235 * If the repo is not hashed, returns an empty string
236 */
237 function getHashPath( $name ) {
238 return self::getHashPathForLevel( $name, $this->hashLevels );
239 }
240
241 /**
242 * Get the name of this repository, as specified by $info['name]' to the constructor
243 */
244 function getName() {
245 return $this->name;
246 }
247
248 /**
249 * Make an url to this repo
250 *
251 * @param $query mixed Query string to append
252 * @param $entry string Entry point; defaults to index
253 * @return string
254 */
255 function makeUrl( $query = '', $entry = 'index' ) {
256 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
257 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
258 }
259
260 /**
261 * Get the URL of an image description page. May return false if it is
262 * unknown or not applicable. In general this should only be called by the
263 * File class, since it may return invalid results for certain kinds of
264 * repositories. Use File::getDescriptionUrl() in user code.
265 *
266 * In particular, it uses the article paths as specified to the repository
267 * constructor, whereas local repositories use the local Title functions.
268 */
269 function getDescriptionUrl( $name ) {
270 $encName = wfUrlencode( $name );
271 if ( !is_null( $this->descBaseUrl ) ) {
272 # "http://example.com/wiki/Image:"
273 return $this->descBaseUrl . $encName;
274 }
275 if ( !is_null( $this->articleUrl ) ) {
276 # "http://example.com/wiki/$1"
277 #
278 # We use "Image:" as the canonical namespace for
279 # compatibility across all MediaWiki versions.
280 return str_replace( '$1',
281 "Image:$encName", $this->articleUrl );
282 }
283 if ( !is_null( $this->scriptDirUrl ) ) {
284 # "http://example.com/w"
285 #
286 # We use "Image:" as the canonical namespace for
287 # compatibility across all MediaWiki versions,
288 # and just sort of hope index.php is right. ;)
289 return $this->makeUrl( "title=Image:$encName" );
290 }
291 return false;
292 }
293
294 /**
295 * Get the URL of the content-only fragment of the description page. For
296 * MediaWiki this means action=render. This should only be called by the
297 * repository's file class, since it may return invalid results. User code
298 * should use File::getDescriptionText().
299 * @param $name String: name of image to fetch
300 * @param $lang String: language to fetch it in, if any.
301 */
302 function getDescriptionRenderUrl( $name, $lang = null ) {
303 $query = 'action=render';
304 if ( !is_null( $lang ) ) {
305 $query .= '&uselang=' . $lang;
306 }
307 if ( isset( $this->scriptDirUrl ) ) {
308 return $this->makeUrl(
309 'title=' .
310 wfUrlencode( 'Image:' . $name ) .
311 "&$query" );
312 } else {
313 $descUrl = $this->getDescriptionUrl( $name );
314 if ( $descUrl ) {
315 return wfAppendQuery( $descUrl, $query );
316 } else {
317 return false;
318 }
319 }
320 }
321
322 /**
323 * Get the URL of the stylesheet to apply to description pages
324 * @return string
325 */
326 function getDescriptionStylesheetUrl() {
327 if ( $this->scriptDirUrl ) {
328 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
329 wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
330 }
331 }
332
333 /**
334 * Store a file to a given destination.
335 *
336 * @param $srcPath String: source path or virtual URL
337 * @param $dstZone String: destination zone
338 * @param $dstRel String: destination relative path
339 * @param $flags Integer: bitwise combination of the following flags:
340 * self::DELETE_SOURCE Delete the source file after upload
341 * self::OVERWRITE Overwrite an existing destination file instead of failing
342 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
343 * same contents as the source
344 * @return FileRepoStatus
345 */
346 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
347 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
348 if ( $status->successCount == 0 ) {
349 $status->ok = false;
350 }
351 return $status;
352 }
353
354 /**
355 * Store a batch of files
356 *
357 * @param $triplets Array: (src,zone,dest) triplets as per store()
358 * @param $flags Integer: flags as per store
359 */
360 abstract function storeBatch( $triplets, $flags = 0 );
361
362 /**
363 * Pick a random name in the temp zone and store a file to it.
364 * Returns a FileRepoStatus object with the URL in the value.
365 *
366 * @param $originalName String: the base name of the file as specified
367 * by the user. The file extension will be maintained.
368 * @param $srcPath String: the current location of the file.
369 */
370 abstract function storeTemp( $originalName, $srcPath );
371
372
373 /**
374 * Append the contents of the source path to the given file.
375 * @param $srcPath String: location of the source file
376 * @param $toAppendPath String: path to append to.
377 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
378 * that the source file should be deleted if possible
379 * @return mixed Status or false
380 */
381 abstract function append( $srcPath, $toAppendPath, $flags = 0 );
382
383 /**
384 * Remove a temporary file or mark it for garbage collection
385 * @param $virtualUrl String: the virtual URL returned by storeTemp
386 * @return Boolean: true on success, false on failure
387 * STUB
388 */
389 function freeTemp( $virtualUrl ) {
390 return true;
391 }
392
393 /**
394 * Copy or move a file either from the local filesystem or from an mwrepo://
395 * virtual URL, into this repository at the specified destination location.
396 *
397 * Returns a FileRepoStatus object. On success, the value contains "new" or
398 * "archived", to indicate whether the file was new with that name.
399 *
400 * @param $srcPath String: the source path or URL
401 * @param $dstRel String: the destination relative path
402 * @param $archiveRel String: rhe relative path where the existing file is to
403 * be archived, if there is one. Relative to the public zone root.
404 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
405 * that the source file should be deleted if possible
406 */
407 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
408 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
409 if ( $status->successCount == 0 ) {
410 $status->ok = false;
411 }
412 if ( isset( $status->value[0] ) ) {
413 $status->value = $status->value[0];
414 } else {
415 $status->value = false;
416 }
417 return $status;
418 }
419
420 /**
421 * Publish a batch of files
422 * @param $triplets Array: (source,dest,archive) triplets as per publish()
423 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
424 * that the source files should be deleted if possible
425 */
426 abstract function publishBatch( $triplets, $flags = 0 );
427
428 function fileExists( $file, $flags = 0 ) {
429 $result = $this->fileExistsBatch( array( $file ), $flags );
430 return $result[0];
431 }
432
433 /**
434 * Checks existence of an array of files.
435 *
436 * @param $files Array: URLs (or paths) of files to check
437 * @param $flags Integer: bitwise combination of the following flags:
438 * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
439 * @return Either array of files and existence flags, or false
440 */
441 abstract function fileExistsBatch( $files, $flags = 0 );
442
443 /**
444 * Move a group of files to the deletion archive.
445 *
446 * If no valid deletion archive is configured, this may either delete the
447 * file or throw an exception, depending on the preference of the repository.
448 *
449 * The overwrite policy is determined by the repository -- currently FSRepo
450 * assumes a naming scheme in the deleted zone based on content hash, as
451 * opposed to the public zone which is assumed to be unique.
452 *
453 * @param $sourceDestPairs Array of source/destination pairs. Each element
454 * is a two-element array containing the source file path relative to the
455 * public root in the first element, and the archive file path relative
456 * to the deleted zone root in the second element.
457 * @return FileRepoStatus
458 */
459 abstract function deleteBatch( $sourceDestPairs );
460
461 /**
462 * Move a file to the deletion archive.
463 * If no valid deletion archive exists, this may either delete the file
464 * or throw an exception, depending on the preference of the repository
465 * @param $srcRel Mixed: relative path for the file to be deleted
466 * @param $archiveRel Mixed: relative path for the archive location.
467 * Relative to a private archive directory.
468 * @return FileRepoStatus object
469 */
470 function delete( $srcRel, $archiveRel ) {
471 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
472 }
473
474 /**
475 * Get properties of a file with a given virtual URL
476 * The virtual URL must refer to this repo
477 * Properties should ultimately be obtained via File::getPropsFromPath()
478 */
479 abstract function getFileProps( $virtualUrl );
480
481 /**
482 * Call a callback function for every file in the repository
483 * May use either the database or the filesystem
484 * STUB
485 */
486 function enumFiles( $callback ) {
487 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
488 }
489
490 /**
491 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
492 */
493 function validateFilename( $filename ) {
494 if ( strval( $filename ) == '' ) {
495 return false;
496 }
497 if ( wfIsWindows() ) {
498 $filename = strtr( $filename, '\\', '/' );
499 }
500 /**
501 * Use the same traversal protection as Title::secureAndSplit()
502 */
503 if ( strpos( $filename, '.' ) !== false &&
504 ( $filename === '.' || $filename === '..' ||
505 strpos( $filename, './' ) === 0 ||
506 strpos( $filename, '../' ) === 0 ||
507 strpos( $filename, '/./' ) !== false ||
508 strpos( $filename, '/../' ) !== false ) )
509 {
510 return false;
511 } else {
512 return true;
513 }
514 }
515
516 /**#@+
517 * Path disclosure protection functions
518 */
519 function paranoidClean( $param ) { return '[hidden]'; }
520 function passThrough( $param ) { return $param; }
521
522 /**
523 * Get a callback function to use for cleaning error message parameters
524 */
525 function getErrorCleanupFunction() {
526 switch ( $this->pathDisclosureProtection ) {
527 case 'none':
528 $callback = array( $this, 'passThrough' );
529 break;
530 default: // 'paranoid'
531 $callback = array( $this, 'paranoidClean' );
532 }
533 return $callback;
534 }
535 /**#@-*/
536
537 /**
538 * Create a new fatal error
539 */
540 function newFatal( $message /*, parameters...*/ ) {
541 $params = func_get_args();
542 array_unshift( $params, $this );
543 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
544 }
545
546 /**
547 * Create a new good result
548 */
549 function newGood( $value = null ) {
550 return FileRepoStatus::newGood( $this, $value );
551 }
552
553 /**
554 * Delete files in the deleted directory if they are not referenced in the filearchive table
555 * STUB
556 */
557 function cleanupDeletedBatch( $storageKeys ) {}
558
559 /**
560 * Checks if there is a redirect named as $title. If there is, return the
561 * title object. If not, return false.
562 * STUB
563 *
564 * @param $title Title of image
565 * @return Bool
566 */
567 function checkRedirect( $title ) {
568 return false;
569 }
570
571 /**
572 * Invalidates image redirect cache related to that image
573 * Doesn't do anything for repositories that don't support image redirects.
574 *
575 * STUB
576 * @param $title Title of image
577 */
578 function invalidateImageRedirect( $title ) {}
579
580 /**
581 * Get an array or iterator of file objects for files that have a given
582 * SHA-1 content hash.
583 *
584 * STUB
585 */
586 function findBySha1( $hash ) {
587 return array();
588 }
589
590 /**
591 * Get the human-readable name of the repo.
592 * @return string
593 */
594 public function getDisplayName() {
595 // We don't name our own repo, return nothing
596 if ( $this->isLocal() ) {
597 return null;
598 }
599 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
600 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
601 }
602
603 /**
604 * Returns true if this the local file repository.
605 *
606 * @return bool
607 */
608 function isLocal() {
609 return $this->getName() == 'local';
610 }
611
612
613 /**
614 * Get a key on the primary cache for this repository.
615 * Returns false if the repository's cache is not accessible at this site.
616 * The parameters are the parts of the key, as for wfMemcKey().
617 *
618 * STUB
619 */
620 function getSharedCacheKey( /*...*/ ) {
621 return false;
622 }
623
624 /**
625 * Get a key for this repo in the local cache domain. These cache keys are
626 * not shared with remote instances of the repo.
627 * The parameters are the parts of the key, as for wfMemcKey().
628 */
629 function getLocalCacheKey( /*...*/ ) {
630 $args = func_get_args();
631 array_unshift( $args, 'filerepo', $this->getName() );
632 return call_user_func_array( 'wfMemcKey', $args );
633 }
634
635 /**
636 * Get an UploadStash associated with this repo.
637 *
638 * @return UploadStash
639 */
640 function getUploadStash() {
641 return new UploadStash( $this );
642 }
643 }