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