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