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('STATUSNET') && !defined('LACONICA')) {
41 var $fileRecord = null;
44 var $short_fileurl = null;
47 function __construct($user = null, $filename = null, $mimetype = null)
50 $this->user = common_current_user();
53 $this->filename = $filename;
54 $this->mimetype = $mimetype;
55 $this->fileRecord = $this->storeFile();
57 $this->fileurl = common_local_url('attachment',
58 array('attachment' => $this->fileRecord->id));
60 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
61 $this->short_fileurl = common_shorten_url($this->fileurl);
62 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
65 function attachToNotice($notice)
67 File_to_post::processNew($this->fileRecord->id, $notice->id);
68 $this->maybeAddRedir($this->fileRecord->id,
69 common_local_url('file', array('notice' => $notice->id)));
74 return $this->short_fileurl;
79 $filepath = File::path($this->filename);
83 function storeFile() {
87 $file->filename = $this->filename;
88 $file->url = File::url($this->filename);
89 $filepath = File::path($this->filename);
90 $file->size = filesize($filepath);
92 $file->mimetype = $this->mimetype;
94 $file_id = $file->insert();
97 common_log_db_error($file, "INSERT", __FILE__);
98 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
104 function rememberFile($file, $short)
106 $this->maybeAddRedir($file->id, $short);
109 function maybeAddRedir($file_id, $url)
111 $file_redir = File_redirection::staticGet('url', $url);
113 if (empty($file_redir)) {
115 $file_redir = new File_redirection;
116 $file_redir->url = $url;
117 $file_redir->file_id = $file_id;
119 $result = $file_redir->insert();
122 common_log_db_error($file_redir, "INSERT", __FILE__);
123 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
128 static function fromUpload($param = 'media', $user = null)
131 $user = common_current_user();
134 if (!isset($_FILES[$param]['error'])){
138 switch ($_FILES[$param]['error']) {
139 case UPLOAD_ERR_OK: // success, jump out
141 case UPLOAD_ERR_INI_SIZE:
142 throw new ClientException(_('The uploaded file exceeds the ' .
143 'upload_max_filesize directive in php.ini.'));
145 case UPLOAD_ERR_FORM_SIZE:
146 throw new ClientException(
147 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
148 ' that was specified in the HTML form.'));
150 case UPLOAD_ERR_PARTIAL:
151 @unlink($_FILES[$param]['tmp_name']);
152 throw new ClientException(_('The uploaded file was only' .
153 ' partially uploaded.'));
155 case UPLOAD_ERR_NO_FILE:
156 // No file; probably just a non-AJAX submission.
158 case UPLOAD_ERR_NO_TMP_DIR:
159 throw new ClientException(_('Missing a temporary folder.'));
161 case UPLOAD_ERR_CANT_WRITE:
162 throw new ClientException(_('Failed to write file to disk.'));
164 case UPLOAD_ERR_EXTENSION:
165 throw new ClientException(_('File upload stopped by extension.'));
168 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
169 $_FILES[$param]['error']);
170 throw new ClientException(_('System error uploading file.'));
174 if (!MediaFile::respectsQuota($user, $_FILES['attach']['size'])) {
176 // Should never actually get here
178 @unlink($_FILES[$param]['tmp_name']);
179 throw new ClientException(_('File exceeds user\'s quota.'));
183 $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
184 $_FILES[$param]['name']);
188 if (isset($mimetype)) {
190 $basename = basename($_FILES[$param]['name']);
191 $filename = File::filename($user->getProfile(), $basename, $mimetype);
192 $filepath = File::path($filename);
194 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
197 throw new ClientException(_('File could not be moved to destination directory.'));
202 throw new ClientException(_('Could not determine file\'s MIME type.'));
206 return new MediaFile($user, $filename, $mimetype);
209 static function fromFilehandle($fh, $user) {
211 $stream = stream_get_meta_data($fh);
213 if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
215 // Should never actually get here
217 throw new ClientException(_('File exceeds user\'s quota.'));
221 $mimetype = MediaFile::getUploadedFileType($fh);
225 if (isset($mimetype)) {
227 $filename = File::filename($user->getProfile(), "email", $mimetype);
229 $filepath = File::path($filename);
231 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
234 throw new ClientException(_('File could not be moved to destination directory.' .
235 $stream['uri'] . ' ' . $filepath));
238 throw new ClientException(_('Could not determine file\'s MIME type.'));
242 return new MediaFile($user, $filename, $mimetype);
246 * Attempt to identify the content type of a given file.
248 * @param mixed $f file handle resource, or filesystem path as string
249 * @param string $originalFilename (optional) for extension-based detection
252 * @fixme is this an internal or public method? It's called from GetFileAction
253 * @fixme this seems to tie a front-end error message in, kinda confusing
254 * @fixme this looks like it could return a PEAR_Error in some cases, if
255 * type can't be identified and $config['attachments']['supported'] is true
257 * @throws ClientException if type is known, but not supported for local uploads
259 static function getUploadedFileType($f, $originalFilename=false) {
260 require_once 'MIME/Type.php';
261 require_once 'MIME/Type/Extension.php';
262 $mte = new MIME_Type_Extension();
264 $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
265 $cmd = common_config('attachments', 'filecommand');
269 // If we couldn't get a clear type from the file extension,
270 // we'll go ahead and try checking the content. Content checks
271 // are unambiguous for most image files, but nearly useless
272 // for office document formats.
276 // assuming a filename
278 $filetype = MIME_Type::autoDetect($f);
282 // assuming a filehandle
284 $stream = stream_get_meta_data($f);
285 $filetype = MIME_Type::autoDetect($stream['uri']);
288 // The content-based sources for MIME_Type::autoDetect()
289 // are wildly unreliable for office-type documents. If we've
290 // gotten an unclear reponse back or just couldn't identify it,
291 // we'll try detecting a type from its extension...
292 $unclearTypes = array('application/octet-stream',
293 'application/vnd.ms-office',
296 if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
297 $type = $mte->getMIMEType($originalFilename);
298 if (is_string($type)) {
303 $supported = common_config('attachments', 'supported');
304 if (is_array($supported)) {
305 // Normalize extensions to mime types
306 foreach ($supported as $i => $entry) {
307 if (strpos($entry, '/') === false) {
308 common_log(LOG_INFO, "sample.$entry");
309 $supported[$i] = $mte->getMIMEType("sample.$entry");
313 if ($supported === true || in_array($filetype, $supported)) {
316 $media = MIME_Type::getMedia($filetype);
317 if ('application' !== $media) {
318 $hint = sprintf(_(' Try using another %s format.'), $media);
322 throw new ClientException(sprintf(
323 _('%s is not a supported file type on this server.'), $filetype) . $hint);
326 static function respectsQuota($user, $filesize)
329 $result = $file->isRespectsQuota($user, $filesize);
330 if ($result === true) {
333 throw new ClientException($result);