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;
79 $filepath = File::path($this->filename);
83 public function getFile()
85 if (!$this->fileRecord instanceof File) {
86 throw new ServerException('File record did not exist for MediaFile');
89 return $this->fileRecord;
92 protected function storeFile()
94 $filepath = File::path($this->filename);
95 if (!empty($this->filename) && $this->filehash === null) {
96 // Calculate if we have an older upload method somewhere (Qvitter) that
97 // doesn't do this before calling new MediaFile on its local files...
98 $this->filehash = hash_file(File::FILEHASH_ALG, $filepath);
99 if ($this->filehash === false) {
100 throw new ServerException('Could not read file for hashing');
105 $file = File::getByHash($this->filehash);
106 // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
108 } catch (NoResultException $e) {
109 // Well, let's just continue below.
112 $fileurl = File::url($this->filename);
116 $file->filename = $this->filename;
117 $file->urlhash = File::hashurl($fileurl);
118 $file->url = $fileurl;
119 $file->filehash = $this->filehash;
120 $file->size = filesize($filepath);
121 if ($file->size === false) {
122 throw new ServerException('Could not read file to get its size');
124 $file->date = time();
125 $file->mimetype = $this->mimetype;
128 $file_id = $file->insert();
130 if ($file_id===false) {
131 common_log_db_error($file, "INSERT", __FILE__);
132 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
133 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
136 // Set file geometrical properties if available
138 $image = ImageFile::fromFileObject($file);
139 $orig = clone($file);
140 $file->width = $image->width;
141 $file->height = $image->height;
142 $file->update($orig);
144 // We have to cleanup after ImageFile, since it
145 // may have generated a temporary file from a
146 // video support plugin or something.
147 // FIXME: Do this more automagically.
148 if ($image->getPath() != $file->getPath()) {
151 } catch (ServerException $e) {
152 // We just couldn't make out an image from the file. This
153 // does not have to be UnsupportedMediaException, as we can
154 // also get ServerException from files not existing etc.
160 function rememberFile($file, $short)
162 $this->maybeAddRedir($file->id, $short);
165 function maybeAddRedir($file_id, $url)
168 $file_redir = File_redirection::getByUrl($url);
169 } catch (NoResultException $e) {
170 $file_redir = new File_redirection;
171 $file_redir->urlhash = File::hashurl($url);
172 $file_redir->url = $url;
173 $file_redir->file_id = $file_id;
175 $result = $file_redir->insert();
177 if ($result===false) {
178 common_log_db_error($file_redir, "INSERT", __FILE__);
179 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
180 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
185 static function fromUpload($param='media', Profile $scoped=null)
187 if (is_null($scoped)) {
188 $scoped = Profile::current();
191 // The existence of the "error" element means PHP has processed it properly even if it was ok.
192 if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
193 throw new NoUploadedMediaException($param);
196 switch ($_FILES[$param]['error']) {
197 case UPLOAD_ERR_OK: // success, jump out
199 case UPLOAD_ERR_INI_SIZE:
200 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
201 throw new ClientException(_('The uploaded file exceeds the ' .
202 'upload_max_filesize directive in php.ini.'));
203 case UPLOAD_ERR_FORM_SIZE:
204 throw new ClientException(
205 // TRANS: Client exception.
206 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
207 ' that was specified in the HTML form.'));
208 case UPLOAD_ERR_PARTIAL:
209 @unlink($_FILES[$param]['tmp_name']);
210 // TRANS: Client exception.
211 throw new ClientException(_('The uploaded file was only' .
212 ' partially uploaded.'));
213 case UPLOAD_ERR_NO_FILE:
214 // No file; probably just a non-AJAX submission.
215 throw new NoUploadedMediaException($param);
216 case UPLOAD_ERR_NO_TMP_DIR:
217 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
218 throw new ClientException(_('Missing a temporary folder.'));
219 case UPLOAD_ERR_CANT_WRITE:
220 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
221 throw new ClientException(_('Failed to write file to disk.'));
222 case UPLOAD_ERR_EXTENSION:
223 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
224 throw new ClientException(_('File upload stopped by extension.'));
226 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
227 $_FILES[$param]['error']);
228 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
229 throw new ClientException(_('System error uploading file.'));
232 // TODO: Make documentation clearer that this won't work for files >2GiB because
233 // PHP is stupid in its 32bit head. But noone accepts 2GiB files with PHP
235 $filehash = hash_file(File::FILEHASH_ALG, $_FILES[$param]['tmp_name']);
238 $file = File::getByHash($filehash);
239 // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
240 $filename = $file->filename;
241 $mimetype = $file->mimetype;
243 } catch (NoResultException $e) {
244 // We have to save the upload as a new local file. This is the normal course of action.
246 // Throws exception if additional size does not respect quota
247 // This test is only needed, of course, if we're uploading something new.
248 File::respectsQuota($scoped, $_FILES[$param]['size']);
250 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
252 switch (common_config('attachments', 'filename_base')) {
254 $basename = basename($_FILES[$param]['name']);
255 $filename = File::filename($scoped, $basename, $mimetype);
259 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
261 $filepath = File::path($filename);
263 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
266 // TRANS: Client exception thrown when a file upload operation fails because the file could
267 // TRANS: not be moved from the temporary folder to the permanent file location.
268 throw new ClientException(_('File could not be moved to destination directory.'));
272 return new MediaFile($scoped, $filename, $mimetype, $filehash);
275 static function fromFilehandle($fh, Profile $scoped) {
276 $stream = stream_get_meta_data($fh);
277 // So far we're only handling filehandles originating from tmpfile(),
278 // so we can always do hash_file on $stream['uri'] as far as I can tell!
279 $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
282 $file = File::getByHash($filehash);
283 // Already have it, so let's reuse the locally stored File
284 $filename = $file->filename;
285 $mimetype = $file->mimetype;
286 } catch (NoResultException $e) {
287 File::respectsQuota($scoped, filesize($stream['uri']));
289 $mimetype = self::getUploadedMimeType($stream['uri']);
291 switch (common_config('attachments', 'filename_base')) {
293 $filename = File::filename($scoped, "email", $mimetype);
297 $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
299 $filepath = File::path($filename);
301 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
304 // TRANS: Client exception thrown when a file upload operation fails because the file could
305 // TRANS: not be moved from the temporary folder to the permanent file location.
306 throw new ClientException(_('File could not be moved to destination directory.' .
307 $stream['uri'] . ' ' . $filepath));
311 return new MediaFile($scoped, $filename, $mimetype, $filehash);
315 * Attempt to identify the content type of a given file.
317 * @param string $filepath filesystem path as string (file must exist)
318 * @param string $originalFilename (optional) for extension-based detection
321 * @fixme this seems to tie a front-end error message in, kinda confusing
323 * @throws ClientException if type is known, but not supported for local uploads
325 static function getUploadedMimeType($filepath, $originalFilename=false) {
326 // We only accept filenames to existing files
327 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
328 $mimetype = $mimelookup->file($filepath);
330 // Unclear types are such that we can't really tell by the auto
331 // detect what they are (.bin, .exe etc. are just "octet-stream")
332 $unclearTypes = array('application/octet-stream',
333 'application/vnd.ms-office',
335 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
336 // TODO: for XML we could do better content-based sniffing too
339 $supported = common_config('attachments', 'supported');
341 // If we didn't match, or it is an unclear match
342 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
344 $type = common_supported_ext_to_mime($originalFilename);
346 } catch (Exception $e) {
347 // Extension not found, so $mimetype is our best guess
351 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
352 if ($supported === true || array_key_exists($mimetype, $supported)) {
353 // FIXME: Don't know if it always has a mimetype here because
354 // finfo->file CAN return false on error: http://php.net/finfo_file
355 // so if $supported === true, this may return something unexpected.
359 // We can conclude that we have failed to get the MIME type
360 $media = common_get_mime_media($mimetype);
361 if ('application' !== $media) {
362 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
363 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
364 // TRANS: the MIME type that was denied.
365 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
366 'Try using another %2$s format.'), $mimetype, $media);
368 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
369 // TRANS: %s is the file type that was denied.
370 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
372 throw new ClientException($hint);