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