(bug 29408) Key 'something.' is not in a proper format
[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 = reset( $status->getErrorsArray() );
144 if ( ! count( $error ) ) {
145 $error = reset( $status->getWarningsArray() );
146 if ( ! count( $error ) ) {
147 $error = array( 'unknown', 'no error recorded' );
148 }
149 }
150 throw new UploadStashFileException( "error storing file in '$path': " . implode( '; ', $error ) );
151 }
152 $stashPath = $status->value;
153
154 // required info we always store. Must trump any other application info in $data
155 // 'mTempPath', 'mFileSize', and 'mFileProps' are arbitrary names
156 // chosen for compatibility with UploadBase's way of doing this.
157 $requiredData = array(
158 'mTempPath' => $stashPath,
159 'mFileSize' => $fileProps['size'],
160 'mFileProps' => $fileProps,
161 'version' => UploadBase::SESSION_VERSION
162 );
163
164 // now, merge required info and extra data into the session. (The extra data changes from application to application.
165 // UploadWizard wants different things than say FirefoggChunkedUpload.)
166 wfDebug( __METHOD__ . " storing under $key\n" );
167 $_SESSION[UploadBase::SESSION_KEYNAME][$key] = array_merge( $data, $requiredData );
168
169 return $this->getFile( $key );
170 }
171
172 /**
173 * Remove all files from the stash.
174 * Does not clean up files in the repo, just the record of them.
175 * @return boolean: success
176 */
177 public function clear() {
178 $_SESSION[UploadBase::SESSION_KEYNAME] = array();
179 return true;
180 }
181
182
183 /**
184 * Remove a particular file from the stash.
185 * Does not clean up file in the repo, just the record of it.
186 * @return boolean: success
187 */
188 public function removeFile( $key ) {
189 unset ( $_SESSION[UploadBase::SESSION_KEYNAME][$key] );
190 return true;
191 }
192
193 /**
194 * List all files in the stash.
195 */
196 public function listFiles() {
197 return array_keys( $_SESSION[UploadBase::SESSION_KEYNAME] );
198 }
199
200 /**
201 * Find or guess extension -- ensuring that our extension matches our mime type.
202 * Since these files are constructed from php tempnames they may not start off
203 * with an extension.
204 * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
205 * uploads versus the desired filename. Maybe we can get that passed to us...
206 */
207 public static function getExtensionForPath( $path ) {
208 // Does this have an extension?
209 $n = strrpos( $path, '.' );
210 $extension = null;
211 if ( $n !== false ) {
212 $extension = $n ? substr( $path, $n + 1 ) : '';
213 } else {
214 // If not, assume that it should be related to the mime type of the original file.
215 $magic = MimeMagic::singleton();
216 $mimeType = $magic->guessMimeType( $path );
217 $extensions = explode( ' ', MimeMagic::singleton()->getExtensionsForType( $mimeType ) );
218 if ( count( $extensions ) ) {
219 $extension = $extensions[0];
220 }
221 }
222
223 if ( is_null( $extension ) ) {
224 throw new UploadStashFileException( "extension is null" );
225 }
226
227 return File::normalizeExtension( $extension );
228 }
229
230 }
231
232 class UploadStashFile extends UnregisteredLocalFile {
233 private $sessionStash;
234 private $sessionKey;
235 private $sessionData;
236 private $urlName;
237 protected $url;
238
239 /**
240 * A LocalFile wrapper around a file that has been temporarily stashed, so we can do things like create thumbnails for it
241 * Arguably UnregisteredLocalFile should be handling its own file repo but that class is a bit retarded currently
242 *
243 * @param $stash UploadStash: useful for obtaining config, stashing transformed files
244 * @param $repo FSRepo: repository where we should find the path
245 * @param $path String: path to file
246 * @param $key String: key to store the path and any stashed data under
247 * @param $data String: any other data we want stored with this file
248 * @throws UploadStashBadPathException
249 * @throws UploadStashFileNotFoundException
250 */
251 public function __construct( $stash, $repo, $path, $key, $data ) {
252 $this->sessionStash = $stash;
253 $this->sessionKey = $key;
254 $this->sessionData = $data;
255
256 // resolve mwrepo:// urls
257 if ( $repo->isVirtualUrl( $path ) ) {
258 $path = $repo->resolveVirtualUrl( $path );
259 }
260
261 // check if path appears to be sane, no parent traversals, and is in this repo's temp zone.
262 $repoTempPath = $repo->getZonePath( 'temp' );
263 if ( ( ! $repo->validateFilename( $path ) ) ||
264 ( strpos( $path, $repoTempPath ) !== 0 ) ) {
265 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not valid\n" );
266 throw new UploadStashBadPathException( 'path is not valid' );
267 }
268
269 // check if path exists! and is a plain file.
270 if ( ! $repo->fileExists( $path, FileRepo::FILES_ONLY ) ) {
271 wfDebug( "UploadStash: tried to construct an UploadStashFile from a file that should already exist at '$path', but path is not found\n" );
272 throw new UploadStashFileNotFoundException( 'cannot find path, or not a plain file' );
273 }
274
275 parent::__construct( false, $repo, $path, false );
276
277 $this->name = basename( $this->path );
278 }
279
280 /**
281 * A method needed by the file transforming and scaling routines in File.php
282 * We do not necessarily care about doing the description at this point
283 * However, we also can't return the empty string, as the rest of MediaWiki demands this (and calls to imagemagick
284 * convert require it to be there)
285 *
286 * @return String: dummy value
287 */
288 public function getDescriptionUrl() {
289 return $this->getUrl();
290 }
291
292 /**
293 * Get the path for the thumbnail (actually any transformation of this file)
294 * The actual argument is the result of thumbName although we seem to have
295 * buggy code elsewhere that expects a boolean 'suffix'
296 *
297 * @param $thumbName String: name of thumbnail (e.g. "120px-123456.jpg" ), or false to just get the path
298 * @return String: path thumbnail should take on filesystem, or containing directory if thumbname is false
299 */
300 public function getThumbPath( $thumbName = false ) {
301 $path = dirname( $this->path );
302 if ( $thumbName !== false ) {
303 $path .= "/$thumbName";
304 }
305 return $path;
306 }
307
308 /**
309 * Return the file/url base name of a thumbnail with the specified parameters.
310 * We override this because we want to use the pretty url name instead of the
311 * ugly file name.
312 *
313 * @param $params Array: handler-specific parameters
314 * @return String: base name for URL, like '120px-12345.jpg', or null if there is no handler
315 */
316 function thumbName( $params ) {
317 return $this->generateThumbName( $this->getUrlName(), $params );
318 }
319
320 /**
321 * Helper function -- given a 'subpage', return the local URL e.g. /wiki/Special:UploadStash/subpage
322 * @param {String} $subPage
323 * @return {String} local URL for this subpage in the Special:UploadStash space.
324 */
325 private function getSpecialUrl( $subPage ) {
326 return SpecialPage::getTitleFor( 'UploadStash', $subPage )->getLocalURL();
327 }
328
329 /**
330 * Get a URL to access the thumbnail
331 * This is required because the model of how files work requires that
332 * the thumbnail urls be predictable. However, in our model the URL is not based on the filename
333 * (that's hidden in the session)
334 *
335 * @param $thumbName String: basename of thumbnail file -- however, we don't want to use the file exactly
336 * @return String: URL to access thumbnail, or URL with partial path
337 */
338 public function getThumbUrl( $thumbName = false ) {
339 wfDebug( __METHOD__ . " getting for $thumbName \n" );
340 return $this->getSpecialUrl( 'thumb/' . $this->getUrlName() . '/' . $thumbName );
341 }
342
343 /**
344 * The basename for the URL, which we want to not be related to the filename.
345 * Will also be used as the lookup key for a thumbnail file.
346 *
347 * @return String: base url name, like '120px-123456.jpg'
348 */
349 public function getUrlName() {
350 if ( ! $this->urlName ) {
351 $this->urlName = $this->sessionKey;
352 }
353 return $this->urlName;
354 }
355
356 /**
357 * Return the URL of the file, if for some reason we wanted to download it
358 * We tend not to do this for the original file, but we do want thumb icons
359 *
360 * @return String: url
361 */
362 public function getUrl() {
363 if ( !isset( $this->url ) ) {
364 $this->url = $this->getSpecialUrl( 'file/' . $this->getUrlName() );
365 }
366 return $this->url;
367 }
368
369 /**
370 * Parent classes use this method, for no obvious reason, to return the path (relative to wiki root, I assume).
371 * But with this class, the URL is unrelated to the path.
372 *
373 * @return String: url
374 */
375 public function getFullUrl() {
376 return $this->getUrl();
377 }
378
379 /**
380 * Getter for session key (the session-unique id by which this file's location & metadata is stored in the session)
381 *
382 * @return String: session key
383 */
384 public function getSessionKey() {
385 return $this->sessionKey;
386 }
387
388 /**
389 * Remove the associated temporary file
390 * @return Status: success
391 */
392 public function remove() {
393 return $this->repo->freeTemp( $this->path );
394 }
395
396 }
397
398 class UploadStashNotAvailableException extends MWException {};
399 class UploadStashFileNotFoundException extends MWException {};
400 class UploadStashBadPathException extends MWException {};
401 class UploadStashBadVersionException extends MWException {};
402 class UploadStashFileException extends MWException {};
403 class UploadStashZeroLengthFileException extends MWException {};
404