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;
59 * Save a new file record.
61 * @param array $redir_data lookup data eg from File_redirection::where()
62 * @param string $given_url
65 function saveNew(array $redir_data, $given_url) {
68 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
69 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
70 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
71 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
72 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
73 $file_id = $x->insert();
75 $x->saveOembed($redir_data, $given_url);
80 * Save embedding information for this file, if applicable.
82 * Normally this won't need to be called manually, as File::saveNew()
85 * @param array $redir_data lookup data eg from File_redirection::where()
86 * @param string $given_url
87 * @return boolean success
89 public function saveOembed($redir_data, $given_url)
91 if (isset($redir_data['type'])
92 && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
93 && ($oembed_data = File_oembed::_getOembed($given_url))) {
95 $fo = File_oembed::staticGet('file_id', $this->id);
98 File_oembed::saveNew($oembed_data, $this->id);
101 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
108 * Go look at a URL and possibly save data about it if it's new:
109 * - follow redirect chains and store them in file_redirection
110 * - look up oEmbed data and save it in file_oembed
111 * - if a thumbnail is available, save it in file_thumbnail
112 * - save file record with basic info
113 * - optionally save a file_to_post record
114 * - return the File object with the full reference
116 * @fixme refactor this mess, it's gotten pretty scary.
117 * @param string $given_url the URL we're looking at
118 * @param int $notice_id (optional)
119 * @param bool $followRedirects defaults to true
121 * @return mixed File on success, -1 on some errors
123 * @throws ServerException on some errors
125 public function processNew($given_url, $notice_id=null, $followRedirects=true) {
126 if (empty($given_url)) return -1; // error, no url to process
127 $given_url = File_redirection::_canonUrl($given_url);
128 if (empty($given_url)) return -1; // error, no url to process
129 $file = File::staticGet('url', $given_url);
131 $file_redir = File_redirection::staticGet('url', $given_url);
132 if (empty($file_redir)) {
133 // @fixme for new URLs this also looks up non-redirect data
134 // such as target content type, size, etc, which we need
135 // for File::saveNew(); so we call it even if not following
137 $redir_data = File_redirection::where($given_url);
138 if (is_array($redir_data)) {
139 $redir_url = $redir_data['url'];
140 } elseif (is_string($redir_data)) {
141 $redir_url = $redir_data;
142 $redir_data = array();
144 // TRANS: Server exception thrown when a URL cannot be processed.
145 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
147 // TODO: max field length
148 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
149 $x = File::saveNew($redir_data, $given_url);
152 // This seems kind of messed up... for now skipping this part
153 // if we're already under a redirect, so we don't go into
154 // horrible infinite loops if we've been given an unstable
155 // redirect (where the final destination of the first request
156 // doesn't match what we get when we ask for it again).
158 // Seen in the wild with clojure.org, which redirects through
159 // wikispaces for auth and appends session data in the URL params.
160 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
162 File_redirection::saveNew($redir_data, $file_id, $given_url);
165 $file_id = $file_redir->file_id;
168 $file_id = $file->id;
173 $x = File::staticGet($file_id);
175 // @todo FIXME: This could possibly be a clearer message :)
176 // TRANS: Server exception thrown when... Robin thinks something is impossible!
177 throw new ServerException(_('Robin thinks something is impossible.'));
181 if (!empty($notice_id)) {
182 File_to_post::processNew($file_id, $notice_id);
187 function isRespectsQuota($user,$fileSize) {
189 if ($fileSize > common_config('attachments', 'file_quota')) {
190 // TRANS: Message given if an upload is larger than the configured maximum.
191 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
192 // TRANS: %1$s is used for plural.
193 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.',
194 'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
195 common_config('attachments', 'file_quota')),
196 common_config('attachments', 'file_quota'), $fileSize);
199 $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'";
200 $this->query($query);
202 $total = $this->total + $fileSize;
203 if ($total > common_config('attachments', 'user_quota')) {
204 // TRANS: Message given if an upload would exceed user quota.
205 // TRANS: %d (number) is the user quota in bytes and is used for plural.
206 return sprintf(_m('A file this large would exceed your user quota of %d byte.',
207 'A file this large would exceed your user quota of %d bytes.',
208 common_config('attachments', 'user_quota')),
209 common_config('attachments', 'user_quota'));
211 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
212 $this->query($query);
214 $total = $this->total + $fileSize;
215 if ($total > common_config('attachments', 'monthly_quota')) {
216 // TRANS: Message given id an upload would exceed a user's monthly quota.
217 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
218 return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
219 'A file this large would exceed your monthly quota of %d bytes.',
220 common_config('attachments', 'monthly_quota')),
221 common_config('attachments', 'monthly_quota'));
226 // where should the file go?
228 static function filename($profile, $basename, $mimetype)
230 require_once 'MIME/Type/Extension.php';
232 // We have to temporarily disable auto handling of PEAR errors...
233 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
235 $mte = new MIME_Type_Extension();
236 $ext = $mte->getExtension($mimetype);
237 if (PEAR::isError($ext)) {
238 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
241 // Restore error handling.
242 PEAR::staticPopErrorHandling();
244 $nickname = $profile->nickname;
245 $datestamp = strftime('%Y%m%dT%H%M%S', time());
246 $random = strtolower(common_confirmation_code(32));
247 return "$nickname-$datestamp-$random.$ext";
251 * Validation for as-saved base filenames
253 static function validFilename($filename)
255 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
259 * @throws ClientException on invalid filename
261 static function path($filename)
263 if (!self::validFilename($filename)) {
264 // TRANS: Client exception thrown if a file upload does not have a valid name.
265 throw new ClientException(_("Invalid filename."));
267 $dir = common_config('attachments', 'dir');
269 if ($dir[strlen($dir)-1] != '/') {
273 return $dir . $filename;
276 static function url($filename)
278 if (!self::validFilename($filename)) {
279 // TRANS: Client exception thrown if a file upload does not have a valid name.
280 throw new ClientException(_("Invalid filename."));
283 if (common_config('site','private')) {
285 return common_local_url('getfile',
286 array('filename' => $filename));
290 if (StatusNet::isHTTPS()) {
292 $sslserver = common_config('attachments', 'sslserver');
294 if (empty($sslserver)) {
295 // XXX: this assumes that background dir == site dir + /file/
296 // not true if there's another server
297 if (is_string(common_config('site', 'sslserver')) &&
298 mb_strlen(common_config('site', 'sslserver')) > 0) {
299 $server = common_config('site', 'sslserver');
300 } else if (common_config('site', 'server')) {
301 $server = common_config('site', 'server');
303 $path = common_config('site', 'path') . '/file/';
305 $server = $sslserver;
306 $path = common_config('attachments', 'sslpath');
308 $path = common_config('attachments', 'path');
314 $path = common_config('attachments', 'path');
315 $server = common_config('attachments', 'server');
317 if (empty($server)) {
318 $server = common_config('site', 'server');
321 $ssl = common_config('attachments', 'ssl');
323 $protocol = ($ssl) ? 'https' : 'http';
326 if ($path[strlen($path)-1] != '/') {
330 if ($path[0] != '/') {
334 return $protocol.'://'.$server.$path.$filename;
337 function getEnclosure(){
338 $enclosure = (object) array();
339 $enclosure->title=$this->title;
340 $enclosure->url=$this->url;
341 $enclosure->title=$this->title;
342 $enclosure->date=$this->date;
343 $enclosure->modified=$this->modified;
344 $enclosure->size=$this->size;
345 $enclosure->mimetype=$this->mimetype;
347 if(! isset($this->filename)){
348 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
349 $mimetype = $this->mimetype;
350 if($mimetype != null){
351 $mimetype = strtolower($this->mimetype);
353 $semicolon = strpos($mimetype,';');
355 $mimetype = substr($mimetype,0,$semicolon);
357 if(in_array($mimetype,$notEnclosureMimeTypes)){
358 // Never treat generic HTML links as an enclosure type!
359 // But if we have oEmbed info, we'll consider it golden.
360 $oembed = File_oembed::staticGet('file_id',$this->id);
361 if($oembed && in_array($oembed->type, array('photo', 'video'))){
362 $mimetype = strtolower($oembed->mimetype);
363 $semicolon = strpos($mimetype,';');
365 $mimetype = substr($mimetype,0,$semicolon);
367 // @fixme uncertain if this is right.
368 // we want to expose things like YouTube videos as
369 // viewable attachments, but don't expose them as
370 // downloadable enclosures.....?
371 //if (in_array($mimetype, $notEnclosureMimeTypes)) {
374 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
375 if($oembed->url) $enclosure->url=$oembed->url;
376 if($oembed->title) $enclosure->title=$oembed->title;
377 if($oembed->modified) $enclosure->modified=$oembed->modified;
378 unset($oembed->size);
388 // quick back-compat hack, since there's still code using this
389 function isEnclosure()
391 $enclosure = $this->getEnclosure();
392 return !empty($enclosure);
396 * Get the attachment's thumbnail record, if any.
398 * @return File_thumbnail
400 function getThumbnail()
402 return File_thumbnail::staticGet('file_id', $this->id);
406 * Blow the cache of notices that link to this URL
408 * @param boolean $last Whether to blow the "last" cache too
413 function blowCache($last=false)
415 self::blow('file:notice-ids:%s', $this->url);
417 self::blow('file:notice-ids:%s;last', $this->url);
419 self::blow('file:notice-count:%d', $this->id);
423 * Stream of notices linking to this URL
425 * @param integer $offset Offset to show; default is 0
426 * @param integer $limit Limit of notices to show
427 * @param integer $since_id Since this notice
428 * @param integer $max_id Before this notice
430 * @return array ids of notices that link to this file
433 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
435 $stream = new FileNoticeStream($this);
436 return $stream->getNotices($offset, $limit, $since_id, $max_id);
439 function noticeCount()
441 $cacheKey = sprintf('file:notice-count:%d', $this->id);
443 $count = self::cacheGet($cacheKey);
445 if ($count === false) {
447 $f2p = new File_to_post();
449 $f2p->file_id = $this->id;
451 $count = $f2p->count();
453 self::cacheSet($cacheKey, $count);