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) {
90 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
91 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
92 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
93 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
94 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
95 $file_id = $x->insert();
97 $x->saveOembed($redir_data, $given_url);
102 * Save embedding information for this file, if applicable.
104 * Normally this won't need to be called manually, as File::saveNew()
107 * @param array $redir_data lookup data eg from File_redirection::where()
108 * @param string $given_url
109 * @return boolean success
111 public function saveOembed($redir_data, $given_url)
113 if (isset($redir_data['type'])
114 && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
115 && ($oembed_data = File_oembed::_getOembed($given_url))) {
117 $fo = File_oembed::staticGet('file_id', $this->id);
120 File_oembed::saveNew($oembed_data, $this->id);
123 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
130 * Go look at a URL and possibly save data about it if it's new:
131 * - follow redirect chains and store them in file_redirection
132 * - look up oEmbed data and save it in file_oembed
133 * - if a thumbnail is available, save it in file_thumbnail
134 * - save file record with basic info
135 * - optionally save a file_to_post record
136 * - return the File object with the full reference
138 * @fixme refactor this mess, it's gotten pretty scary.
139 * @param string $given_url the URL we're looking at
140 * @param int $notice_id (optional)
141 * @param bool $followRedirects defaults to true
143 * @return mixed File on success, -1 on some errors
145 * @throws ServerException on some errors
147 public function processNew($given_url, $notice_id=null, $followRedirects=true) {
148 if (empty($given_url)) return -1; // error, no url to process
149 $given_url = File_redirection::_canonUrl($given_url);
150 if (empty($given_url)) return -1; // error, no url to process
151 $file = File::staticGet('url', $given_url);
153 $file_redir = File_redirection::staticGet('url', $given_url);
154 if (empty($file_redir)) {
155 // @fixme for new URLs this also looks up non-redirect data
156 // such as target content type, size, etc, which we need
157 // for File::saveNew(); so we call it even if not following
159 $redir_data = File_redirection::where($given_url);
160 if (is_array($redir_data)) {
161 $redir_url = $redir_data['url'];
162 } elseif (is_string($redir_data)) {
163 $redir_url = $redir_data;
164 $redir_data = array();
166 // TRANS: Server exception thrown when a URL cannot be processed.
167 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
169 // TODO: max field length
170 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
171 $x = File::saveNew($redir_data, $given_url);
174 // This seems kind of messed up... for now skipping this part
175 // if we're already under a redirect, so we don't go into
176 // horrible infinite loops if we've been given an unstable
177 // redirect (where the final destination of the first request
178 // doesn't match what we get when we ask for it again).
180 // Seen in the wild with clojure.org, which redirects through
181 // wikispaces for auth and appends session data in the URL params.
182 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
184 File_redirection::saveNew($redir_data, $file_id, $given_url);
187 $file_id = $file_redir->file_id;
190 $file_id = $file->id;
195 $x = File::staticGet($file_id);
197 // @todo FIXME: This could possibly be a clearer message :)
198 // TRANS: Server exception thrown when... Robin thinks something is impossible!
199 throw new ServerException(_('Robin thinks something is impossible.'));
203 if (!empty($notice_id)) {
204 File_to_post::processNew($file_id, $notice_id);
209 function isRespectsQuota($user,$fileSize) {
211 if ($fileSize > common_config('attachments', 'file_quota')) {
212 // TRANS: Message given if an upload is larger than the configured maximum.
213 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
214 // TRANS: %1$s is used for plural.
215 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.',
216 'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
217 common_config('attachments', 'file_quota')),
218 common_config('attachments', 'file_quota'), $fileSize);
221 $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'";
222 $this->query($query);
224 $total = $this->total + $fileSize;
225 if ($total > common_config('attachments', 'user_quota')) {
226 // TRANS: Message given if an upload would exceed user quota.
227 // TRANS: %d (number) is the user quota in bytes and is used for plural.
228 return sprintf(_m('A file this large would exceed your user quota of %d byte.',
229 'A file this large would exceed your user quota of %d bytes.',
230 common_config('attachments', 'user_quota')),
231 common_config('attachments', 'user_quota'));
233 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
234 $this->query($query);
236 $total = $this->total + $fileSize;
237 if ($total > common_config('attachments', 'monthly_quota')) {
238 // TRANS: Message given id an upload would exceed a user's monthly quota.
239 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
240 return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
241 'A file this large would exceed your monthly quota of %d bytes.',
242 common_config('attachments', 'monthly_quota')),
243 common_config('attachments', 'monthly_quota'));
248 // where should the file go?
250 static function filename($profile, $basename, $mimetype)
252 require_once 'MIME/Type/Extension.php';
254 // We have to temporarily disable auto handling of PEAR errors...
255 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
257 $mte = new MIME_Type_Extension();
258 $ext = $mte->getExtension($mimetype);
259 if (PEAR::isError($ext)) {
260 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
263 // Restore error handling.
264 PEAR::staticPopErrorHandling();
266 $nickname = $profile->nickname;
267 $datestamp = strftime('%Y%m%dT%H%M%S', time());
268 $random = strtolower(common_confirmation_code(32));
269 return "$nickname-$datestamp-$random.$ext";
273 * Validation for as-saved base filenames
275 static function validFilename($filename)
277 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
281 * @throws ClientException on invalid filename
283 static function path($filename)
285 if (!self::validFilename($filename)) {
286 // TRANS: Client exception thrown if a file upload does not have a valid name.
287 throw new ClientException(_("Invalid filename."));
289 $dir = common_config('attachments', 'dir');
291 if ($dir[strlen($dir)-1] != '/') {
295 return $dir . $filename;
298 static function url($filename)
300 if (!self::validFilename($filename)) {
301 // TRANS: Client exception thrown if a file upload does not have a valid name.
302 throw new ClientException(_("Invalid filename."));
305 if (common_config('site','private')) {
307 return common_local_url('getfile',
308 array('filename' => $filename));
312 if (StatusNet::isHTTPS()) {
314 $sslserver = common_config('attachments', 'sslserver');
316 if (empty($sslserver)) {
317 // XXX: this assumes that background dir == site dir + /file/
318 // not true if there's another server
319 if (is_string(common_config('site', 'sslserver')) &&
320 mb_strlen(common_config('site', 'sslserver')) > 0) {
321 $server = common_config('site', 'sslserver');
322 } else if (common_config('site', 'server')) {
323 $server = common_config('site', 'server');
325 $path = common_config('site', 'path') . '/file/';
327 $server = $sslserver;
328 $path = common_config('attachments', 'sslpath');
330 $path = common_config('attachments', 'path');
336 $path = common_config('attachments', 'path');
337 $server = common_config('attachments', 'server');
339 if (empty($server)) {
340 $server = common_config('site', 'server');
343 $ssl = common_config('attachments', 'ssl');
345 $protocol = ($ssl) ? 'https' : 'http';
348 if ($path[strlen($path)-1] != '/') {
352 if ($path[0] != '/') {
356 return $protocol.'://'.$server.$path.$filename;
359 function getEnclosure(){
360 $enclosure = (object) array();
361 $enclosure->title=$this->title;
362 $enclosure->url=$this->url;
363 $enclosure->title=$this->title;
364 $enclosure->date=$this->date;
365 $enclosure->modified=$this->modified;
366 $enclosure->size=$this->size;
367 $enclosure->mimetype=$this->mimetype;
369 if(! isset($this->filename)){
370 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
371 $mimetype = $this->mimetype;
372 if($mimetype != null){
373 $mimetype = strtolower($this->mimetype);
375 $semicolon = strpos($mimetype,';');
377 $mimetype = substr($mimetype,0,$semicolon);
379 if(in_array($mimetype,$notEnclosureMimeTypes)){
380 // Never treat generic HTML links as an enclosure type!
381 // But if we have oEmbed info, we'll consider it golden.
382 $oembed = File_oembed::staticGet('file_id',$this->id);
383 if($oembed && in_array($oembed->type, array('photo', 'video'))){
384 $mimetype = strtolower($oembed->mimetype);
385 $semicolon = strpos($mimetype,';');
387 $mimetype = substr($mimetype,0,$semicolon);
389 // @fixme uncertain if this is right.
390 // we want to expose things like YouTube videos as
391 // viewable attachments, but don't expose them as
392 // downloadable enclosures.....?
393 //if (in_array($mimetype, $notEnclosureMimeTypes)) {
396 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
397 if($oembed->url) $enclosure->url=$oembed->url;
398 if($oembed->title) $enclosure->title=$oembed->title;
399 if($oembed->modified) $enclosure->modified=$oembed->modified;
400 unset($oembed->size);
410 // quick back-compat hack, since there's still code using this
411 function isEnclosure()
413 $enclosure = $this->getEnclosure();
414 return !empty($enclosure);
418 * Get the attachment's thumbnail record, if any.
420 * @return File_thumbnail
422 function getThumbnail()
424 return File_thumbnail::staticGet('file_id', $this->id);
428 * Blow the cache of notices that link to this URL
430 * @param boolean $last Whether to blow the "last" cache too
435 function blowCache($last=false)
437 self::blow('file:notice-ids:%s', $this->url);
439 self::blow('file:notice-ids:%s;last', $this->url);
441 self::blow('file:notice-count:%d', $this->id);
445 * Stream of notices linking to this URL
447 * @param integer $offset Offset to show; default is 0
448 * @param integer $limit Limit of notices to show
449 * @param integer $since_id Since this notice
450 * @param integer $max_id Before this notice
452 * @return array ids of notices that link to this file
455 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
457 $stream = new FileNoticeStream($this);
458 return $stream->getNotices($offset, $limit, $since_id, $max_id);
461 function noticeCount()
463 $cacheKey = sprintf('file:notice-count:%d', $this->id);
465 $count = self::cacheGet($cacheKey);
467 if ($count === false) {
469 $f2p = new File_to_post();
471 $f2p->file_id = $this->id;
473 $count = $f2p->count();
475 self::cacheSet($cacheKey, $count);