bf06aefee83d232bf1ccce6131f902aaf3d1af89
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2
3 /**
4 * Base class for file repositories
5 * Do not instantiate, use a derived class.
6 */
7 abstract class FileRepo {
8 const DELETE_SOURCE = 1;
9 const FIND_PRIVATE = 1;
10 const FIND_IGNORE_REDIRECT = 2;
11 const OVERWRITE = 2;
12 const OVERWRITE_SAME = 4;
13
14 var $thumbScriptUrl, $transformVia404;
15 var $descBaseUrl, $scriptDirUrl, $articleUrl, $fetchDescription, $initialCapital;
16 var $pathDisclosureProtection = 'paranoid';
17
18 /**
19 * Factory functions for creating new files
20 * Override these in the base class
21 */
22 var $fileFactory = false, $oldFileFactory = false;
23 var $fileFactoryKey = false, $oldFileFactoryKey = false;
24
25 function __construct( $info ) {
26 // Required settings
27 $this->name = $info['name'];
28
29 // Optional settings
30 $this->initialCapital = true; // by default
31 foreach ( array( 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
32 'thumbScriptUrl', 'initialCapital', 'pathDisclosureProtection' ) as $var )
33 {
34 if ( isset( $info[$var] ) ) {
35 $this->$var = $info[$var];
36 }
37 }
38 $this->transformVia404 = !empty( $info['transformVia404'] );
39 }
40
41 /**
42 * Determine if a string is an mwrepo:// URL
43 */
44 static function isVirtualUrl( $url ) {
45 return substr( $url, 0, 9 ) == 'mwrepo://';
46 }
47
48 /**
49 * Create a new File object from the local repository
50 * @param mixed $title Title object or string
51 * @param mixed $time Time at which the image was uploaded.
52 * If this is specified, the returned object will be an
53 * instance of the repository's old file class instead of
54 * a current file. Repositories not supporting version
55 * control should return false if this parameter is set.
56 */
57 function newFile( $title, $time = false ) {
58 if ( !($title instanceof Title) ) {
59 $title = Title::makeTitleSafe( NS_IMAGE, $title );
60 if ( !is_object( $title ) ) {
61 return null;
62 }
63 }
64 if ( $time ) {
65 if ( $this->oldFileFactory ) {
66 return call_user_func( $this->oldFileFactory, $title, $this, $time );
67 } else {
68 return false;
69 }
70 } else {
71 return call_user_func( $this->fileFactory, $title, $this );
72 }
73 }
74
75 /**
76 * Find an instance of the named file created at the specified time
77 * Returns false if the file does not exist. Repositories not supporting
78 * version control should return false if the time is specified.
79 *
80 * @param mixed $title Title object or string
81 * @param mixed $time 14-character timestamp, or false for the current version
82 */
83 function findFile( $title, $time = false, $flags = 0 ) {
84 if ( !($title instanceof Title) ) {
85 $title = Title::makeTitleSafe( NS_IMAGE, $title );
86 if ( !is_object( $title ) ) {
87 return false;
88 }
89 }
90 # First try the current version of the file to see if it precedes the timestamp
91 $img = $this->newFile( $title );
92 if ( !$img ) {
93 return false;
94 }
95 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
96 return $img;
97 }
98 # Now try an old version of the file
99 if ( $time !== false ) {
100 $img = $this->newFile( $title, $time );
101 if ( $img->exists() ) {
102 if ( !$img->isDeleted(File::DELETED_FILE) ) {
103 return $img;
104 } else if ( ($flags & FileRepo::FIND_PRIVATE) && $img->userCan(File::DELETED_FILE) ) {
105 return $img;
106 }
107 }
108 }
109
110 # Now try redirects
111 if ( $flags & FileRepo::FIND_IGNORE_REDIRECT ) {
112 return false;
113 }
114 $redir = $this->checkRedirect( $title );
115 if( $redir && $redir->getNamespace() == NS_IMAGE) {
116 $img = $this->newFile( $redir );
117 if( !$img ) {
118 return false;
119 }
120 if( $img->exists() ) {
121 $img->redirectedFrom( $title->getDBkey() );
122 return $img;
123 }
124 }
125 return false;
126 }
127
128 /*
129 * Find many files at once
130 */
131 function findFiles( &$titles, $time = false, $flags ) {
132 $result = array();
133 foreach ( $titles as $index => $title ) {
134 $file = $this->findFile( $title );
135 if ( $file ) {
136 $result[$file->getTitle()->getDBkey()] = $file;
137 unset( $titles[$index] );
138 }
139 }
140 return $result;
141 }
142
143 /**
144 * Create a new File object from the local repository
145 * @param mixed $sha1 SHA-1 key
146 * @param mixed $time Time at which the image was uploaded.
147 * If this is specified, the returned object will be an
148 * instance of the repository's old file class instead of
149 * a current file. Repositories not supporting version
150 * control should return false if this parameter is set.
151 */
152 function newFileFromKey( $sha1, $time = false ) {
153 if ( $time ) {
154 if ( $this->oldFileFactoryKey ) {
155 return call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
156 } else {
157 return false;
158 }
159 } else {
160 return call_user_func( $this->fileFactoryKey, $sha1, $this );
161 }
162 }
163
164 /**
165 * Find an instance of the file with this key, created at the specified time
166 * Returns false if the file does not exist. Repositories not supporting
167 * version control should return false if the time is specified.
168 *
169 * @param string $sha1 string
170 * @param mixed $time 14-character timestamp, or false for the current version
171 */
172 function findFileFromKey( $sha1, $time = false, $flags = 0 ) {
173 # First try the current version of the file to see if it precedes the timestamp
174 $img = $this->newFileFromKey( $sha1 );
175 if ( !$img ) {
176 return false;
177 }
178 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
179 return $img;
180 }
181 # Now try an old version of the file
182 if ( $time !== false ) {
183 $img = $this->newFileFromKey( $sha1, $time );
184 if ( $img->exists() ) {
185 if ( !$img->isDeleted(File::DELETED_FILE) ) {
186 return $img;
187 } else if ( ($flags & FileRepo::FIND_PRIVATE) && $img->userCan(File::DELETED_FILE) ) {
188 return $img;
189 }
190 }
191 }
192 return false;
193 }
194
195 /**
196 * Get the URL of thumb.php
197 */
198 function getThumbScriptUrl() {
199 return $this->thumbScriptUrl;
200 }
201
202 /**
203 * Returns true if the repository can transform files via a 404 handler
204 */
205 function canTransformVia404() {
206 return $this->transformVia404;
207 }
208
209 /**
210 * Get the name of an image from its title object
211 */
212 function getNameFromTitle( $title ) {
213 global $wgCapitalLinks;
214 if ( $this->initialCapital != $wgCapitalLinks ) {
215 global $wgContLang;
216 $name = $title->getUserCaseDBKey();
217 if ( $this->initialCapital ) {
218 $name = $wgContLang->ucfirst( $name );
219 }
220 } else {
221 $name = $title->getDBkey();
222 }
223 return $name;
224 }
225
226 static function getHashPathForLevel( $name, $levels ) {
227 if ( $levels == 0 ) {
228 return '';
229 } else {
230 $hash = md5( $name );
231 $path = '';
232 for ( $i = 1; $i <= $levels; $i++ ) {
233 $path .= substr( $hash, 0, $i ) . '/';
234 }
235 return $path;
236 }
237 }
238
239 /**
240 * Get the name of this repository, as specified by $info['name]' to the constructor
241 */
242 function getName() {
243 return $this->name;
244 }
245
246 /**
247 * Get the file description page base URL, or false if there isn't one.
248 * @private
249 */
250 function getDescBaseUrl() {
251 if ( is_null( $this->descBaseUrl ) ) {
252 if ( !is_null( $this->articleUrl ) ) {
253 $this->descBaseUrl = str_replace( '$1',
254 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) ) . ':', $this->articleUrl );
255 } elseif ( !is_null( $this->scriptDirUrl ) ) {
256 $this->descBaseUrl = $this->scriptDirUrl . '/index.php?title=' .
257 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) ) . ':';
258 } else {
259 $this->descBaseUrl = false;
260 }
261 }
262 return $this->descBaseUrl;
263 }
264
265 /**
266 * Get the URL of an image description page. May return false if it is
267 * unknown or not applicable. In general this should only be called by the
268 * File class, since it may return invalid results for certain kinds of
269 * repositories. Use File::getDescriptionUrl() in user code.
270 *
271 * In particular, it uses the article paths as specified to the repository
272 * constructor, whereas local repositories use the local Title functions.
273 */
274 function getDescriptionUrl( $name ) {
275 $base = $this->getDescBaseUrl();
276 if ( $base ) {
277 return $base . wfUrlencode( $name );
278 } else {
279 return false;
280 }
281 }
282
283 /**
284 * Get the URL of the content-only fragment of the description page. For
285 * MediaWiki this means action=render. This should only be called by the
286 * repository's file class, since it may return invalid results. User code
287 * should use File::getDescriptionText().
288 */
289 function getDescriptionRenderUrl( $name ) {
290 if ( isset( $this->scriptDirUrl ) ) {
291 return $this->scriptDirUrl . '/index.php?title=' .
292 wfUrlencode( MWNamespace::getCanonicalName( NS_IMAGE ) . ':' . $name ) .
293 '&action=render';
294 } else {
295 $descBase = $this->getDescBaseUrl();
296 if ( $descBase ) {
297 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
298 } else {
299 return false;
300 }
301 }
302 }
303
304 /**
305 * Store a file to a given destination.
306 *
307 * @param string $srcPath Source path or virtual URL
308 * @param string $dstZone Destination zone
309 * @param string $dstRel Destination relative path
310 * @param integer $flags Bitwise combination of the following flags:
311 * self::DELETE_SOURCE Delete the source file after upload
312 * self::OVERWRITE Overwrite an existing destination file instead of failing
313 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
314 * same contents as the source
315 * @return FileRepoStatus
316 */
317 function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
318 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
319 if ( $status->successCount == 0 ) {
320 $status->ok = false;
321 }
322 return $status;
323 }
324
325 /**
326 * Store a batch of files
327 *
328 * @param array $triplets (src,zone,dest) triplets as per store()
329 * @param integer $flags Flags as per store
330 */
331 abstract function storeBatch( $triplets, $flags = 0 );
332
333 /**
334 * Pick a random name in the temp zone and store a file to it.
335 * Returns a FileRepoStatus object with the URL in the value.
336 *
337 * @param string $originalName The base name of the file as specified
338 * by the user. The file extension will be maintained.
339 * @param string $srcPath The current location of the file.
340 */
341 abstract function storeTemp( $originalName, $srcPath );
342
343 /**
344 * Remove a temporary file or mark it for garbage collection
345 * @param string $virtualUrl The virtual URL returned by storeTemp
346 * @return boolean True on success, false on failure
347 * STUB
348 */
349 function freeTemp( $virtualUrl ) {
350 return true;
351 }
352
353 /**
354 * Copy or move a file either from the local filesystem or from an mwrepo://
355 * virtual URL, into this repository at the specified destination location.
356 *
357 * Returns a FileRepoStatus object. On success, the value contains "new" or
358 * "archived", to indicate whether the file was new with that name.
359 *
360 * @param string $srcPath The source path or URL
361 * @param string $dstRel The destination relative path
362 * @param string $archiveRel The relative path where the existing file is to
363 * be archived, if there is one. Relative to the public zone root.
364 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
365 * that the source file should be deleted if possible
366 */
367 function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
368 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
369 if ( $status->successCount == 0 ) {
370 $status->ok = false;
371 }
372 if ( isset( $status->value[0] ) ) {
373 $status->value = $status->value[0];
374 } else {
375 $status->value = false;
376 }
377 return $status;
378 }
379
380 /**
381 * Publish a batch of files
382 * @param array $triplets (source,dest,archive) triplets as per publish()
383 * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
384 * that the source files should be deleted if possible
385 */
386 abstract function publishBatch( $triplets, $flags = 0 );
387
388 /**
389 * Move a group of files to the deletion archive.
390 *
391 * If no valid deletion archive is configured, this may either delete the
392 * file or throw an exception, depending on the preference of the repository.
393 *
394 * The overwrite policy is determined by the repository -- currently FSRepo
395 * assumes a naming scheme in the deleted zone based on content hash, as
396 * opposed to the public zone which is assumed to be unique.
397 *
398 * @param array $sourceDestPairs Array of source/destination pairs. Each element
399 * is a two-element array containing the source file path relative to the
400 * public root in the first element, and the archive file path relative
401 * to the deleted zone root in the second element.
402 * @return FileRepoStatus
403 */
404 abstract function deleteBatch( $sourceDestPairs );
405
406 /**
407 * Move a file to the deletion archive.
408 * If no valid deletion archive exists, this may either delete the file
409 * or throw an exception, depending on the preference of the repository
410 * @param mixed $srcRel Relative path for the file to be deleted
411 * @param mixed $archiveRel Relative path for the archive location.
412 * Relative to a private archive directory.
413 * @return WikiError object (wikitext-formatted), or true for success
414 */
415 function delete( $srcRel, $archiveRel ) {
416 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
417 }
418
419 /**
420 * Get properties of a file with a given virtual URL
421 * The virtual URL must refer to this repo
422 * Properties should ultimately be obtained via File::getPropsFromPath()
423 */
424 abstract function getFileProps( $virtualUrl );
425
426 /**
427 * Call a callback function for every file in the repository
428 * May use either the database or the filesystem
429 * STUB
430 */
431 function enumFiles( $callback ) {
432 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
433 }
434
435 /**
436 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
437 */
438 function validateFilename( $filename ) {
439 if ( strval( $filename ) == '' ) {
440 return false;
441 }
442 if ( wfIsWindows() ) {
443 $filename = strtr( $filename, '\\', '/' );
444 }
445 /**
446 * Use the same traversal protection as Title::secureAndSplit()
447 */
448 if ( strpos( $filename, '.' ) !== false &&
449 ( $filename === '.' || $filename === '..' ||
450 strpos( $filename, './' ) === 0 ||
451 strpos( $filename, '../' ) === 0 ||
452 strpos( $filename, '/./' ) !== false ||
453 strpos( $filename, '/../' ) !== false ) )
454 {
455 return false;
456 } else {
457 return true;
458 }
459 }
460
461 /**#@+
462 * Path disclosure protection functions
463 */
464 function paranoidClean( $param ) { return '[hidden]'; }
465 function passThrough( $param ) { return $param; }
466
467 /**
468 * Get a callback function to use for cleaning error message parameters
469 */
470 function getErrorCleanupFunction() {
471 switch ( $this->pathDisclosureProtection ) {
472 case 'none':
473 $callback = array( $this, 'passThrough' );
474 break;
475 default: // 'paranoid'
476 $callback = array( $this, 'paranoidClean' );
477 }
478 return $callback;
479 }
480 /**#@-*/
481
482 /**
483 * Create a new fatal error
484 */
485 function newFatal( $message /*, parameters...*/ ) {
486 $params = func_get_args();
487 array_unshift( $params, $this );
488 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
489 }
490
491 /**
492 * Create a new good result
493 */
494 function newGood( $value = null ) {
495 return FileRepoStatus::newGood( $this, $value );
496 }
497
498 /**
499 * Delete files in the deleted directory if they are not referenced in the filearchive table
500 * STUB
501 */
502 function cleanupDeletedBatch( $storageKeys ) {}
503
504 /**
505 * Checks if there is a redirect named as $title
506 * STUB
507 *
508 * @param Title $title Title of image
509 */
510 function checkRedirect( $title ) {
511 return false;
512 }
513
514 /**
515 * Invalidates image redirect cache related to that image
516 * STUB
517 *
518 * @param Title $title Title of image
519 */
520 function invalidateImageRedirect( $title ) {
521 }
522
523 function findBySha1( $hash ) {
524 return array();
525 }
526 }