Follow up with the problem noted in r90530.
[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
16 // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
17 const KEY_FORMAT_REGEX = '/^[\w-]+\.\w*$/';
18
19 /**
20 * repository that this uses to store temp files
21 * public because we sometimes need to get a LocalFile within the same repo.
22 *
23 * @var LocalRepo
24 */
25 public $repo;
26
27 // array of initialized objects obtained from session (lazily initialized upon getFile())
28 private $files = array();
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
39 */
40 public function __construct( $repo ) {
41
42 // this might change based on wiki's configuration.
43 $this->repo = $repo;
44
45 if ( ! isset( $_SESSION ) ) {
46 throw new UploadStashNotAvailableException( 'no session variable' );
47 }
48
49 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME] ) ) {
50 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
51 }
52
53 }
54
55 /**
56 * Get a file and its metadata from the stash.
57 * May throw exception if session data cannot be parsed due to schema change, or key not found.
58 *
59 * @param $key Integer: key
60 * @throws UploadStashFileNotFoundException
61 * @throws UploadStashBadVersionException
62 * @return UploadStashFile
63 */
64 public function getFile( $key ) {
65 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
66 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
67 }
68
69 if ( !isset( $this->files[$key] ) ) {
70 if ( !isset( $_SESSION[UploadBase::SESSION_KEYNAME][$key] ) ) {
71 throw new UploadStashFileNotFoundException( "key '$key' not found in stash" );
72 }
73
74 $data = $_SESSION[UploadBase::SESSION_KEYNAME][$key];
75 // guards against PHP class changing while session data doesn't
76 if ($data['version'] !== UploadBase::SESSION_VERSION ) {
77 throw new UploadStashBadVersionException( $data['version'] . " does not match current version " . UploadBase::SESSION_VERSION );
78 }
79
80 // separate the stashData into the path, and then the rest of the data
81 $path = $data['mTempPath'];
82 unset( $data['mTempPath'] );
83
84 $file = new UploadStashFile( $this, $this->repo, $path, $key, $data );
85 if ( $file->getSize() === 0 ) {
86 throw new UploadStashZeroLengthFileException( "File is zero length" );
87 }
88 $this->files[$key] = $file;
89
90 }
91 return $this->files[$key];
92 }
93
94 /**
95 * Stash a file in a temp directory and record that we did this in the session, along with other metadata.
96 * We store data in a flat key-val namespace because that's how UploadBase did it. This also means we have to
97 * ensure that the key-val pairs in $data do not overwrite other required fields.
98 *
99 * @param $path String: path to file you want stashed
100 * @param $data Array: optional, other data you want associated with the file. Do not use 'mTempPath', 'mFileProps', 'mFileSize', or 'version' as keys here
101 * @param $key String: optional, unique key for this file in this session. Used for directory hashing when storing, otherwise not important
102 * @throws UploadStashBadPathException
103 * @throws UploadStashFileException
104 * @return UploadStashFile: file, or null on failure
105 */
106 public function stashFile( $path, $data = array(), $key = null ) {
107 if ( ! file_exists( $path ) ) {
108 wfDebug( "UploadStash: tried to stash file at '$path', but it doesn't exist\n" );
109 throw new UploadStashBadPathException( "path doesn't exist" );
110 }
111 $fileProps = File::getPropsFromPath( $path );
112
113 // we will be initializing from some tmpnam files that don't have extensions.
114 // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
115 $extension = self::getExtensionForPath( $path );
116 if ( ! preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
117 $pathWithGoodExtension = "$path.$extension";
118 if ( ! rename( $path, $pathWithGoodExtension ) ) {
119 throw new UploadStashFileException( "couldn't rename $path to have a better extension at $pathWithGoodExtension" );
120 }
121 $path = $pathWithGoodExtension;
122 }
123
124 // If no key was supplied, use content hash. Also has the nice property of collapsing multiple identical files
125 // uploaded this session, which could happen if uploads had failed.
126 if ( is_null( $key ) ) {
127 $key = $fileProps['sha1'] . "." . $extension;
128 }
129
130 if ( ! preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
131 throw new UploadStashBadPathException( "key '$key' is not in a proper format" );
132 }
133
134 // if not already in a temporary area, put it there
135 $status = $this->repo->storeTemp( basename( $path ), $path );
136
137 if( ! $status->isOK() ) {
138 // It is a convention in MediaWiki to only return one error per API exception, even if multiple errors
139 // are available. We use reset() to pick the "first" thing that was wrong, preferring errors to warnings.
140 // 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
141 // redesigning API errors significantly.
142 // $status->value just contains the virtual URL (if anything) which is probably useless to the caller
143 $error = $status->getErrorsArray();
144 $error = reset( $error );
145 if ( ! count( $error ) ) {
146 $error = $status->getWarningsArray();
147 $error = reset( $error );
148 if ( ! count( $error ) ) {
149 $error = array( 'unknown', 'no error recorded' );
150 }
151 }
152 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
153 }
154 $stashPath = $status->value;
155
156 // required info we always store. Must trump any other application info in $data
157 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
158 // chosen for compatibility with UploadBase's way of doing this.
159 $requiredData = array(
160 'mTempPath' => $stashPath,
161 'mFileSize' => $fileProps['size'],
162 'mFileProps' => $fileProps,
163 'version' => UploadBase::SESSION_VERSION
164 );
165
166 // now, merge required info and extra data into the session. (The extra data changes from application to application.
167 // UploadWizard wants different things than say FirefoggChunkedUpload.)
168 wfDebug( __METHOD__ . " storing under $key\n" );
169 $_SESSION[UploadBase::SESSION_KEYNAME][$key] = array_merge( $data, $requiredData );
170
171 return $this->getFile( $key );
172 }
173
174 /**
175 * Remove all files from the stash.
176 * Does not clean up files in the repo, just the record of them.
177 * @return boolean: success
178 */
179 public function clear() {
180 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
181 return true;
182 }
183
184
185 /**
186 * Remove a particular file from the stash.
187 * Does not clean up file in the repo, just the record of it.
188 * @return boolean: success
189 */
190 public function removeFile( $key ) {
191 unset ( $_SESSION[UploadBase::SESSION_KEYNAME][$key] );
192 return true;
193 }
194
195 /**
196 * List all files in the stash.
197 */
198 public function listFiles() {
199 return array_keys( $_SESSION[UploadBase::SESSION_KEYNAME] );
200 }
201
202 /**
203 * Find or guess extension -- ensuring that our extension matches our mime type.
204 * Since these files are constructed from php tempnames they may not start off
205 * with an extension.
206 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
207 * uploads versus the desired filename. Maybe we can get that passed to us...
208 */
209 public static function getExtensionForPath( $path ) {
210 // Does this have an extension?
211 $n = strrpos( $path, '.' );
212 $extension = null;
213 if ( $n !== false ) {
214 $extension = $n ? substr( $path, $n + 1 ) : '';
215 } else {
216 // If not, assume that it should be related to the mime type of the original file.
217 $magic = MimeMagic::singleton();
218 $mimeType = $magic->guessMimeType( $path );
219 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
220 if ( count( $extensions ) ) {
221 $extension = $extensions[0];
222 }
223 }
224
225 if ( is_null( $extension ) ) {
226 throw new UploadStashFileException( "extension is null" );
227 }
228
229 return File::normalizeExtension( $extension );
230 }
231
232 }
233
234 class UploadStashFile extends UnregisteredLocalFile {
235 private $sessionStash;
236 private $sessionKey;
237 private $sessionData;
238 private $urlName;
239 protected $url;
240
241 /**
242 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
243 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
244 *
245 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
246 * @param $repo FSRepo: repository where we should find the path
247 * @param $path String: path to file
248 * @param $key String: key to store the path and any stashed data under
249 * @param $data String: any other data we want stored with this file
250 * @throws UploadStashBadPathException
251 * @throws UploadStashFileNotFoundException
252 */
253 public function __construct( $stash, $repo, $path, $key, $data ) {
254 $this->sessionStash = $stash;
255 $this->sessionKey = $key;
256 $this->sessionData = $data;
257
258 // resolve mwrepo:// urls
259 if ( $repo->isVirtualUrl( $path ) ) {
260 $path = $repo->resolveVirtualUrl( $path );
261 }
262
263 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
264 $repoTempPath = $repo->getZonePath( 'temp' );
265 if ( ( ! $repo->validateFilename( $path ) ) ||
266 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
267 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
268 throw new UploadStashBadPathException( 'path is not valid' );
269 }
270
271 // check if path exists! and is a plain file.
272 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
273 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
274 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
275 }
276
277 parent::__construct( false, $repo, $path, false );
278
279 $this->name = basename( $this->path );
280 }
281
282 /**
283 * A method needed by the file transforming and scaling routines in File.php
284 * We do not necessarily care about doing the description at this point
285 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
286 * convert require it to be there)
287 *
288 * @return String: dummy value
289 */
290 public function getDescriptionUrl() {
291 return $this->getUrl();
292 }
293
294 /**
295 * Get the path for the thumbnail (actually any transformation of this file)
296 * The actual argument is the result of thumbName although we seem to have
297 * buggy code elsewhere that expects a boolean 'suffix'
298 *
299 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
300 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
301 */
302 public function getThumbPath( $thumbName = false ) {
303 $path = dirname( $this->path );
304 if ( $thumbName !== false ) {
305 $path .= "/$thumbName";
306 }
307 return $path;
308 }
309
310 /**
311 * Return the file/url base name of a thumbnail with the specified parameters.
312 * We override this because we want to use the pretty url name instead of the
313 * ugly file name.
314 *
315 * @param $params Array: handler-specific parameters
316 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
317 */
318 function thumbName( $params ) {
319 return $this->generateThumbName( $this->getUrlName(), $params );
320 }
321
322 /**
323 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
324 * @param {String} $subPage
325 * @return {String} local URL for this subpage in the Special:UploadStash space.
326 */
327 private function getSpecialUrl( $subPage ) {
328 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
329 }
330
331 /**
332 * Get a URL to access the thumbnail
333 * This is required because the model of how files work requires that
334 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
335 * (that's hidden in the session)
336 *
337 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
338 * @return String: URL to access thumbnail, or URL with partial path
339 */
340 public function getThumbUrl( $thumbName = false ) {
341 wfDebug( __METHOD__ . " getting for $thumbName \n" );
342 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
343 }
344
345 /**
346 * The basename for the URL, which we want to not be related to the filename.
347 * Will also be used as the lookup key for a thumbnail file.
348 *
349 * @return String: base url name, like '120px-123456.jpg'
350 */
351 public function getUrlName() {
352 if ( ! $this->urlName ) {
353 $this->urlName = $this->sessionKey;
354 }
355 return $this->urlName;
356 }
357
358 /**
359 * Return the URL of the file, if for some reason we wanted to download it
360 * We tend not to do this for the original file, but we do want thumb icons
361 *
362 * @return String: url
363 */
364 public function getUrl() {
365 if ( !isset( $this->url ) ) {
366 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
367 }
368 return $this->url;
369 }
370
371 /**
372 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
373 * But with this class, the URL is unrelated to the path.
374 *
375 * @return String: url
376 */
377 public function getFullUrl() {
378 return $this->getUrl();
379 }
380
381 /**
382 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
383 *
384 * @return String: session key
385 */
386 public function getSessionKey() {
387 return $this->sessionKey;
388 }
389
390 /**
391 * Remove the associated temporary file
392 * @return Status: success
393 */
394 public function remove() {
395 return $this->repo->freeTemp( $this->path );
396 }
397
398 }
399
400 class UploadStashNotAvailableException extends MWException {};
401 class UploadStashFileNotFoundException extends MWException {};
402 class UploadStashBadPathException extends MWException {};
403 class UploadStashBadVersionException extends MWException {};
404 class UploadStashFileException extends MWException {};
405 class UploadStashZeroLengthFileException extends MWException {};
406