]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/filerepo/FileRepo.php
MediaWiki 1.11.0
[autoinstallsdev/mediawiki.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
95         /**
96          * Get the URL of thumb.php
97          */
98         function getThumbScriptUrl() {
99                 return $this->thumbScriptUrl;
100         }
101
102         /**
103          * Returns true if the repository can transform files via a 404 handler
104          */
105         function canTransformVia404() {
106                 return $this->transformVia404;
107         }
108
109         /**
110          * Get the name of an image from its title object
111          */
112         function getNameFromTitle( $title ) {
113                 global $wgCapitalLinks;
114                 if ( $this->initialCapital != $wgCapitalLinks ) {
115                         global $wgContLang;
116                         $name = $title->getUserCaseDBKey();
117                         if ( $this->initialCapital ) {
118                                 $name = $wgContLang->ucfirst( $name );
119                         }
120                 } else {
121                         $name = $title->getDBkey();
122                 }
123                 return $name;
124         }
125
126         static function getHashPathForLevel( $name, $levels ) {
127                 if ( $levels == 0 ) {
128                         return '';
129                 } else {
130                         $hash = md5( $name );
131                         $path = '';
132                         for ( $i = 1; $i <= $levels; $i++ ) {
133                                 $path .= substr( $hash, 0, $i ) . '/';
134                         }
135                         return $path;
136                 }
137         }
138
139         /**
140          * Get the name of this repository, as specified by $info['name]' to the constructor
141          */
142         function getName() {
143                 return $this->name;
144         }
145
146         /**
147          * Get the file description page base URL, or false if there isn't one.
148          * @private
149          */
150         function getDescBaseUrl() {
151                 if ( is_null( $this->descBaseUrl ) ) {
152                         if ( !is_null( $this->articleUrl ) ) {
153                                 $this->descBaseUrl = str_replace( '$1', 
154                                         wfUrlencode( Namespace::getCanonicalName( NS_IMAGE ) ) . ':', $this->articleUrl );
155                         } elseif ( !is_null( $this->scriptDirUrl ) ) {
156                                 $this->descBaseUrl = $this->scriptDirUrl . '/index.php?title=' . 
157                                         wfUrlencode( Namespace::getCanonicalName( NS_IMAGE ) ) . ':';
158                         } else {
159                                 $this->descBaseUrl = false;
160                         }
161                 }
162                 return $this->descBaseUrl;
163         }
164
165         /**
166          * Get the URL of an image description page. May return false if it is
167          * unknown or not applicable. In general this should only be called by the 
168          * File class, since it may return invalid results for certain kinds of 
169          * repositories. Use File::getDescriptionUrl() in user code.
170          *
171          * In particular, it uses the article paths as specified to the repository
172          * constructor, whereas local repositories use the local Title functions.
173          */
174         function getDescriptionUrl( $name ) {
175                 $base = $this->getDescBaseUrl();
176                 if ( $base ) {
177                         return $base . wfUrlencode( $name );
178                 } else {
179                         return false;
180                 }
181         }
182
183         /**
184          * Get the URL of the content-only fragment of the description page. For 
185          * MediaWiki this means action=render. This should only be called by the 
186          * repository's file class, since it may return invalid results. User code 
187          * should use File::getDescriptionText().
188          */
189         function getDescriptionRenderUrl( $name ) {
190                 if ( isset( $this->scriptDirUrl ) ) {
191                         return $this->scriptDirUrl . '/index.php?title=' . 
192                                 wfUrlencode( Namespace::getCanonicalName( NS_IMAGE ) . ':' . $name ) .
193                                 '&action=render';
194                 } else {
195                         $descBase = $this->getDescBaseUrl();
196                         if ( $descBase ) {
197                                 return wfAppendQuery( $descBase . wfUrlencode( $name ), 'action=render' );
198                         } else {
199                                 return false;
200                         }
201                 }
202         }
203
204         /**
205          * Store a file to a given destination.
206          *
207          * @param string $srcPath Source path or virtual URL
208          * @param string $dstZone Destination zone
209          * @param string $dstRel Destination relative path
210          * @param integer $flags Bitwise combination of the following flags:
211          *     self::DELETE_SOURCE     Delete the source file after upload
212          *     self::OVERWRITE         Overwrite an existing destination file instead of failing
213          *     self::OVERWRITE_SAME    Overwrite the file if the destination exists and has the 
214          *                             same contents as the source
215          * @return FileRepoStatus
216          */
217         function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
218                 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
219                 if ( $status->successCount == 0 ) {
220                         $status->ok = false;
221                 }
222                 return $status;
223         }
224
225         /**
226          * Store a batch of files
227          *
228          * @param array $triplets (src,zone,dest) triplets as per store()
229          * @param integer $flags Flags as per store
230          */
231         abstract function storeBatch( $triplets, $flags = 0 );
232
233         /**
234          * Pick a random name in the temp zone and store a file to it.
235          * Returns a FileRepoStatus object with the URL in the value.
236          *
237          * @param string $originalName The base name of the file as specified 
238          *     by the user. The file extension will be maintained.
239          * @param string $srcPath The current location of the file.
240          */
241         abstract function storeTemp( $originalName, $srcPath );
242
243         /**
244          * Remove a temporary file or mark it for garbage collection
245          * @param string $virtualUrl The virtual URL returned by storeTemp
246          * @return boolean True on success, false on failure
247          * STUB
248          */
249         function freeTemp( $virtualUrl ) {
250                 return true;
251         }
252
253         /**
254          * Copy or move a file either from the local filesystem or from an mwrepo://
255          * virtual URL, into this repository at the specified destination location.
256          *
257          * Returns a FileRepoStatus object. On success, the value contains "new" or
258          * "archived", to indicate whether the file was new with that name. 
259          *
260          * @param string $srcPath The source path or URL
261          * @param string $dstRel The destination relative path
262          * @param string $archiveRel The relative path where the existing file is to
263          *        be archived, if there is one. Relative to the public zone root.
264          * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
265          *        that the source file should be deleted if possible
266          */
267         function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
268                 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
269                 if ( $status->successCount == 0 ) {
270                         $status->ok = false;
271                 }
272                 if ( isset( $status->value[0] ) ) {
273                         $status->value = $status->value[0];
274                 } else {
275                         $status->value = false;
276                 }
277                 return $status;
278         }
279
280         /**
281          * Publish a batch of files
282          * @param array $triplets (source,dest,archive) triplets as per publish()
283          * @param integer $flags Bitfield, may be FileRepo::DELETE_SOURCE to indicate
284          *        that the source files should be deleted if possible
285          */
286         abstract function publishBatch( $triplets, $flags = 0 );
287
288         /**
289          * Move a group of files to the deletion archive.
290          *
291          * If no valid deletion archive is configured, this may either delete the 
292          * file or throw an exception, depending on the preference of the repository.
293          *
294          * The overwrite policy is determined by the repository -- currently FSRepo
295          * assumes a naming scheme in the deleted zone based on content hash, as 
296          * opposed to the public zone which is assumed to be unique.
297          *
298          * @param array $sourceDestPairs Array of source/destination pairs. Each element 
299          *        is a two-element array containing the source file path relative to the
300          *        public root in the first element, and the archive file path relative 
301          *        to the deleted zone root in the second element.
302          * @return FileRepoStatus
303          */
304         abstract function deleteBatch( $sourceDestPairs );
305
306         /**
307          * Move a file to the deletion archive.
308          * If no valid deletion archive exists, this may either delete the file 
309          * or throw an exception, depending on the preference of the repository
310          * @param mixed $srcRel Relative path for the file to be deleted
311          * @param mixed $archiveRel Relative path for the archive location. 
312          *        Relative to a private archive directory.
313          * @return WikiError object (wikitext-formatted), or true for success
314          */
315         function delete( $srcRel, $archiveRel ) {
316                 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
317         }
318
319         /**
320          * Get properties of a file with a given virtual URL
321          * The virtual URL must refer to this repo
322          * Properties should ultimately be obtained via File::getPropsFromPath()
323          */
324         abstract function getFileProps( $virtualUrl );
325
326         /**
327          * Call a callback function for every file in the repository
328          * May use either the database or the filesystem
329          * STUB
330          */
331         function enumFiles( $callback ) {
332                 throw new MWException( 'enumFiles is not supported by ' . get_class( $this ) );
333         }
334
335         /**
336          * Determine if a relative path is valid, i.e. not blank or involving directory traveral
337          */
338         function validateFilename( $filename ) {
339                 if ( strval( $filename ) == '' ) {
340                         return false;
341                 }
342                 if ( wfIsWindows() ) {
343                         $filename = strtr( $filename, '\\', '/' );
344                 }
345                 /**
346                  * Use the same traversal protection as Title::secureAndSplit()
347                  */
348                 if ( strpos( $filename, '.' ) !== false &&
349                      ( $filename === '.' || $filename === '..' ||
350                        strpos( $filename, './' ) === 0  ||
351                        strpos( $filename, '../' ) === 0 ||
352                        strpos( $filename, '/./' ) !== false ||
353                        strpos( $filename, '/../' ) !== false ) )
354                 {
355                         return false;
356                 } else {
357                         return true;
358                 }
359         }
360
361         /**#@+
362          * Path disclosure protection functions
363          */
364         function paranoidClean( $param ) { return '[hidden]'; }
365         function passThrough( $param ) { return $param; }
366
367         /**
368          * Get a callback function to use for cleaning error message parameters
369          */
370         function getErrorCleanupFunction() {
371                 switch ( $this->pathDisclosureProtection ) {
372                         case 'none':
373                                 $callback = array( $this, 'passThrough' );
374                                 break;
375                         default: // 'paranoid'
376                                 $callback = array( $this, 'paranoidClean' );
377                 }
378                 return $callback;
379         }
380         /**#@-*/
381
382         /**
383          * Create a new fatal error
384          */
385         function newFatal( $message /*, parameters...*/ ) {
386                 $params = func_get_args();
387                 array_unshift( $params, $this );
388                 return call_user_func_array( array( 'FileRepoStatus', 'newFatal' ), $params );
389         }
390
391         /**
392          * Create a new good result
393          */
394         function newGood( $value = null ) {
395                 return FileRepoStatus::newGood( $this, $value );
396         }
397
398         /**
399          * Delete files in the deleted directory if they are not referenced in the filearchive table
400          * STUB
401          */
402         function cleanupDeletedBatch( $storageKeys ) {}
403 }
404