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 * Get the attachments for a particlar notice.
62 * @return array of File objects
64 static function getAttachments($post_id) {
66 $query = "select file.* from file join file_to_post on (file_id = file.id) where post_id = " . $file->escape($post_id);
67 $file = Memcached_DataObject::cachedQuery('File', $query);
69 while ($file->fetch()) {
70 $att[] = clone($file);
76 * Save a new file record.
78 * @param array $redir_data lookup data eg from File_redirection::where()
79 * @param string $given_url
82 function saveNew(array $redir_data, $given_url) {
85 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
86 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
87 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
88 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
89 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
90 $file_id = $x->insert();
92 $x->saveOembed($redir_data, $given_url);
97 * Save embedding information for this file, if applicable.
99 * Normally this won't need to be called manually, as File::saveNew()
102 * @param array $redir_data lookup data eg from File_redirection::where()
103 * @param string $given_url
104 * @return boolean success
106 public function saveOembed($redir_data, $given_url)
108 if (isset($redir_data['type'])
109 && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
110 && ($oembed_data = File_oembed::_getOembed($given_url))) {
112 $fo = File_oembed::staticGet('file_id', $this->id);
115 File_oembed::saveNew($oembed_data, $this->id);
118 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
125 * Go look at a URL and possibly save data about it if it's new:
126 * - follow redirect chains and store them in file_redirection
127 * - look up oEmbed data and save it in file_oembed
128 * - if a thumbnail is available, save it in file_thumbnail
129 * - save file record with basic info
130 * - optionally save a file_to_post record
131 * - return the File object with the full reference
133 * @fixme refactor this mess, it's gotten pretty scary.
134 * @param string $given_url the URL we're looking at
135 * @param int $notice_id (optional)
136 * @param bool $followRedirects defaults to true
138 * @return mixed File on success, -1 on some errors
140 * @throws ServerException on some errors
142 public function processNew($given_url, $notice_id=null, $followRedirects=true) {
143 if (empty($given_url)) return -1; // error, no url to process
144 $given_url = File_redirection::_canonUrl($given_url);
145 if (empty($given_url)) return -1; // error, no url to process
146 $file = File::staticGet('url', $given_url);
148 $file_redir = File_redirection::staticGet('url', $given_url);
149 if (empty($file_redir)) {
150 // @fixme for new URLs this also looks up non-redirect data
151 // such as target content type, size, etc, which we need
152 // for File::saveNew(); so we call it even if not following
154 $redir_data = File_redirection::where($given_url);
155 if (is_array($redir_data)) {
156 $redir_url = $redir_data['url'];
157 } elseif (is_string($redir_data)) {
158 $redir_url = $redir_data;
159 $redir_data = array();
161 // TRANS: Server exception thrown when a URL cannot be processed.
162 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
164 // TODO: max field length
165 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
166 $x = File::saveNew($redir_data, $given_url);
169 // This seems kind of messed up... for now skipping this part
170 // if we're already under a redirect, so we don't go into
171 // horrible infinite loops if we've been given an unstable
172 // redirect (where the final destination of the first request
173 // doesn't match what we get when we ask for it again).
175 // Seen in the wild with clojure.org, which redirects through
176 // wikispaces for auth and appends session data in the URL params.
177 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
179 File_redirection::saveNew($redir_data, $file_id, $given_url);
182 $file_id = $file_redir->file_id;
185 $file_id = $file->id;
190 $x = File::staticGet($file_id);
192 // @todo FIXME: This could possibly be a clearer message :)
193 // TRANS: Server exception thrown when... Robin thinks something is impossible!
194 throw new ServerException(_('Robin thinks something is impossible.'));
198 if (!empty($notice_id)) {
199 File_to_post::processNew($file_id, $notice_id);
204 function isRespectsQuota($user,$fileSize) {
206 if ($fileSize > common_config('attachments', 'file_quota')) {
207 // TRANS: Message given if an upload is larger than the configured maximum.
208 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
209 // TRANS: %1$s is used for plural.
210 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.',
211 'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
212 common_config('attachments', 'file_quota')),
213 common_config('attachments', 'file_quota'), $fileSize);
216 $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'";
217 $this->query($query);
219 $total = $this->total + $fileSize;
220 if ($total > common_config('attachments', 'user_quota')) {
221 // TRANS: Message given if an upload would exceed user quota.
222 // TRANS: %d (number) is the user quota in bytes and is used for plural.
223 return sprintf(_m('A file this large would exceed your user quota of %d byte.',
224 'A file this large would exceed your user quota of %d bytes.',
225 common_config('attachments', 'user_quota')),
226 common_config('attachments', 'user_quota'));
228 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
229 $this->query($query);
231 $total = $this->total + $fileSize;
232 if ($total > common_config('attachments', 'monthly_quota')) {
233 // TRANS: Message given id an upload would exceed a user's monthly quota.
234 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
235 return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
236 'A file this large would exceed your monthly quota of %d bytes.',
237 common_config('attachments', 'monthly_quota')),
238 common_config('attachments', 'monthly_quota'));
243 // where should the file go?
245 static function filename($profile, $basename, $mimetype)
247 require_once 'MIME/Type/Extension.php';
249 // We have to temporarily disable auto handling of PEAR errors...
250 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
252 $mte = new MIME_Type_Extension();
253 $ext = $mte->getExtension($mimetype);
254 if (PEAR::isError($ext)) {
255 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
258 // Restore error handling.
259 PEAR::staticPopErrorHandling();
261 $nickname = $profile->nickname;
262 $datestamp = strftime('%Y%m%dT%H%M%S', time());
263 $random = strtolower(common_confirmation_code(32));
264 return "$nickname-$datestamp-$random.$ext";
268 * Validation for as-saved base filenames
270 static function validFilename($filename)
272 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
276 * @throws ClientException on invalid filename
278 static function path($filename)
280 if (!self::validFilename($filename)) {
281 // TRANS: Client exception thrown if a file upload does not have a valid name.
282 throw new ClientException(_("Invalid filename."));
284 $dir = common_config('attachments', 'dir');
286 if ($dir[strlen($dir)-1] != '/') {
290 return $dir . $filename;
293 static function url($filename)
295 if (!self::validFilename($filename)) {
296 // TRANS: Client exception thrown if a file upload does not have a valid name.
297 throw new ClientException(_("Invalid filename."));
300 if (common_config('site','private')) {
302 return common_local_url('getfile',
303 array('filename' => $filename));
307 if (StatusNet::isHTTPS()) {
309 $sslserver = common_config('attachments', 'sslserver');
311 if (empty($sslserver)) {
312 // XXX: this assumes that background dir == site dir + /file/
313 // not true if there's another server
314 if (is_string(common_config('site', 'sslserver')) &&
315 mb_strlen(common_config('site', 'sslserver')) > 0) {
316 $server = common_config('site', 'sslserver');
317 } else if (common_config('site', 'server')) {
318 $server = common_config('site', 'server');
320 $path = common_config('site', 'path') . '/file/';
322 $server = $sslserver;
323 $path = common_config('attachments', 'sslpath');
325 $path = common_config('attachments', 'path');
331 $path = common_config('attachments', 'path');
332 $server = common_config('attachments', 'server');
334 if (empty($server)) {
335 $server = common_config('site', 'server');
338 $ssl = common_config('attachments', 'ssl');
340 $protocol = ($ssl) ? 'https' : 'http';
343 if ($path[strlen($path)-1] != '/') {
347 if ($path[0] != '/') {
351 return $protocol.'://'.$server.$path.$filename;
354 function getEnclosure(){
355 $enclosure = (object) array();
356 $enclosure->title=$this->title;
357 $enclosure->url=$this->url;
358 $enclosure->title=$this->title;
359 $enclosure->date=$this->date;
360 $enclosure->modified=$this->modified;
361 $enclosure->size=$this->size;
362 $enclosure->mimetype=$this->mimetype;
364 if(! isset($this->filename)){
365 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
366 $mimetype = $this->mimetype;
367 if($mimetype != null){
368 $mimetype = strtolower($this->mimetype);
370 $semicolon = strpos($mimetype,';');
372 $mimetype = substr($mimetype,0,$semicolon);
374 if(in_array($mimetype,$notEnclosureMimeTypes)){
375 // Never treat generic HTML links as an enclosure type!
376 // But if we have oEmbed info, we'll consider it golden.
377 $oembed = File_oembed::staticGet('file_id',$this->id);
378 if($oembed && in_array($oembed->type, array('photo', 'video'))){
379 $mimetype = strtolower($oembed->mimetype);
380 $semicolon = strpos($mimetype,';');
382 $mimetype = substr($mimetype,0,$semicolon);
384 // @fixme uncertain if this is right.
385 // we want to expose things like YouTube videos as
386 // viewable attachments, but don't expose them as
387 // downloadable enclosures.....?
388 //if (in_array($mimetype, $notEnclosureMimeTypes)) {
391 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
392 if($oembed->url) $enclosure->url=$oembed->url;
393 if($oembed->title) $enclosure->title=$oembed->title;
394 if($oembed->modified) $enclosure->modified=$oembed->modified;
395 unset($oembed->size);
405 // quick back-compat hack, since there's still code using this
406 function isEnclosure()
408 $enclosure = $this->getEnclosure();
409 return !empty($enclosure);
413 * Get the attachment's thumbnail record, if any.
415 * @return File_thumbnail
417 function getThumbnail()
419 return File_thumbnail::staticGet('file_id', $this->id);
423 * Blow the cache of notices that link to this URL
425 * @param boolean $last Whether to blow the "last" cache too
430 function blowCache($last=false)
432 self::blow('file:notice-ids:%s', $this->url);
434 self::blow('file:notice-ids:%s;last', $this->url);
436 self::blow('file:notice-count:%d', $this->id);
440 * Stream of notices linking to this URL
442 * @param integer $offset Offset to show; default is 0
443 * @param integer $limit Limit of notices to show
444 * @param integer $since_id Since this notice
445 * @param integer $max_id Before this notice
447 * @return array ids of notices that link to this file
450 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
452 $stream = new FileNoticeStream($this);
453 return $stream->getNotices($offset, $limit, $since_id, $max_id);
456 function noticeCount()
458 $cacheKey = sprintf('file:notice-count:%d', $this->id);
460 $count = self::cacheGet($cacheKey);
462 if ($count === false) {
464 $f2p = new File_to_post();
466 $f2p->file_id = $this->id;
468 $count = $f2p->count();
470 self::cacheSet($cacheKey, $count);