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