updated comments, error messages. Removing exposure of actual paths in error message...
[lhc/web/wiklou.git] / includes / upload / UploadStash.php
1 <?php
2 /**
3 * UploadStash is intended to accomplish a few things:
4 * - enable applications to temporarily stash files without publishing them to the wiki.
5 * - Several parts of MediaWiki do this in similar ways: UploadBase, UploadWizard, and FirefoggChunkedExtension
6 * And there are several that reimplement stashing from scratch, in idiosyncratic ways. The idea is to unify them all here.
7 * Mostly all of them are the same except for storing some custom fields, which we subsume into the data array.
8 * - enable applications to find said files later, as long as the session or temp files haven't been purged.
9 * - enable the uploading user (and *ONLY* the uploading user) to access said files, and thumbnails of said files, via a URL.
10 * We accomplish this by making the session serve as a URL->file mapping, on the assumption that nobody else can access
11 * the session, even the uploading user. See SpecialUploadStash, which implements a web interface to some files stored this way.
12 *
13 */
14 class UploadStash {
15 // Format of the key for files -- has to be suitable as a filename itself in some cases.
16 // This should encompass a sha1 content hash in hex (new style), or an integer (old style),
17 // and also thumbnails with prepended strings like "120px-".
18 // The file extension should not be part of the key.
19 const KEY_FORMAT_REGEX = '/^[\w-]+$/';
20
21 // repository that this uses to store temp files
22 protected $repo;
23
24 // array of initialized objects obtained from session (lazily initialized upon getFile())
25 private $files = array();
26
27 // the base URL for files in the stash
28 private $baseUrl;
29
30 // TODO: Once UploadBase starts using this, switch to use these constants rather than UploadBase::SESSION*
31 // const SESSION_VERSION = 2;
32 // const SESSION_KEYNAME = 'wsUploadData';
33
34 /**
35 * Represents the session which contains temporarily stored files.
36 * Designed to be compatible with the session stashing code in UploadBase (should replace it eventually)
37 *
38 * @param $repo FileRepo: optional -- repo in which to store files. Will choose LocalRepo if not supplied.
39 */
40 public function __construct( $repo = null ) {
41
42 if ( is_null( $repo ) ) {
43 $repo = RepoGroup::singleton()->getLocalRepo();
44 }
45
46 $this->repo = $repo;
47
48 if ( ! isset( $_SESSION ) ) {
49 throw new UploadStashNotAvailableException( 'no session variable' );
50 }
51
52 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME] ) ) {
53 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
54 }
55
56 $this->baseUrl = SpecialPage::getTitleFor( 'UploadStash' )->getLocalURL();
57 }
58
59 /**
60 * Get the base of URLs by which one can access the files
61 *
62 * @return String: url
63 */
64 public function getBaseUrl() {
65 return $this->baseUrl;
66 }
67
68 /**
69 * Get a file and its metadata from the stash.
70 * May throw exception if session data cannot be parsed due to schema change, or key not found.
71 *
72 * @param $key Integer: key
73 * @throws UploadStashFileNotFoundException
74 * @throws UploadStashBadVersionException
75 * @return UploadStashFile
76 */
77 public function getFile( $key ) {
78 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
79 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
80 }
81
82 if ( !isset( $this->files[$key] ) ) {
83 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME][$key] ) ) {
84 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
85 }
86
87 $data = $_SESSION[UploadBase::SESSION_KEYNAME][$key];
88 // guards against PHP class changing while session data doesn't
89 if ($data['version'] !== UploadBase::SESSION_VERSION ) {
90 throw new UploadStashBadVersionException( $data['version'] . " does not match current version " . UploadBase::SESSION_VERSION );
91 }
92
93 // separate the stashData into the path, and then the rest of the data
94 $path = $data['mTempPath'];
95 unset( $data['mTempPath'] );
96
97 $file = new UploadStashFile( $this, $this->repo, $path, $key, $data );
98
99 $this->files[$key] = $file;
100
101 }
102 return $this->files[$key];
103 }
104
105 /**
106 * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
107 * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
108 * ensure that the key-val pairs in $data do not overwrite other required fields.
109 *
110 * @param $path String: path to file you want stashed
111 * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
112 * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
113 * @throws UploadStashBadPathException
114 * @throws UploadStashFileException
115 * @return UploadStashFile: file, or null on failure
116 */
117 public function stashFile( $path, $data = array(), $key = null ) {
118 if ( ! file_exists( $path ) ) {
119 throw new UploadStashBadPathException( "path doesn't exist" );
120 }
121 $fileProps = File::getPropsFromPath( $path );
122
123 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
124 // uploaded this session, which could happen if uploads had failed.
125 if ( is_null( $key ) ) {
126 $key = $fileProps['sha1'];
127 }
128
129 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
130 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
131 }
132
133 // if not already in a temporary area, put it there
134 $status = $this->repo->storeTemp( basename( $path ), $path );
135 if( ! $status->isOK() ) {
136 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
137 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
138 // This is a bit lame, as we may have more info in the $status and we're throwing it away, but to fix it means
139 // redesigning API errors significantly.
140 // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
141 $error = reset( $status->getErrorsArray() );
142 if ( ! count( $error ) ) {
143 $error = reset( $status->getWarningsArray() );
144 if ( ! count( $error ) ) {
145 $error = array( 'unknown', 'no error recorded' );
146 }
147 }
148 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
149 }
150 $stashPath = $status->value;
151
152 // required info we always store. Must trump any other application info in $data
153 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
154 // chosen for compatibility with UploadBase's way of doing this.
155 $requiredData = array(
156 'mTempPath' => $stashPath,
157 'mFileSize' => $fileProps['size'],
158 'mFileProps' => $fileProps,
159 'version' => UploadBase::SESSION_VERSION
160 );
161
162 // now, merge required info and extra data into the session. (The extra data changes from application to application.
163 // UploadWizard wants different things than say FirefoggChunkedUpload.)
164 $_SESSION[UploadBase::SESSION_KEYNAME][$key] = array_merge( $data, $requiredData );
165
166 return $this->getFile( $key );
167 }
168
169 }
170
171 class UploadStashFile extends UnregisteredLocalFile {
172 private $sessionStash;
173 private $sessionKey;
174 private $sessionData;
175 private $urlName;
176
177 /**
178 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
179 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
180 *
181 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
182 * @param $repo FileRepo: repository where we should find the path
183 * @param $path String: path to file
184 * @param $key String: key to store the path and any stashed data under
185 * @param $data String: any other data we want stored with this file
186 * @throws UploadStashBadPathException
187 * @throws UploadStashFileNotFoundException
188 */
189 public function __construct( $stash, $repo, $path, $key, $data ) {
190 $this->sessionStash = $stash;
191 $this->sessionKey = $key;
192 $this->sessionData = $data;
193
194 // resolve mwrepo:// urls
195 if ( $repo->isVirtualUrl( $path ) ) {
196 $path = $repo->resolveVirtualUrl( $path );
197 }
198
199 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
200 $repoTempPath = $repo->getZonePath( 'temp' );
201 if ( ( ! $repo->validateFilename( $path ) ) ||
202 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
203 throw new UploadStashBadPathException( 'path is not valid' );
204 }
205
206 // check if path exists! and is a plain file.
207 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
208 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
209 }
210
211 parent::__construct( false, $repo, $path, false );
212
213 // we will be initializing from some tmpnam files that don't have extensions.
214 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
215 $this->name = basename( $this->path );
216 $this->setExtension();
217
218 }
219
220 /**
221 * A method needed by the file transforming and scaling routines in File.php
222 * We do not necessarily care about doing the description at this point
223 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
224 * convert require it to be there)
225 *
226 * @return String: dummy value
227 */
228 public function getDescriptionUrl() {
229 return $this->getUrl();
230 }
231
232 /**
233 * Find or guess extension -- ensuring that our extension matches our mime type.
234 * Since these files are constructed from php tempnames they may not start off
235 * with an extension.
236 * This does not override getExtension() because things like getMimeType() already call getExtension(),
237 * and that results in infinite recursion. So, we preemptively *set* the extension so getExtension() can find it.
238 * For obvious reasons this should be called as early as possible, as part of initialization
239 */
240 public function setExtension() {
241 // Does this have an extension?
242 $n = strrpos( $this->path, '.' );
243 $extension = null;
244 if ( $n !== false ) {
245 $extension = $n ? substr( $this->path, $n + 1 ) : '';
246 } else {
247 // If not, assume that it should be related to the mime type of the original file.
248 //
249 // This entire thing is backwards -- we *should* just create an extension based on
250 // the mime type of the transformed file, *after* transformation. But File.php demands
251 // to know the name of the transformed file before creating it.
252 $mimeType = $this->getMimeType();
253 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
254 if ( count( $extensions ) ) {
255 $extension = $extensions[0];
256 }
257 }
258
259 if ( is_null( $extension ) ) {
260 throw new UploadStashFileException( "extension is null" );
261 }
262
263 $this->extension = parent::normalizeExtension( $extension );
264 }
265
266 /**
267 * Get the path for the thumbnail (actually any transformation of this file)
268 * The actual argument is the result of thumbName although we seem to have
269 * buggy code elsewhere that expects a boolean 'suffix'
270 *
271 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
272 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
273 */
274 public function getThumbPath( $thumbName = false ) {
275 $path = dirname( $this->path );
276 if ( $thumbName !== false ) {
277 $path .= "/$thumbName";
278 }
279 return $path;
280 }
281
282 /**
283 * Return the file/url base name of a thumbnail with the specified parameters
284 *
285 * @param $params Array: handler-specific parameters
286 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
287 */
288 function thumbName( $params ) {
289 if ( !$this->getHandler() ) {
290 return null;
291 }
292 $extension = $this->getExtension();
293 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
294 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $this->getUrlName();
295 if ( $thumbExt != $extension ) {
296 $thumbName .= ".$thumbExt";
297 }
298 return $thumbName;
299 }
300
301 /**
302 * Get a URL to access the thumbnail
303 * This is required because the model of how files work requires that
304 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
305 * (that's hidden in the session)
306 *
307 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
308 * @return String: URL to access thumbnail, or URL with partial path
309 */
310 public function getThumbUrl( $thumbName = false ) {
311 $path = $this->sessionStash->getBaseUrl();
312 if ( $thumbName !== false ) {
313 $path .= '/' . rawurlencode( $thumbName );
314 }
315 return $path;
316 }
317
318 /**
319 * The basename for the URL, which we want to not be related to the filename.
320 * Will also be used as the lookup key for a thumbnail file.
321 *
322 * @return String: base url name, like '120px-123456.jpg'
323 */
324 public function getUrlName() {
325 if ( ! $this->urlName ) {
326 $this->urlName = $this->sessionKey . '.' . $this->getExtension();
327 }
328 return $this->urlName;
329 }
330
331 /**
332 * Return the URL of the file, if for some reason we wanted to download it
333 * We tend not to do this for the original file, but we do want thumb icons
334 *
335 * @return String: url
336 */
337 public function getUrl() {
338 if ( !isset( $this->url ) ) {
339 $this->url = $this->sessionStash->getBaseUrl() . '/' . $this->getUrlName();
340 }
341 return $this->url;
342 }
343
344 /**
345 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
346 * But with this class, the URL is unrelated to the path.
347 *
348 * @return String: url
349 */
350 public function getFullUrl() {
351 return $this->getUrl();
352 }
353
354
355 /**
356 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
357 *
358 * @return String: session key
359 */
360 public function getSessionKey() {
361 return $this->sessionKey;
362 }
363
364 /**
365 * Typically, transform() returns a ThumbnailImage, which you can think of as being the exact
366 * equivalent of an HTML thumbnail on Wikipedia. So its URL is the full-size file, not the thumbnail's URL.
367 *
368 * Here we override transform() to stash the thumbnail file, and then
369 * provide a way to get at the stashed thumbnail file to extract properties such as its URL
370 *
371 * @param $params Array: parameters suitable for File::transform()
372 * @param $flags Integer: bitmask, flags suitable for File::transform()
373 * @return ThumbnailImage: with additional File thumbnailFile property
374 */
375 public function transform( $params, $flags = 0 ) {
376
377 // force it to get a thumbnail right away
378 $flags |= self::RENDER_NOW;
379
380 // returns a ThumbnailImage object containing the url and path. Note. NOT A FILE OBJECT.
381 $thumb = parent::transform( $params, $flags );
382 $key = $this->thumbName($params);
383
384 // remove extension, so it's stored in the session under '120px-123456'
385 // this makes it uniform with the other session key for the original, '123456'
386 $n = strrpos( $key, '.' );
387 if ( $n !== false ) {
388 $key = substr( $key, 0, $n );
389 }
390
391 // stash the thumbnail File, and provide our caller with a way to get at its properties
392 $stashedThumbFile = $this->sessionStash->stashFile( $thumb->getPath(), array(), $key );
393 $thumb->thumbnailFile = $stashedThumbFile;
394
395 return $thumb;
396
397 }
398
399 /**
400 * Remove the associated temporary file
401 * @return Status: success
402 */
403 public function remove() {
404 return $this->repo->freeTemp( $this->path );
405 }
406
407 }
408
409 class UploadStashNotAvailableException extends MWException {};
410 class UploadStashFileNotFoundException extends MWException {};
411 class UploadStashBadPathException extends MWException {};
412 class UploadStashBadVersionException extends MWException {};
413 class UploadStashFileException extends MWException {};
414