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)
47 $this->scoped = $scoped;
49 $this->filename = $filename;
50 $this->mimetype = $mimetype;
51 $this->fileRecord = $this->storeFile();
53 $this->fileurl = common_local_url('attachment',
54 array('attachment' => $this->fileRecord->id));
56 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
57 $this->short_fileurl = common_shorten_url($this->fileurl);
58 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
61 public function attachToNotice(Notice $notice)
63 File_to_post::processNew($this->fileRecord->id, $notice->id);
64 $this->maybeAddRedir($this->fileRecord->id,
65 common_local_url('file', array('notice' => $notice->id)));
68 public function getPath()
70 return File::path($this->filename);
75 return $this->short_fileurl;
80 $filepath = File::path($this->filename);
84 protected function storeFile()
89 $file->filename = $this->filename;
90 $file->url = File::url($this->filename);
91 $filepath = File::path($this->filename);
92 $file->size = filesize($filepath);
94 $file->mimetype = $this->mimetype;
96 $file_id = $file->insert();
98 if ($file_id===false) {
99 common_log_db_error($file, "INSERT", __FILE__);
100 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
101 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
104 // Set file geometrical properties if available
106 $image = ImageFile::fromFileObject($file);
107 $orig = clone($file);
108 $file->width = $image->width;
109 $file->height = $image->height;
110 $file->update($orig);
112 // We have to cleanup after ImageFile, since it
113 // may have generated a temporary file from a
114 // video support plugin or something.
115 // FIXME: Do this more automagically.
116 if ($image->getPath() != $file->getPath()) {
119 } catch (ServerException $e) {
120 // We just couldn't make out an image from the file. This
121 // does not have to be UnsupportedMediaException, as we can
122 // also get ServerException from files not existing etc.
128 function rememberFile($file, $short)
130 $this->maybeAddRedir($file->id, $short);
133 function maybeAddRedir($file_id, $url)
135 $file_redir = File_redirection::getKV('url', $url);
137 if (empty($file_redir)) {
139 $file_redir = new File_redirection;
140 $file_redir->url = $url;
141 $file_redir->file_id = $file_id;
143 $result = $file_redir->insert();
146 common_log_db_error($file_redir, "INSERT", __FILE__);
147 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
148 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
153 static function fromUpload($param = 'media', Profile $scoped)
155 if (is_null($scoped)) {
156 $scoped = Profile::current();
159 if (!isset($_FILES[$param]['error'])){
163 switch ($_FILES[$param]['error']) {
164 case UPLOAD_ERR_OK: // success, jump out
166 case UPLOAD_ERR_INI_SIZE:
167 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
168 throw new ClientException(_('The uploaded file exceeds the ' .
169 'upload_max_filesize directive in php.ini.'));
170 case UPLOAD_ERR_FORM_SIZE:
171 throw new ClientException(
172 // TRANS: Client exception.
173 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
174 ' that was specified in the HTML form.'));
175 case UPLOAD_ERR_PARTIAL:
176 @unlink($_FILES[$param]['tmp_name']);
177 // TRANS: Client exception.
178 throw new ClientException(_('The uploaded file was only' .
179 ' partially uploaded.'));
180 case UPLOAD_ERR_NO_FILE:
181 // No file; probably just a non-AJAX submission.
183 case UPLOAD_ERR_NO_TMP_DIR:
184 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
185 throw new ClientException(_('Missing a temporary folder.'));
186 case UPLOAD_ERR_CANT_WRITE:
187 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
188 throw new ClientException(_('Failed to write file to disk.'));
189 case UPLOAD_ERR_EXTENSION:
190 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
191 throw new ClientException(_('File upload stopped by extension.'));
193 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
194 $_FILES[$param]['error']);
195 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
196 throw new ClientException(_('System error uploading file.'));
199 // Throws exception if additional size does not respect quota
200 File::respectsQuota($scoped, $_FILES[$param]['size']);
202 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
203 $_FILES[$param]['name']);
205 $basename = basename($_FILES[$param]['name']);
206 $filename = File::filename($scoped, $basename, $mimetype);
207 $filepath = File::path($filename);
209 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
212 // TRANS: Client exception thrown when a file upload operation fails because the file could
213 // TRANS: not be moved from the temporary folder to the permanent file location.
214 throw new ClientException(_('File could not be moved to destination directory.'));
217 return new MediaFile($scoped, $filename, $mimetype);
220 static function fromFilehandle($fh, Profile $scoped) {
222 $stream = stream_get_meta_data($fh);
224 File::respectsQuota($scoped, filesize($stream['uri']));
226 $mimetype = self::getUploadedMimeType($stream['uri']);
228 $filename = File::filename($scoped, "email", $mimetype);
230 $filepath = File::path($filename);
232 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
235 // TRANS: Client exception thrown when a file upload operation fails because the file could
236 // TRANS: not be moved from the temporary folder to the permanent file location.
237 throw new ClientException(_('File could not be moved to destination directory.' .
238 $stream['uri'] . ' ' . $filepath));
241 return new MediaFile($scoped, $filename, $mimetype);
245 * Attempt to identify the content type of a given file.
247 * @param string $filepath filesystem path as string (file must exist)
248 * @param string $originalFilename (optional) for extension-based detection
251 * @fixme this seems to tie a front-end error message in, kinda confusing
253 * @throws ClientException if type is known, but not supported for local uploads
255 static function getUploadedMimeType($filepath, $originalFilename=false) {
256 // We only accept filenames to existing files
257 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
258 $mimetype = $mimelookup->file($filepath);
260 // Unclear types are such that we can't really tell by the auto
261 // detect what they are (.bin, .exe etc. are just "octet-stream")
262 $unclearTypes = array('application/octet-stream',
263 'application/vnd.ms-office',
265 // TODO: for XML we could do better content-based sniffing too
268 $supported = common_config('attachments', 'supported');
270 // If we didn't match, or it is an unclear match
271 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
273 $type = common_supported_ext_to_mime($originalFilename);
275 } catch (Exception $e) {
276 // Extension not found, so $mimetype is our best guess
280 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
281 if ($supported === true || array_key_exists($mimetype, $supported)) {
282 // FIXME: Don't know if it always has a mimetype here because
283 // finfo->file CAN return false on error: http://php.net/finfo_file
284 // so if $supported === true, this may return something unexpected.
288 // We can conclude that we have failed to get the MIME type
289 $media = common_get_mime_media($mimetype);
290 if ('application' !== $media) {
291 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
292 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
293 // TRANS: the MIME type that was denied.
294 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
295 'Try using another %2$s format.'), $mimetype, $media);
297 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
298 // TRANS: %s is the file type that was denied.
299 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
301 throw new ClientException($hint);