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
32 class File extends Memcached_DataObject
35 /* the code below is auto generated do not remove the above tag */
37 public $__table = 'file'; // table name
38 public $id; // int(4) primary_key not_null
39 public $url; // varchar(255) unique_key
40 public $mimetype; // varchar(50)
41 public $size; // int(4)
42 public $title; // varchar(255)
43 public $date; // int(4)
44 public $protected; // int(4)
45 public $filename; // varchar(255)
46 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
49 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File',$k,$v); }
51 /* the code above is auto generated do not remove the tag below */
54 function isProtected($url) {
55 return 'http://www.facebook.com/login.php' === $url;
58 function getAttachments($post_id) {
59 $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);
62 while ($this->fetch()) {
63 $att[] = clone($this);
70 * Save a new file record.
72 * @param array $redir_data lookup data eg from File_redirection::where()
73 * @param string $given_url
76 function saveNew(array $redir_data, $given_url) {
79 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
80 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
81 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
82 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
83 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
84 $file_id = $x->insert();
86 $x->saveOembed($redir_data, $given_url);
91 * Save embedding information for this file, if applicable.
93 * Normally this won't need to be called manually, as File::saveNew()
96 * @param array $redir_data lookup data eg from File_redirection::where()
97 * @param string $given_url
98 * @return boolean success
100 public function saveOembed($redir_data, $given_url)
102 if (isset($redir_data['type'])
103 && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
104 && ($oembed_data = File_oembed::_getOembed($given_url))) {
106 $fo = File_oembed::staticGet('file_id', $this->id);
109 File_oembed::saveNew($oembed_data, $this->id);
112 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
119 * @fixme refactor this mess, it's gotten pretty scary.
120 * @param bool $followRedirects
122 function processNew($given_url, $notice_id=null, $followRedirects=true) {
123 if (empty($given_url)) return -1; // error, no url to process
124 $given_url = File_redirection::_canonUrl($given_url);
125 if (empty($given_url)) return -1; // error, no url to process
126 $file = File::staticGet('url', $given_url);
128 $file_redir = File_redirection::staticGet('url', $given_url);
129 if (empty($file_redir)) {
130 // @fixme for new URLs this also looks up non-redirect data
131 // such as target content type, size, etc, which we need
132 // for File::saveNew(); so we call it even if not following
134 $redir_data = File_redirection::where($given_url);
135 if (is_array($redir_data)) {
136 $redir_url = $redir_data['url'];
137 } elseif (is_string($redir_data)) {
138 $redir_url = $redir_data;
139 $redir_data = array();
141 // TRANS: Server exception thrown when a URL cannot be processed.
142 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
144 // TODO: max field length
145 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
146 $x = File::saveNew($redir_data, $given_url);
149 // This seems kind of messed up... for now skipping this part
150 // if we're already under a redirect, so we don't go into
151 // horrible infinite loops if we've been given an unstable
152 // redirect (where the final destination of the first request
153 // doesn't match what we get when we ask for it again).
155 // Seen in the wild with clojure.org, which redirects through
156 // wikispaces for auth and appends session data in the URL params.
157 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
159 File_redirection::saveNew($redir_data, $file_id, $given_url);
162 $file_id = $file_redir->file_id;
165 $file_id = $file->id;
170 $x = File::staticGet($file_id);
172 // @todo FIXME: This could possibly be a clearer message :)
173 // TRANS: Server exception thrown when... Robin thinks something is impossible!
174 throw new ServerException(_('Robin thinks something is impossible.'));
178 if (!empty($notice_id)) {
179 File_to_post::processNew($file_id, $notice_id);
184 function isRespectsQuota($user,$fileSize) {
186 if ($fileSize > common_config('attachments', 'file_quota')) {
187 // TRANS: Message given if an upload is larger than the configured maximum.
188 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
189 // TRANS: %1$s is used for plural.
190 return sprintf(_m('No file may be larger than %1$d byte and the file you sent was %2$d bytes. Try to upload a smaller version.',
191 'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
192 common_config('attachments', 'file_quota')),
193 common_config('attachments', 'file_quota'), $fileSize);
196 $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'";
197 $this->query($query);
199 $total = $this->total + $fileSize;
200 if ($total > common_config('attachments', 'user_quota')) {
201 // TRANS: Message given if an upload would exceed user quota.
202 // TRANS: %d (number) is the user quota in bytes and is used for plural.
203 return sprintf(_m('A file this large would exceed your user quota of %d byte.',
204 'A file this large would exceed your user quota of %d bytes.',
205 common_config('attachments', 'user_quota')),
206 common_config('attachments', 'user_quota'));
208 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
209 $this->query($query);
211 $total = $this->total + $fileSize;
212 if ($total > common_config('attachments', 'monthly_quota')) {
213 // TRANS: Message given id an upload would exceed a user's monthly quota.
214 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
215 return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
216 'A file this large would exceed your monthly quota of %d bytes.',
217 common_config('attachments', 'monthly_quota')),
218 common_config('attachments', 'monthly_quota'));
223 // where should the file go?
225 static function filename($profile, $basename, $mimetype)
227 require_once 'MIME/Type/Extension.php';
229 // We have to temporarily disable auto handling of PEAR errors...
230 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
232 $mte = new MIME_Type_Extension();
233 $ext = $mte->getExtension($mimetype);
234 if (PEAR::isError($ext)) {
235 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
238 // Restore error handling.
239 PEAR::staticPopErrorHandling();
241 $nickname = $profile->nickname;
242 $datestamp = strftime('%Y%m%dT%H%M%S', time());
243 $random = strtolower(common_confirmation_code(32));
244 return "$nickname-$datestamp-$random.$ext";
248 * Validation for as-saved base filenames
250 static function validFilename($filename)
252 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
256 * @throws ClientException on invalid filename
258 static function path($filename)
260 if (!self::validFilename($filename)) {
261 // TRANS: Client exception thrown if a file upload does not have a valid name.
262 throw new ClientException(_("Invalid filename."));
264 $dir = common_config('attachments', 'dir');
266 if ($dir[strlen($dir)-1] != '/') {
270 return $dir . $filename;
273 static function url($filename)
275 if (!self::validFilename($filename)) {
276 // TRANS: Client exception thrown if a file upload does not have a valid name.
277 throw new ClientException(_("Invalid filename."));
280 if (common_config('site','private')) {
282 return common_local_url('getfile',
283 array('filename' => $filename));
287 if (StatusNet::isHTTPS()) {
289 $sslserver = common_config('attachments', 'sslserver');
291 if (empty($sslserver)) {
292 // XXX: this assumes that background dir == site dir + /file/
293 // not true if there's another server
294 if (is_string(common_config('site', 'sslserver')) &&
295 mb_strlen(common_config('site', 'sslserver')) > 0) {
296 $server = common_config('site', 'sslserver');
297 } else if (common_config('site', 'server')) {
298 $server = common_config('site', 'server');
300 $path = common_config('site', 'path') . '/file/';
302 $server = $sslserver;
303 $path = common_config('attachments', 'sslpath');
305 $path = common_config('attachments', 'path');
311 $path = common_config('attachments', 'path');
312 $server = common_config('attachments', 'server');
314 if (empty($server)) {
315 $server = common_config('site', 'server');
318 $ssl = common_config('attachments', 'ssl');
320 $protocol = ($ssl) ? 'https' : 'http';
323 if ($path[strlen($path)-1] != '/') {
327 if ($path[0] != '/') {
331 return $protocol.'://'.$server.$path.$filename;
334 function getEnclosure(){
335 $enclosure = (object) array();
336 $enclosure->title=$this->title;
337 $enclosure->url=$this->url;
338 $enclosure->title=$this->title;
339 $enclosure->date=$this->date;
340 $enclosure->modified=$this->modified;
341 $enclosure->size=$this->size;
342 $enclosure->mimetype=$this->mimetype;
344 if(! isset($this->filename)){
345 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
346 $mimetype = $this->mimetype;
347 if($mimetype != null){
348 $mimetype = strtolower($this->mimetype);
350 $semicolon = strpos($mimetype,';');
352 $mimetype = substr($mimetype,0,$semicolon);
354 if(in_array($mimetype,$notEnclosureMimeTypes)){
355 $oembed = File_oembed::staticGet('file_id',$this->id);
357 $mimetype = strtolower($oembed->mimetype);
358 $semicolon = strpos($mimetype,';');
360 $mimetype = substr($mimetype,0,$semicolon);
362 if(in_array($mimetype,$notEnclosureMimeTypes)){
365 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
366 if($oembed->url) $enclosure->url=$oembed->url;
367 if($oembed->title) $enclosure->title=$oembed->title;
368 if($oembed->modified) $enclosure->modified=$oembed->modified;
369 unset($oembed->size);
379 // quick back-compat hack, since there's still code using this
380 function isEnclosure()
382 $enclosure = $this->getEnclosure();
383 return !empty($enclosure);