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