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