3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
22 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
23 require_once INSTALLDIR.'/classes/File_redirection.php';
24 require_once INSTALLDIR.'/classes/File_oembed.php';
25 require_once INSTALLDIR.'/classes/File_thumbnail.php';
26 require_once INSTALLDIR.'/classes/File_to_post.php';
27 //require_once INSTALLDIR.'/classes/File_redirection.php';
30 * Table Definition for file
33 class File extends Memcached_DataObject
36 /* the code below is auto generated do not remove the above tag */
38 public $__table = 'file'; // table name
39 public $id; // int(4) primary_key not_null
40 public $url; // varchar(255) unique_key
41 public $mimetype; // varchar(50)
42 public $size; // int(4)
43 public $title; // varchar(255)
44 public $date; // int(4)
45 public $protected; // int(4)
46 public $filename; // varchar(255)
47 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
50 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File',$k,$v); }
52 /* the code above is auto generated do not remove the tag below */
55 function isProtected($url) {
56 return 'http://www.facebook.com/login.php' === $url;
59 function getAttachments($post_id) {
60 $query = "select file.* from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $this->escape($post_id);
63 while ($this->fetch()) {
64 $att[] = clone($this);
71 * Save a new file record.
73 * @param array $redir_data lookup data eg from File_redirection::where()
74 * @param string $given_url
77 function saveNew(array $redir_data, $given_url) {
80 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
81 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
82 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
83 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
84 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
85 $file_id = $x->insert();
87 $x->saveOembed($redir_data, $given_url);
92 * Save embedding information for this file, if applicable.
94 * Normally this won't need to be called manually, as File::saveNew()
97 * @param array $redir_data lookup data eg from File_redirection::where()
98 * @param string $given_url
99 * @return boolean success
101 public function saveOembed($redir_data, $given_url)
103 if (isset($redir_data['type'])
104 && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
105 && ($oembed_data = File_oembed::_getOembed($given_url))) {
107 $fo = File_oembed::staticGet('file_id', $this->id);
110 File_oembed::saveNew($oembed_data, $this->id);
113 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
120 * @fixme refactor this mess, it's gotten pretty scary.
121 * @param bool $followRedirects
123 function processNew($given_url, $notice_id=null, $followRedirects=true) {
124 if (empty($given_url)) return -1; // error, no url to process
125 $given_url = File_redirection::_canonUrl($given_url);
126 if (empty($given_url)) return -1; // error, no url to process
127 $file = File::staticGet('url', $given_url);
129 $file_redir = File_redirection::staticGet('url', $given_url);
130 if (empty($file_redir)) {
131 // @fixme for new URLs this also looks up non-redirect data
132 // such as target content type, size, etc, which we need
133 // for File::saveNew(); so we call it even if not following
135 $redir_data = File_redirection::where($given_url);
136 if (is_array($redir_data)) {
137 $redir_url = $redir_data['url'];
138 } elseif (is_string($redir_data)) {
139 $redir_url = $redir_data;
140 $redir_data = array();
142 // TRANS: Server exception thrown when a URL cannot be processed.
143 throw new ServerException(_("Cannot process URL '$given_url'"));
145 // TODO: max field length
146 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
147 $x = File::saveNew($redir_data, $given_url);
150 // This seems kind of messed up... for now skipping this part
151 // if we're already under a redirect, so we don't go into
152 // horrible infinite loops if we've been given an unstable
153 // redirect (where the final destination of the first request
154 // doesn't match what we get when we ask for it again).
156 // Seen in the wild with clojure.org, which redirects through
157 // wikispaces for auth and appends session data in the URL params.
158 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
160 File_redirection::saveNew($redir_data, $file_id, $given_url);
163 $file_id = $file_redir->file_id;
166 $file_id = $file->id;
171 $x = File::staticGet($file_id);
173 // FIXME: This could possibly be a clearer message :)
174 // TRANS: Server exception thrown when... Robin thinks something is impossible!
175 throw new ServerException(_("Robin thinks something is impossible."));
179 if (!empty($notice_id)) {
180 File_to_post::processNew($file_id, $notice_id);
185 function isRespectsQuota($user,$fileSize) {
187 if ($fileSize > common_config('attachments', 'file_quota')) {
188 // TRANS: Message given if an upload is larger than the configured maximum.
189 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
190 return sprintf(_('No file may be larger than %1$d bytes ' .
191 'and the file you sent was %2$d bytes. Try to upload a smaller version.'),
192 common_config('attachments', 'file_quota'), $fileSize);
195 $query = "select sum(size) as total from file join file_to_post on file_to_post.file_id = file.id join notice on file_to_post.post_id = notice.id where profile_id = {$user->id} and file.url like '%/notice/%/file'";
196 $this->query($query);
198 $total = $this->total + $fileSize;
199 if ($total > common_config('attachments', 'user_quota')) {
200 // TRANS: Message given if an upload would exceed user quota.
201 // TRANS: %d (number) is the user quota in bytes.
202 return sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota'));
204 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
205 $this->query($query);
207 $total = $this->total + $fileSize;
208 if ($total > common_config('attachments', 'monthly_quota')) {
209 // TRANS: Message given id an upload would exceed a user's monthly quota.
210 // TRANS: $d (number) is the monthly user quota in bytes.
211 return sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota'));
216 // where should the file go?
218 static function filename($profile, $basename, $mimetype)
220 require_once 'MIME/Type/Extension.php';
221 $mte = new MIME_Type_Extension();
223 $ext = $mte->getExtension($mimetype);
224 } catch ( Exception $e) {
225 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
227 $nickname = $profile->nickname;
228 $datestamp = strftime('%Y%m%dT%H%M%S', time());
229 $random = strtolower(common_confirmation_code(32));
230 return "$nickname-$datestamp-$random.$ext";
234 * Validation for as-saved base filenames
236 static function validFilename($filename)
238 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
242 * @throws ClientException on invalid filename
244 static function path($filename)
246 if (!self::validFilename($filename)) {
247 // TRANS: Client exception thrown if a file upload does not have a valid name.
248 throw new ClientException(_("Invalid filename."));
250 $dir = common_config('attachments', 'dir');
252 if ($dir[strlen($dir)-1] != '/') {
256 return $dir . $filename;
259 static function url($filename)
261 if (!self::validFilename($filename)) {
262 // TRANS: Client exception thrown if a file upload does not have a valid name.
263 throw new ClientException(_("Invalid filename."));
265 if(common_config('site','private')) {
267 return common_local_url('getfile',
268 array('filename' => $filename));
271 $path = common_config('attachments', 'path');
273 if ($path[strlen($path)-1] != '/') {
277 if ($path[0] != '/') {
281 $server = common_config('attachments', 'server');
283 if (empty($server)) {
284 $server = common_config('site', 'server');
287 $ssl = common_config('attachments', 'ssl');
289 if (is_null($ssl)) { // null -> guess
290 if (common_config('site', 'ssl') == 'always' &&
291 !common_config('attachments', 'server')) {
298 $protocol = ($ssl) ? 'https' : 'http';
300 return $protocol.'://'.$server.$path.$filename;
304 function getEnclosure(){
305 $enclosure = (object) array();
306 $enclosure->title=$this->title;
307 $enclosure->url=$this->url;
308 $enclosure->title=$this->title;
309 $enclosure->date=$this->date;
310 $enclosure->modified=$this->modified;
311 $enclosure->size=$this->size;
312 $enclosure->mimetype=$this->mimetype;
314 if(! isset($this->filename)){
315 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
316 $mimetype = $this->mimetype;
317 if($mimetype != null){
318 $mimetype = strtolower($this->mimetype);
320 $semicolon = strpos($mimetype,';');
322 $mimetype = substr($mimetype,0,$semicolon);
324 if(in_array($mimetype,$notEnclosureMimeTypes)){
325 $oembed = File_oembed::staticGet('file_id',$this->id);
327 $mimetype = strtolower($oembed->mimetype);
328 $semicolon = strpos($mimetype,';');
330 $mimetype = substr($mimetype,0,$semicolon);
332 if(in_array($mimetype,$notEnclosureMimeTypes)){
335 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
336 if($oembed->url) $enclosure->url=$oembed->url;
337 if($oembed->title) $enclosure->title=$oembed->title;
338 if($oembed->modified) $enclosure->modified=$oembed->modified;
339 unset($oembed->size);
349 // quick back-compat hack, since there's still code using this
350 function isEnclosure()
352 $enclosure = $this->getEnclosure();
353 return !empty($enclosure);