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 Managed_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 public static function schemaDef()
58 'id' => array('type' => 'serial', 'not null' => true),
59 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'destination URL after following redirections'),
60 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
61 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
62 'title' => array('type' => 'varchar', 'length' => 255, 'description' => 'title of resource when available'),
63 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
64 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
65 'filename' => array('type' => 'varchar', 'length' => 255, 'description' => 'if a local file, name of the file'),
67 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
69 'primary key' => array('id'),
70 'unique keys' => array(
71 'file_url_key' => array('url'),
76 function isProtected($url) {
77 return 'http://www.facebook.com/login.php' === $url;
81 * Save a new file record.
83 * @param array $redir_data lookup data eg from File_redirection::where()
84 * @param string $given_url
87 function saveNew(array $redir_data, $given_url) {
89 // I don't know why we have to keep doing this but I'm adding this last check to avoid
92 $x = File::staticGet('url', $given_url);
97 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
98 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
99 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
100 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
101 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
102 $file_id = $x->insert();
105 $x->saveOembed($redir_data, $given_url);
110 * Save embedding information for this file, if applicable.
112 * Normally this won't need to be called manually, as File::saveNew()
115 * @param array $redir_data lookup data eg from File_redirection::where()
116 * @param string $given_url
117 * @return boolean success
119 public function saveOembed($redir_data, $given_url)
121 if (isset($redir_data['type'])
122 && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
123 && ($oembed_data = File_oembed::_getOembed($given_url))) {
125 $fo = File_oembed::staticGet('file_id', $this->id);
128 File_oembed::saveNew($oembed_data, $this->id);
131 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
138 * Go look at a URL and possibly save data about it if it's new:
139 * - follow redirect chains and store them in file_redirection
140 * - look up oEmbed data and save it in file_oembed
141 * - if a thumbnail is available, save it in file_thumbnail
142 * - save file record with basic info
143 * - optionally save a file_to_post record
144 * - return the File object with the full reference
146 * @fixme refactor this mess, it's gotten pretty scary.
147 * @param string $given_url the URL we're looking at
148 * @param int $notice_id (optional)
149 * @param bool $followRedirects defaults to true
151 * @return mixed File on success, -1 on some errors
153 * @throws ServerException on some errors
155 public function processNew($given_url, $notice_id=null, $followRedirects=true) {
156 if (empty($given_url)) return -1; // error, no url to process
157 $given_url = File_redirection::_canonUrl($given_url);
158 if (empty($given_url)) return -1; // error, no url to process
159 $file = File::staticGet('url', $given_url);
161 $file_redir = File_redirection::staticGet('url', $given_url);
162 if (empty($file_redir)) {
163 // @fixme for new URLs this also looks up non-redirect data
164 // such as target content type, size, etc, which we need
165 // for File::saveNew(); so we call it even if not following
167 $redir_data = File_redirection::where($given_url);
168 if (is_array($redir_data)) {
169 $redir_url = $redir_data['url'];
170 } elseif (is_string($redir_data)) {
171 $redir_url = $redir_data;
172 $redir_data = array();
174 // TRANS: Server exception thrown when a URL cannot be processed.
175 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
177 // TODO: max field length
178 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
179 $x = File::saveNew($redir_data, $given_url);
182 // This seems kind of messed up... for now skipping this part
183 // if we're already under a redirect, so we don't go into
184 // horrible infinite loops if we've been given an unstable
185 // redirect (where the final destination of the first request
186 // doesn't match what we get when we ask for it again).
188 // Seen in the wild with clojure.org, which redirects through
189 // wikispaces for auth and appends session data in the URL params.
190 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
192 File_redirection::saveNew($redir_data, $file_id, $given_url);
195 $file_id = $file_redir->file_id;
198 $file_id = $file->id;
203 $x = File::staticGet('id', $file_id);
205 // @todo FIXME: This could possibly be a clearer message :)
206 // TRANS: Server exception thrown when... Robin thinks something is impossible!
207 throw new ServerException(_('Robin thinks something is impossible.'));
211 if (!empty($notice_id)) {
212 File_to_post::processNew($file_id, $notice_id);
217 function isRespectsQuota($user,$fileSize) {
219 if ($fileSize > common_config('attachments', 'file_quota')) {
220 // TRANS: Message given if an upload is larger than the configured maximum.
221 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
222 // TRANS: %1$s is used for plural.
223 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.',
224 'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
225 common_config('attachments', 'file_quota')),
226 common_config('attachments', 'file_quota'), $fileSize);
229 $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'";
230 $this->query($query);
232 $total = $this->total + $fileSize;
233 if ($total > common_config('attachments', 'user_quota')) {
234 // TRANS: Message given if an upload would exceed user quota.
235 // TRANS: %d (number) is the user quota in bytes and is used for plural.
236 return sprintf(_m('A file this large would exceed your user quota of %d byte.',
237 'A file this large would exceed your user quota of %d bytes.',
238 common_config('attachments', 'user_quota')),
239 common_config('attachments', 'user_quota'));
241 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
242 $this->query($query);
244 $total = $this->total + $fileSize;
245 if ($total > common_config('attachments', 'monthly_quota')) {
246 // TRANS: Message given id an upload would exceed a user's monthly quota.
247 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
248 return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
249 'A file this large would exceed your monthly quota of %d bytes.',
250 common_config('attachments', 'monthly_quota')),
251 common_config('attachments', 'monthly_quota'));
256 // where should the file go?
258 static function filename($profile, $basename, $mimetype)
260 require_once 'MIME/Type/Extension.php';
262 // We have to temporarily disable auto handling of PEAR errors...
263 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
265 $mte = new MIME_Type_Extension();
266 $ext = $mte->getExtension($mimetype);
267 if (PEAR::isError($ext)) {
268 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
271 // Restore error handling.
272 PEAR::staticPopErrorHandling();
274 $nickname = $profile->nickname;
275 $datestamp = strftime('%Y%m%dT%H%M%S', time());
276 $random = strtolower(common_confirmation_code(32));
277 return "$nickname-$datestamp-$random.$ext";
281 * Validation for as-saved base filenames
283 static function validFilename($filename)
285 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
289 * @throws ClientException on invalid filename
291 static function path($filename)
293 if (!self::validFilename($filename)) {
294 // TRANS: Client exception thrown if a file upload does not have a valid name.
295 throw new ClientException(_("Invalid filename."));
297 $dir = common_config('attachments', 'dir');
299 if ($dir[strlen($dir)-1] != '/') {
303 return $dir . $filename;
306 static function url($filename)
308 if (!self::validFilename($filename)) {
309 // TRANS: Client exception thrown if a file upload does not have a valid name.
310 throw new ClientException(_("Invalid filename."));
313 if (common_config('site','private')) {
315 return common_local_url('getfile',
316 array('filename' => $filename));
320 if (StatusNet::isHTTPS()) {
322 $sslserver = common_config('attachments', 'sslserver');
324 if (empty($sslserver)) {
325 // XXX: this assumes that background dir == site dir + /file/
326 // not true if there's another server
327 if (is_string(common_config('site', 'sslserver')) &&
328 mb_strlen(common_config('site', 'sslserver')) > 0) {
329 $server = common_config('site', 'sslserver');
330 } else if (common_config('site', 'server')) {
331 $server = common_config('site', 'server');
333 $path = common_config('site', 'path') . '/file/';
335 $server = $sslserver;
336 $path = common_config('attachments', 'sslpath');
338 $path = common_config('attachments', 'path');
344 $path = common_config('attachments', 'path');
345 $server = common_config('attachments', 'server');
347 if (empty($server)) {
348 $server = common_config('site', 'server');
351 $ssl = common_config('attachments', 'ssl');
353 $protocol = ($ssl) ? 'https' : 'http';
356 if ($path[strlen($path)-1] != '/') {
360 if ($path[0] != '/') {
364 return $protocol.'://'.$server.$path.$filename;
367 function getEnclosure(){
368 $enclosure = (object) array();
369 $enclosure->title=$this->title;
370 $enclosure->url=$this->url;
371 $enclosure->title=$this->title;
372 $enclosure->date=$this->date;
373 $enclosure->modified=$this->modified;
374 $enclosure->size=$this->size;
375 $enclosure->mimetype=$this->mimetype;
377 if(! isset($this->filename)){
378 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
379 $mimetype = $this->mimetype;
380 if($mimetype != null){
381 $mimetype = strtolower($this->mimetype);
383 $semicolon = strpos($mimetype,';');
385 $mimetype = substr($mimetype,0,$semicolon);
387 if(in_array($mimetype,$notEnclosureMimeTypes)){
388 // Never treat generic HTML links as an enclosure type!
389 // But if we have oEmbed info, we'll consider it golden.
390 $oembed = File_oembed::staticGet('file_id',$this->id);
391 if($oembed && in_array($oembed->type, array('photo', 'video'))){
392 $mimetype = strtolower($oembed->mimetype);
393 $semicolon = strpos($mimetype,';');
395 $mimetype = substr($mimetype,0,$semicolon);
397 // @fixme uncertain if this is right.
398 // we want to expose things like YouTube videos as
399 // viewable attachments, but don't expose them as
400 // downloadable enclosures.....?
401 //if (in_array($mimetype, $notEnclosureMimeTypes)) {
404 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
405 if($oembed->url) $enclosure->url=$oembed->url;
406 if($oembed->title) $enclosure->title=$oembed->title;
407 if($oembed->modified) $enclosure->modified=$oembed->modified;
408 unset($oembed->size);
418 // quick back-compat hack, since there's still code using this
419 function isEnclosure()
421 $enclosure = $this->getEnclosure();
422 return !empty($enclosure);
426 * Get the attachment's thumbnail record, if any.
428 * @return File_thumbnail
430 function getThumbnail()
432 return File_thumbnail::staticGet('file_id', $this->id);
436 * Blow the cache of notices that link to this URL
438 * @param boolean $last Whether to blow the "last" cache too
443 function blowCache($last=false)
445 self::blow('file:notice-ids:%s', $this->url);
447 self::blow('file:notice-ids:%s;last', $this->url);
449 self::blow('file:notice-count:%d', $this->id);
453 * Stream of notices linking to this URL
455 * @param integer $offset Offset to show; default is 0
456 * @param integer $limit Limit of notices to show
457 * @param integer $since_id Since this notice
458 * @param integer $max_id Before this notice
460 * @return array ids of notices that link to this file
463 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
465 $stream = new FileNoticeStream($this);
466 return $stream->getNotices($offset, $limit, $since_id, $max_id);
469 function noticeCount()
471 $cacheKey = sprintf('file:notice-count:%d', $this->id);
473 $count = self::cacheGet($cacheKey);
475 if ($count === false) {
477 $f2p = new File_to_post();
479 $f2p->file_id = $this->id;
481 $count = $f2p->count();
483 self::cacheSet($cacheKey, $count);