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);
66 public function getPath()
68 return File::path($this->filename);
73 return $this->short_fileurl;
78 $filepath = File::path($this->filename);
82 public function getFile()
84 if (!$this->fileRecord instanceof File) {
85 throw new ServerException('File record did not exist for MediaFile');
88 return $this->fileRecord;
91 protected function storeFile()
96 $file->filename = $this->filename;
97 $file->url = File::url($this->filename);
98 $filepath = File::path($this->filename);
99 $file->size = filesize($filepath);
100 $file->date = time();
101 $file->mimetype = $this->mimetype;
103 $file_id = $file->insert();
105 if ($file_id===false) {
106 common_log_db_error($file, "INSERT", __FILE__);
107 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
108 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
111 // Set file geometrical properties if available
113 $image = ImageFile::fromFileObject($file);
114 $orig = clone($file);
115 $file->width = $image->width;
116 $file->height = $image->height;
117 $file->update($orig);
119 // We have to cleanup after ImageFile, since it
120 // may have generated a temporary file from a
121 // video support plugin or something.
122 // FIXME: Do this more automagically.
123 if ($image->getPath() != $file->getPath()) {
126 } catch (ServerException $e) {
127 // We just couldn't make out an image from the file. This
128 // does not have to be UnsupportedMediaException, as we can
129 // also get ServerException from files not existing etc.
135 function rememberFile($file, $short)
137 $this->maybeAddRedir($file->id, $short);
140 function maybeAddRedir($file_id, $url)
142 $file_redir = File_redirection::getKV('url', $url);
144 if (!$file_redir instanceof File_redirection) {
145 $file_redir = new File_redirection;
146 $file_redir->url = $url;
147 $file_redir->file_id = $file_id;
149 $result = $file_redir->insert();
151 if ($result===false) {
152 common_log_db_error($file_redir, "INSERT", __FILE__);
153 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
154 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
159 static function fromUpload($param='media', Profile $scoped=null)
161 if (is_null($scoped)) {
162 $scoped = Profile::current();
165 // The existence of the "error" element means PHP has processed it properly even if it was ok.
166 if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
167 throw new NoUploadedMediaException($param);
170 switch ($_FILES[$param]['error']) {
171 case UPLOAD_ERR_OK: // success, jump out
173 case UPLOAD_ERR_INI_SIZE:
174 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
175 throw new ClientException(_('The uploaded file exceeds the ' .
176 'upload_max_filesize directive in php.ini.'));
177 case UPLOAD_ERR_FORM_SIZE:
178 throw new ClientException(
179 // TRANS: Client exception.
180 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
181 ' that was specified in the HTML form.'));
182 case UPLOAD_ERR_PARTIAL:
183 @unlink($_FILES[$param]['tmp_name']);
184 // TRANS: Client exception.
185 throw new ClientException(_('The uploaded file was only' .
186 ' partially uploaded.'));
187 case UPLOAD_ERR_NO_FILE:
188 // No file; probably just a non-AJAX submission.
189 throw new NoUploadedMediaException($param);
190 case UPLOAD_ERR_NO_TMP_DIR:
191 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
192 throw new ClientException(_('Missing a temporary folder.'));
193 case UPLOAD_ERR_CANT_WRITE:
194 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
195 throw new ClientException(_('Failed to write file to disk.'));
196 case UPLOAD_ERR_EXTENSION:
197 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
198 throw new ClientException(_('File upload stopped by extension.'));
200 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
201 $_FILES[$param]['error']);
202 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
203 throw new ClientException(_('System error uploading file.'));
206 // Throws exception if additional size does not respect quota
207 File::respectsQuota($scoped, $_FILES[$param]['size']);
209 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
210 $_FILES[$param]['name']);
212 $basename = basename($_FILES[$param]['name']);
213 $filename = File::filename($scoped, $basename, $mimetype);
214 $filepath = File::path($filename);
216 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
219 // TRANS: Client exception thrown when a file upload operation fails because the file could
220 // TRANS: not be moved from the temporary folder to the permanent file location.
221 throw new ClientException(_('File could not be moved to destination directory.'));
224 return new MediaFile($scoped, $filename, $mimetype);
227 static function fromFilehandle($fh, Profile $scoped) {
229 $stream = stream_get_meta_data($fh);
231 File::respectsQuota($scoped, filesize($stream['uri']));
233 $mimetype = self::getUploadedMimeType($stream['uri']);
235 $filename = File::filename($scoped, "email", $mimetype);
237 $filepath = File::path($filename);
239 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
242 // TRANS: Client exception thrown when a file upload operation fails because the file could
243 // TRANS: not be moved from the temporary folder to the permanent file location.
244 throw new ClientException(_('File could not be moved to destination directory.' .
245 $stream['uri'] . ' ' . $filepath));
248 return new MediaFile($scoped, $filename, $mimetype);
252 * Attempt to identify the content type of a given file.
254 * @param string $filepath filesystem path as string (file must exist)
255 * @param string $originalFilename (optional) for extension-based detection
258 * @fixme this seems to tie a front-end error message in, kinda confusing
260 * @throws ClientException if type is known, but not supported for local uploads
262 static function getUploadedMimeType($filepath, $originalFilename=false) {
263 // We only accept filenames to existing files
264 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
265 $mimetype = $mimelookup->file($filepath);
267 // Unclear types are such that we can't really tell by the auto
268 // detect what they are (.bin, .exe etc. are just "octet-stream")
269 $unclearTypes = array('application/octet-stream',
270 'application/vnd.ms-office',
272 // TODO: for XML we could do better content-based sniffing too
275 $supported = common_config('attachments', 'supported');
277 // If we didn't match, or it is an unclear match
278 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
280 $type = common_supported_ext_to_mime($originalFilename);
282 } catch (Exception $e) {
283 // Extension not found, so $mimetype is our best guess
287 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
288 if ($supported === true || array_key_exists($mimetype, $supported)) {
289 // FIXME: Don't know if it always has a mimetype here because
290 // finfo->file CAN return false on error: http://php.net/finfo_file
291 // so if $supported === true, this may return something unexpected.
295 // We can conclude that we have failed to get the MIME type
296 $media = common_get_mime_media($mimetype);
297 if ('application' !== $media) {
298 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
299 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
300 // TRANS: the MIME type that was denied.
301 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
302 'Try using another %2$s format.'), $mimetype, $media);
304 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
305 // TRANS: %s is the file type that was denied.
306 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
308 throw new ClientException($hint);