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 * Go look at a URL and possibly save data about it if it's new:
120 * - follow redirect chains and store them in file_redirection
121 * - look up oEmbed data and save it in file_oembed
122 * - if a thumbnail is available, save it in file_thumbnail
123 * - save file record with basic info
124 * - optionally save a file_to_post record
125 * - return the File object with the full reference
127 * @fixme refactor this mess, it's gotten pretty scary.
128 * @param string $given_url the URL we're looking at
129 * @param int $notice_id (optional)
130 * @param bool $followRedirects defaults to true
132 * @return mixed File on success, -1 on some errors
134 * @throws ServerException on some errors
136 public function processNew($given_url, $notice_id=null, $followRedirects=true) {
137 if (empty($given_url)) return -1; // error, no url to process
138 $given_url = File_redirection::_canonUrl($given_url);
139 if (empty($given_url)) return -1; // error, no url to process
140 $file = File::staticGet('url', $given_url);
142 $file_redir = File_redirection::staticGet('url', $given_url);
143 if (empty($file_redir)) {
144 // @fixme for new URLs this also looks up non-redirect data
145 // such as target content type, size, etc, which we need
146 // for File::saveNew(); so we call it even if not following
148 $redir_data = File_redirection::where($given_url);
149 if (is_array($redir_data)) {
150 $redir_url = $redir_data['url'];
151 } elseif (is_string($redir_data)) {
152 $redir_url = $redir_data;
153 $redir_data = array();
155 // TRANS: Server exception thrown when a URL cannot be processed.
156 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
158 // TODO: max field length
159 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
160 $x = File::saveNew($redir_data, $given_url);
163 // This seems kind of messed up... for now skipping this part
164 // if we're already under a redirect, so we don't go into
165 // horrible infinite loops if we've been given an unstable
166 // redirect (where the final destination of the first request
167 // doesn't match what we get when we ask for it again).
169 // Seen in the wild with clojure.org, which redirects through
170 // wikispaces for auth and appends session data in the URL params.
171 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
173 File_redirection::saveNew($redir_data, $file_id, $given_url);
176 $file_id = $file_redir->file_id;
179 $file_id = $file->id;
184 $x = File::staticGet($file_id);
186 // @todo FIXME: This could possibly be a clearer message :)
187 // TRANS: Server exception thrown when... Robin thinks something is impossible!
188 throw new ServerException(_('Robin thinks something is impossible.'));
192 if (!empty($notice_id)) {
193 File_to_post::processNew($file_id, $notice_id);
198 function isRespectsQuota($user,$fileSize) {
200 if ($fileSize > common_config('attachments', 'file_quota')) {
201 // TRANS: Message given if an upload is larger than the configured maximum.
202 // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
203 // TRANS: %1$s is used for plural.
204 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.',
205 'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
206 common_config('attachments', 'file_quota')),
207 common_config('attachments', 'file_quota'), $fileSize);
210 $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'";
211 $this->query($query);
213 $total = $this->total + $fileSize;
214 if ($total > common_config('attachments', 'user_quota')) {
215 // TRANS: Message given if an upload would exceed user quota.
216 // TRANS: %d (number) is the user quota in bytes and is used for plural.
217 return sprintf(_m('A file this large would exceed your user quota of %d byte.',
218 'A file this large would exceed your user quota of %d bytes.',
219 common_config('attachments', 'user_quota')),
220 common_config('attachments', 'user_quota'));
222 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
223 $this->query($query);
225 $total = $this->total + $fileSize;
226 if ($total > common_config('attachments', 'monthly_quota')) {
227 // TRANS: Message given id an upload would exceed a user's monthly quota.
228 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
229 return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
230 'A file this large would exceed your monthly quota of %d bytes.',
231 common_config('attachments', 'monthly_quota')),
232 common_config('attachments', 'monthly_quota'));
237 // where should the file go?
239 static function filename($profile, $basename, $mimetype)
241 require_once 'MIME/Type/Extension.php';
243 // We have to temporarily disable auto handling of PEAR errors...
244 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
246 $mte = new MIME_Type_Extension();
247 $ext = $mte->getExtension($mimetype);
248 if (PEAR::isError($ext)) {
249 $ext = strtolower(preg_replace('/\W/', '', $mimetype));
252 // Restore error handling.
253 PEAR::staticPopErrorHandling();
255 $nickname = $profile->nickname;
256 $datestamp = strftime('%Y%m%dT%H%M%S', time());
257 $random = strtolower(common_confirmation_code(32));
258 return "$nickname-$datestamp-$random.$ext";
262 * Validation for as-saved base filenames
264 static function validFilename($filename)
266 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
270 * @throws ClientException on invalid filename
272 static function path($filename)
274 if (!self::validFilename($filename)) {
275 // TRANS: Client exception thrown if a file upload does not have a valid name.
276 throw new ClientException(_("Invalid filename."));
278 $dir = common_config('attachments', 'dir');
280 if ($dir[strlen($dir)-1] != '/') {
284 return $dir . $filename;
287 static function url($filename)
289 if (!self::validFilename($filename)) {
290 // TRANS: Client exception thrown if a file upload does not have a valid name.
291 throw new ClientException(_("Invalid filename."));
294 if (common_config('site','private')) {
296 return common_local_url('getfile',
297 array('filename' => $filename));
301 if (StatusNet::isHTTPS()) {
303 $sslserver = common_config('attachments', 'sslserver');
305 if (empty($sslserver)) {
306 // XXX: this assumes that background dir == site dir + /file/
307 // not true if there's another server
308 if (is_string(common_config('site', 'sslserver')) &&
309 mb_strlen(common_config('site', 'sslserver')) > 0) {
310 $server = common_config('site', 'sslserver');
311 } else if (common_config('site', 'server')) {
312 $server = common_config('site', 'server');
314 $path = common_config('site', 'path') . '/file/';
316 $server = $sslserver;
317 $path = common_config('attachments', 'sslpath');
319 $path = common_config('attachments', 'path');
325 $path = common_config('attachments', 'path');
326 $server = common_config('attachments', 'server');
328 if (empty($server)) {
329 $server = common_config('site', 'server');
332 $ssl = common_config('attachments', 'ssl');
334 $protocol = ($ssl) ? 'https' : 'http';
337 if ($path[strlen($path)-1] != '/') {
341 if ($path[0] != '/') {
345 return $protocol.'://'.$server.$path.$filename;
348 function getEnclosure(){
349 $enclosure = (object) array();
350 $enclosure->title=$this->title;
351 $enclosure->url=$this->url;
352 $enclosure->title=$this->title;
353 $enclosure->date=$this->date;
354 $enclosure->modified=$this->modified;
355 $enclosure->size=$this->size;
356 $enclosure->mimetype=$this->mimetype;
358 if(! isset($this->filename)){
359 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
360 $mimetype = $this->mimetype;
361 if($mimetype != null){
362 $mimetype = strtolower($this->mimetype);
364 $semicolon = strpos($mimetype,';');
366 $mimetype = substr($mimetype,0,$semicolon);
368 if(in_array($mimetype,$notEnclosureMimeTypes)){
369 // Never treat generic HTML links as an enclosure type!
370 // But if we have oEmbed info, we'll consider it golden.
371 $oembed = File_oembed::staticGet('file_id',$this->id);
372 if($oembed && in_array($oembed->type, array('photo', 'video'))){
373 $mimetype = strtolower($oembed->mimetype);
374 $semicolon = strpos($mimetype,';');
376 $mimetype = substr($mimetype,0,$semicolon);
378 // @fixme uncertain if this is right.
379 // we want to expose things like YouTube videos as
380 // viewable attachments, but don't expose them as
381 // downloadable enclosures.....?
382 //if (in_array($mimetype, $notEnclosureMimeTypes)) {
385 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
386 if($oembed->url) $enclosure->url=$oembed->url;
387 if($oembed->title) $enclosure->title=$oembed->title;
388 if($oembed->modified) $enclosure->modified=$oembed->modified;
389 unset($oembed->size);
399 // quick back-compat hack, since there's still code using this
400 function isEnclosure()
402 $enclosure = $this->getEnclosure();
403 return !empty($enclosure);
407 * Get the attachment's thumbnail record, if any.
409 * @return File_thumbnail
411 function getThumbnail()
413 return File_thumbnail::staticGet('file_id', $this->id);