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); }
37 protected $scoped = null;
40 var $fileRecord = null;
42 var $short_fileurl = null;
45 function __construct(Profile $scoped, $filename = null, $mimetype = null, $filehash = null)
47 $this->scoped = $scoped;
49 $this->filename = $filename;
50 $this->mimetype = $mimetype;
51 $this->filehash = $filehash;
52 $this->fileRecord = $this->storeFile();
54 $this->fileurl = common_local_url('attachment',
55 array('attachment' => $this->fileRecord->id));
57 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
58 $this->short_fileurl = common_shorten_url($this->fileurl);
59 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
62 public function attachToNotice(Notice $notice)
64 File_to_post::processNew($this->fileRecord, $notice);
67 public function getPath()
69 return File::path($this->filename);
74 return $this->short_fileurl;
77 function getEnclosure()
79 return $this->getFile()->getEnclosure();
84 $filepath = File::path($this->filename);
88 public function getFile()
90 if (!$this->fileRecord instanceof File) {
91 throw new ServerException('File record did not exist for MediaFile');
94 return $this->fileRecord;
97 protected function storeFile()
99 $filepath = File::path($this->filename);
100 if (!empty($this->filename) && $this->filehash === null) {
101 // Calculate if we have an older upload method somewhere (Qvitter) that
102 // doesn't do this before calling new MediaFile on its local files...
103 $this->filehash = hash_file(File::FILEHASH_ALG, $filepath);
104 if ($this->filehash === false) {
105 throw new ServerException('Could not read file for hashing');
110 $file = File::getByHash($this->filehash);
111 // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
113 } catch (NoResultException $e) {
114 // Well, let's just continue below.
117 $fileurl = File::url($this->filename);
121 $file->filename = $this->filename;
122 $file->urlhash = File::hashurl($fileurl);
123 $file->url = $fileurl;
124 $file->filehash = $this->filehash;
125 $file->size = filesize($filepath);
126 if ($file->size === false) {
127 throw new ServerException('Could not read file to get its size');
129 $file->date = time();
130 $file->mimetype = $this->mimetype;
133 $file_id = $file->insert();
135 if ($file_id===false) {
136 common_log_db_error($file, "INSERT", __FILE__);
137 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
138 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
141 // Set file geometrical properties if available
143 $image = ImageFile::fromFileObject($file);
144 $orig = clone($file);
145 $file->width = $image->width;
146 $file->height = $image->height;
147 $file->update($orig);
149 // We have to cleanup after ImageFile, since it
150 // may have generated a temporary file from a
151 // video support plugin or something.
152 // FIXME: Do this more automagically.
153 if ($image->getPath() != $file->getPath()) {
156 } catch (ServerException $e) {
157 // We just couldn't make out an image from the file. This
158 // does not have to be UnsupportedMediaException, as we can
159 // also get ServerException from files not existing etc.
165 function rememberFile($file, $short)
167 $this->maybeAddRedir($file->id, $short);
170 function maybeAddRedir($file_id, $url)
173 $file_redir = File_redirection::getByUrl($url);
174 } catch (NoResultException $e) {
175 $file_redir = new File_redirection;
176 $file_redir->urlhash = File::hashurl($url);
177 $file_redir->url = $url;
178 $file_redir->file_id = $file_id;
180 $result = $file_redir->insert();
182 if ($result===false) {
183 common_log_db_error($file_redir, "INSERT", __FILE__);
184 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
185 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
190 static function fromUpload($param='media', Profile $scoped=null)
192 if (is_null($scoped)) {
193 $scoped = Profile::current();
196 // The existence of the "error" element means PHP has processed it properly even if it was ok.
197 if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
198 throw new NoUploadedMediaException($param);
201 switch ($_FILES[$param]['error']) {
202 case UPLOAD_ERR_OK: // success, jump out
204 case UPLOAD_ERR_INI_SIZE:
205 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
206 throw new ClientException(_('The uploaded file exceeds the ' .
207 'upload_max_filesize directive in php.ini.'));
208 case UPLOAD_ERR_FORM_SIZE:
209 throw new ClientException(
210 // TRANS: Client exception.
211 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
212 ' that was specified in the HTML form.'));
213 case UPLOAD_ERR_PARTIAL:
214 @unlink($_FILES[$param]['tmp_name']);
215 // TRANS: Client exception.
216 throw new ClientException(_('The uploaded file was only' .
217 ' partially uploaded.'));
218 case UPLOAD_ERR_NO_FILE:
219 // No file; probably just a non-AJAX submission.
220 throw new NoUploadedMediaException($param);
221 case UPLOAD_ERR_NO_TMP_DIR:
222 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
223 throw new ClientException(_('Missing a temporary folder.'));
224 case UPLOAD_ERR_CANT_WRITE:
225 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
226 throw new ClientException(_('Failed to write file to disk.'));
227 case UPLOAD_ERR_EXTENSION:
228 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
229 throw new ClientException(_('File upload stopped by extension.'));
231 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
232 $_FILES[$param]['error']);
233 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
234 throw new ClientException(_('System error uploading file.'));
237 // TODO: Make documentation clearer that this won't work for files >2GiB because
238 // PHP is stupid in its 32bit head. But noone accepts 2GiB files with PHP
240 $filehash = hash_file(File::FILEHASH_ALG, $_FILES[$param]['tmp_name']);
243 $file = File::getByHash($filehash);
244 // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
245 $filename = $file->filename;
246 $mimetype = $file->mimetype;
248 } catch (NoResultException $e) {
249 // We have to save the upload as a new local file. This is the normal course of action.
251 // Throws exception if additional size does not respect quota
252 // This test is only needed, of course, if we're uploading something new.
253 File::respectsQuota($scoped, $_FILES[$param]['size']);
255 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
256 $basename = basename($_FILES[$param]['name']);
258 switch (common_config('attachments', 'filename_base')) {
260 $filename = File::filename($scoped, $basename, $mimetype);
264 $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($scoped, $filename, $mimetype, $filehash);
280 static function fromFilehandle($fh, Profile $scoped) {
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 $filename = $file->filename;
290 $mimetype = $file->mimetype;
291 } catch (NoResultException $e) {
292 File::respectsQuota($scoped, filesize($stream['uri']));
294 $mimetype = self::getUploadedMimeType($stream['uri']);
296 switch (common_config('attachments', 'filename_base')) {
298 $filename = File::filename($scoped, "email", $mimetype);
302 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
304 $filepath = File::path($filename);
306 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
309 // TRANS: Client exception thrown when a file upload operation fails because the file could
310 // TRANS: not be moved from the temporary folder to the permanent file location.
311 throw new ClientException(_('File could not be moved to destination directory.' .
312 $stream['uri'] . ' ' . $filepath));
316 return new MediaFile($scoped, $filename, $mimetype, $filehash);
320 * Attempt to identify the content type of a given file.
322 * @param string $filepath filesystem path as string (file must exist)
323 * @param string $originalFilename (optional) for extension-based detection
326 * @fixme this seems to tie a front-end error message in, kinda confusing
328 * @throws ClientException if type is known, but not supported for local uploads
330 static function getUploadedMimeType($filepath, $originalFilename=false) {
331 // We only accept filenames to existing files
332 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
333 $mimetype = $mimelookup->file($filepath);
335 // Unclear types are such that we can't really tell by the auto
336 // detect what they are (.bin, .exe etc. are just "octet-stream")
337 $unclearTypes = array('application/octet-stream',
338 'application/vnd.ms-office',
340 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
341 // TODO: for XML we could do better content-based sniffing too
344 $supported = common_config('attachments', 'supported');
346 // If we didn't match, or it is an unclear match
347 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
349 $type = common_supported_ext_to_mime($originalFilename);
351 } catch (Exception $e) {
352 // Extension not found, so $mimetype is our best guess
356 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
357 if ($supported === true || array_key_exists($mimetype, $supported)) {
358 // FIXME: Don't know if it always has a mimetype here because
359 // finfo->file CAN return false on error: http://php.net/finfo_file
360 // so if $supported === true, this may return something unexpected.
364 // We can conclude that we have failed to get the MIME type
365 $media = common_get_mime_media($mimetype);
366 if ('application' !== $media) {
367 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
368 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
369 // TRANS: the MIME type that was denied.
370 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
371 'Try using another %2$s format.'), $mimetype, $media);
373 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
374 // TRANS: %s is the file type that was denied.
375 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
377 throw new ClientException($hint);