3 * StatusNet, the distributed open-source microblogging tool
5 * Abstraction for media files in general
7 * TODO: combine with ImageFile?
11 * LICENCE: This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Affero General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
21 * You should have received a copy of the GNU Affero General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 * @author Robin Millette <robin@millette.info>
27 * @author Zach Copley <zach@status.net>
28 * @copyright 2008-2009 StatusNet, Inc.
29 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
30 * @link http://status.net/
33 if (!defined('GNUSOCIAL')) { exit(1); }
38 var $fileRecord = null;
40 var $short_fileurl = null;
43 function __construct($filename = null, $mimetype = null, $filehash = null)
45 $this->filename = $filename;
46 $this->mimetype = $mimetype;
47 $this->filehash = $filehash;
48 $this->fileRecord = $this->storeFile();
50 $this->fileurl = common_local_url('attachment',
51 array('attachment' => $this->fileRecord->id));
53 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
54 $this->short_fileurl = common_shorten_url($this->fileurl);
55 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
58 public function attachToNotice(Notice $notice)
60 File_to_post::processNew($this->fileRecord, $notice);
63 public function getPath()
65 return File::path($this->filename);
70 return $this->short_fileurl;
73 function getEnclosure()
75 return $this->getFile()->getEnclosure();
80 $filepath = File::path($this->filename);
84 public function getFile()
86 if (!$this->fileRecord instanceof File) {
87 throw new ServerException('File record did not exist for MediaFile');
90 return $this->fileRecord;
93 protected function storeFile()
95 $filepath = File::path($this->filename);
96 if (!empty($this->filename) && $this->filehash === null) {
97 // Calculate if we have an older upload method somewhere (Qvitter) that
98 // doesn't do this before calling new MediaFile on its local files...
99 $this->filehash = hash_file(File::FILEHASH_ALG, $filepath);
100 if ($this->filehash === false) {
101 throw new ServerException('Could not read file for hashing');
106 $file = File::getByHash($this->filehash);
107 // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
109 } catch (NoResultException $e) {
110 // Well, let's just continue below.
113 $fileurl = File::url($this->filename);
117 $file->filename = $this->filename;
118 $file->urlhash = File::hashurl($fileurl);
119 $file->url = $fileurl;
120 $file->filehash = $this->filehash;
121 $file->size = filesize($filepath);
122 if ($file->size === false) {
123 throw new ServerException('Could not read file to get its size');
125 $file->date = time();
126 $file->mimetype = $this->mimetype;
129 $file_id = $file->insert();
131 if ($file_id===false) {
132 common_log_db_error($file, "INSERT", __FILE__);
133 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
134 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
137 // Set file geometrical properties if available
139 $image = ImageFile::fromFileObject($file);
140 $orig = clone($file);
141 $file->width = $image->width;
142 $file->height = $image->height;
143 $file->update($orig);
145 // We have to cleanup after ImageFile, since it
146 // may have generated a temporary file from a
147 // video support plugin or something.
148 // FIXME: Do this more automagically.
149 if ($image->getPath() != $file->getPath()) {
152 } catch (ServerException $e) {
153 // We just couldn't make out an image from the file. This
154 // does not have to be UnsupportedMediaException, as we can
155 // also get ServerException from files not existing etc.
161 function rememberFile($file, $short)
163 $this->maybeAddRedir($file->id, $short);
166 function maybeAddRedir($file_id, $url)
169 $file_redir = File_redirection::getByUrl($url);
170 } catch (NoResultException $e) {
171 $file_redir = new File_redirection;
172 $file_redir->urlhash = File::hashurl($url);
173 $file_redir->url = $url;
174 $file_redir->file_id = $file_id;
176 $result = $file_redir->insert();
178 if ($result===false) {
179 common_log_db_error($file_redir, "INSERT", __FILE__);
180 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
181 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
186 static function fromUpload($param='media', Profile $scoped=null)
188 // The existence of the "error" element means PHP has processed it properly even if it was ok.
189 if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
190 throw new NoUploadedMediaException($param);
193 switch ($_FILES[$param]['error']) {
194 case UPLOAD_ERR_OK: // success, jump out
196 case UPLOAD_ERR_INI_SIZE:
197 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
198 throw new ClientException(_('The uploaded file exceeds the ' .
199 'upload_max_filesize directive in php.ini.'));
200 case UPLOAD_ERR_FORM_SIZE:
201 throw new ClientException(
202 // TRANS: Client exception.
203 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
204 ' that was specified in the HTML form.'));
205 case UPLOAD_ERR_PARTIAL:
206 @unlink($_FILES[$param]['tmp_name']);
207 // TRANS: Client exception.
208 throw new ClientException(_('The uploaded file was only' .
209 ' partially uploaded.'));
210 case UPLOAD_ERR_NO_FILE:
211 // No file; probably just a non-AJAX submission.
212 throw new NoUploadedMediaException($param);
213 case UPLOAD_ERR_NO_TMP_DIR:
214 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
215 throw new ClientException(_('Missing a temporary folder.'));
216 case UPLOAD_ERR_CANT_WRITE:
217 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
218 throw new ClientException(_('Failed to write file to disk.'));
219 case UPLOAD_ERR_EXTENSION:
220 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
221 throw new ClientException(_('File upload stopped by extension.'));
223 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
224 $_FILES[$param]['error']);
225 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
226 throw new ClientException(_('System error uploading file.'));
229 // TODO: Make documentation clearer that this won't work for files >2GiB because
230 // PHP is stupid in its 32bit head. But noone accepts 2GiB files with PHP
232 $filehash = hash_file(File::FILEHASH_ALG, $_FILES[$param]['tmp_name']);
235 $file = File::getByHash($filehash);
236 // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
237 // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
238 $filename = basename($file->getPath());
239 $mimetype = $file->mimetype;
241 } catch (FileNotFoundException $e) {
242 // The file does not exist in our local filesystem, so store this upload.
244 if (!move_uploaded_file($_FILES[$param]['tmp_name'], $e->path)) {
245 // TRANS: Client exception thrown when a file upload operation fails because the file could
246 // TRANS: not be moved from the temporary folder to the permanent file location.
247 throw new ClientException(_('File could not be moved to destination directory.'));
250 $filename = basename($file->getPath());
251 $mimetype = $file->mimetype;
253 } catch (NoResultException $e) {
254 // We have to save the upload as a new local file. This is the normal course of action.
256 if ($scoped instanceof Profile) {
257 // Throws exception if additional size does not respect quota
258 // This test is only needed, of course, if we're uploading something new.
259 File::respectsQuota($scoped, $_FILES[$param]['size']);
262 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
263 $basename = basename($_FILES[$param]['name']);
265 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype, $basename);
266 $filepath = File::path($filename);
268 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
271 // TRANS: Client exception thrown when a file upload operation fails because the file could
272 // TRANS: not be moved from the temporary folder to the permanent file location.
273 throw new ClientException(_('File could not be moved to destination directory.'));
277 return new MediaFile($filename, $mimetype, $filehash);
280 static function fromFilehandle($fh, Profile $scoped=null) {
281 $stream = stream_get_meta_data($fh);
282 // So far we're only handling filehandles originating from tmpfile(),
283 // so we can always do hash_file on $stream['uri'] as far as I can tell!
284 $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
287 $file = File::getByHash($filehash);
288 // Already have it, so let's reuse the locally stored File
289 // by using getPath we also check whether the file exists
290 // and throw a FileNotFoundException with the path if it doesn't.
291 $filename = basename($file->getPath());
292 $mimetype = $file->mimetype;
293 } catch (FileNotFoundException $e) {
294 // This happens if the file we have uploaded has disappeared
295 // from the local filesystem for some reason. Since we got the
296 // File object from a sha256 check in fromFilehandle, it's safe
297 // to just copy the uploaded data to disk!
299 fseek($fh, 0); // just to be sure, go to the beginning
300 // dump the contents of our filehandle to the path from our exception
301 // and report error if it failed.
302 if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
303 // TRANS: Client exception thrown when a file upload operation fails because the file could
304 // TRANS: not be moved from the temporary folder to the permanent file location.
305 throw new ClientException(_('File could not be moved to destination directory.'));
307 if (!chmod($e->path, 0664)) {
308 common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
311 $filename = basename($file->getPath());
312 $mimetype = $file->mimetype;
314 } catch (NoResultException $e) {
315 if ($scoped instanceof Profile) {
316 File::respectsQuota($scoped, filesize($stream['uri']));
319 $mimetype = self::getUploadedMimeType($stream['uri']);
321 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
322 $filepath = File::path($filename);
324 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
327 common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
328 // TRANS: Client exception thrown when a file upload operation fails because the file could
329 // TRANS: not be moved from the temporary folder to the permanent file location.
330 throw new ClientException(_('File could not be moved to destination directory.' ));
334 return new MediaFile($filename, $mimetype, $filehash);
338 * Attempt to identify the content type of a given file.
340 * @param string $filepath filesystem path as string (file must exist)
341 * @param string $originalFilename (optional) for extension-based detection
344 * @fixme this seems to tie a front-end error message in, kinda confusing
346 * @throws ClientException if type is known, but not supported for local uploads
348 static function getUploadedMimeType($filepath, $originalFilename=false) {
349 // We only accept filenames to existing files
350 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
351 $mimetype = $mimelookup->file($filepath);
353 // Unclear types are such that we can't really tell by the auto
354 // detect what they are (.bin, .exe etc. are just "octet-stream")
355 $unclearTypes = array('application/octet-stream',
356 'application/vnd.ms-office',
358 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
359 // TODO: for XML we could do better content-based sniffing too
362 $supported = common_config('attachments', 'supported');
364 // If we didn't match, or it is an unclear match
365 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
367 $type = common_supported_ext_to_mime($originalFilename);
369 } catch (Exception $e) {
370 // Extension not found, so $mimetype is our best guess
374 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
375 if ($supported === true || array_key_exists($mimetype, $supported)) {
376 // FIXME: Don't know if it always has a mimetype here because
377 // finfo->file CAN return false on error: http://php.net/finfo_file
378 // so if $supported === true, this may return something unexpected.
382 // We can conclude that we have failed to get the MIME type
383 $media = common_get_mime_media($mimetype);
384 if ('application' !== $media) {
385 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
386 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
387 // TRANS: the MIME type that was denied.
388 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
389 'Try using another %2$s format.'), $mimetype, $media);
391 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
392 // TRANS: %s is the file type that was denied.
393 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
395 throw new ClientException($hint);