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('GNUSOCIAL')) { exit(1); }
23 * Table Definition for file
25 class File extends Managed_DataObject
27 public $__table = 'file'; // table name
28 public $id; // int(4) primary_key not_null
29 public $url; // varchar(255) unique_key
30 public $mimetype; // varchar(50)
31 public $size; // int(4)
32 public $title; // varchar(255)
33 public $date; // int(4)
34 public $protected; // int(4)
35 public $filename; // varchar(255)
36 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
38 public static function schemaDef()
42 'id' => array('type' => 'serial', 'not null' => true),
43 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'destination URL after following redirections'),
44 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
45 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
46 'title' => array('type' => 'varchar', 'length' => 255, 'description' => 'title of resource when available'),
47 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
48 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
49 'filename' => array('type' => 'varchar', 'length' => 255, 'description' => 'if a local file, name of the file'),
50 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
51 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
53 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
55 'primary key' => array('id'),
56 'unique keys' => array(
57 'file_url_key' => array('url'),
62 function isProtected($url) {
63 return 'http://www.facebook.com/login.php' === $url;
67 * Save a new file record.
69 * @param array $redir_data lookup data eg from File_redirection::where()
70 * @param string $given_url
73 public static function saveNew(array $redir_data, $given_url) {
75 // I don't know why we have to keep doing this but I'm adding this last check to avoid
78 $x = File::getKV('url', $given_url);
80 if (!$x instanceof File) {
83 if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
84 if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
85 if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
86 if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
87 if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
88 $file_id = $x->insert();
91 $x->saveOembed($redir_data, $given_url);
96 * Save embedding information for this file, if applicable.
98 * Normally this won't need to be called manually, as File::saveNew()
101 * @param array $redir_data lookup data eg from File_redirection::where()
102 * @param string $given_url
103 * @return boolean success
105 public function saveOembed(array $redir_data, $given_url)
107 if (isset($redir_data['type'])
108 && (('text/html' === substr($redir_data['type'], 0, 9)
109 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
111 $oembed_data = File_oembed::_getOembed($given_url);
112 } catch (Exception $e) {
115 if ($oembed_data === false) {
118 $fo = File_oembed::getKV('file_id', $this->id);
120 if ($fo instanceof File_oembed) {
121 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
123 File_oembed::saveNew($oembed_data, $this->id);
131 * Go look at a URL and possibly save data about it if it's new:
132 * - follow redirect chains and store them in file_redirection
133 * - look up oEmbed data and save it in file_oembed
134 * - if a thumbnail is available, save it in file_thumbnail
135 * - save file record with basic info
136 * - optionally save a file_to_post record
137 * - return the File object with the full reference
139 * @fixme refactor this mess, it's gotten pretty scary.
140 * @param string $given_url the URL we're looking at
141 * @param int $notice_id (optional)
142 * @param bool $followRedirects defaults to true
144 * @return mixed File on success, -1 on some errors
146 * @throws ServerException on some errors
148 public function processNew($given_url, $notice_id=null, $followRedirects=true) {
149 if (empty($given_url)) return -1; // error, no url to process
150 $given_url = File_redirection::_canonUrl($given_url);
151 if (empty($given_url)) return -1; // error, no url to process
152 $file = File::getKV('url', $given_url);
154 $file_redir = File_redirection::getKV('url', $given_url);
155 if (empty($file_redir)) {
156 // @fixme for new URLs this also looks up non-redirect data
157 // such as target content type, size, etc, which we need
158 // for File::saveNew(); so we call it even if not following
160 $redir_data = File_redirection::where($given_url);
161 if (is_array($redir_data)) {
162 $redir_url = $redir_data['url'];
163 } elseif (is_string($redir_data)) {
164 $redir_url = $redir_data;
165 $redir_data = array();
167 // TRANS: Server exception thrown when a URL cannot be processed.
168 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
170 // TODO: max field length
171 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
172 $x = File::saveNew($redir_data, $given_url);
175 // This seems kind of messed up... for now skipping this part
176 // if we're already under a redirect, so we don't go into
177 // horrible infinite loops if we've been given an unstable
178 // redirect (where the final destination of the first request
179 // doesn't match what we get when we ask for it again).
181 // Seen in the wild with clojure.org, which redirects through
182 // wikispaces for auth and appends session data in the URL params.
183 $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
185 File_redirection::saveNew($redir_data, $file_id, $given_url);
188 $file_id = $file_redir->file_id;
191 $file_id = $file->id;
196 $x = File::getKV('id', $file_id);
198 // @todo FIXME: This could possibly be a clearer message :)
199 // TRANS: Server exception thrown when... Robin thinks something is impossible!
200 throw new ServerException(_('Robin thinks something is impossible.'));
204 if (!empty($notice_id)) {
205 File_to_post::processNew($file_id, $notice_id);
210 public static function respectsQuota(Profile $scoped, $fileSize) {
211 if ($fileSize > common_config('attachments', 'file_quota')) {
212 // TRANS: Message used to be inserted as %2$s in the text "No file may
213 // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
214 // TRANS: %1$d is the number of bytes of an uploaded file.
215 $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
217 $fileQuota = common_config('attachments', 'file_quota');
218 // TRANS: Message given if an upload is larger than the configured maximum.
219 // TRANS: %1$d (used for plural) is the byte limit for uploads,
220 // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
221 // TRANS: gettext support multiple plurals in the same message, unfortunately...
222 throw new ClientException(
223 sprintf(_m('No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
224 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
226 $fileQuota, $fileSizeText));
231 $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 = {$scoped->id} and file.url like '%/notice/%/file'";
232 $file->query($query);
234 $total = $file->total + $fileSize;
235 if ($total > common_config('attachments', 'user_quota')) {
236 // TRANS: Message given if an upload would exceed user quota.
237 // TRANS: %d (number) is the user quota in bytes and is used for plural.
238 throw new ClientException(
239 sprintf(_m('A file this large would exceed your user quota of %d byte.',
240 'A file this large would exceed your user quota of %d bytes.',
241 common_config('attachments', 'user_quota')),
242 common_config('attachments', 'user_quota')));
244 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
245 $file->query($query);
247 $total = $file->total + $fileSize;
248 if ($total > common_config('attachments', 'monthly_quota')) {
249 // TRANS: Message given id an upload would exceed a user's monthly quota.
250 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
251 throw new ClientException(
252 sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
253 'A file this large would exceed your monthly quota of %d bytes.',
254 common_config('attachments', 'monthly_quota')),
255 common_config('attachments', 'monthly_quota')));
260 // where should the file go?
262 static function filename(Profile $profile, $origname, $mimetype)
265 $ext = common_supported_mime_to_ext($mimetype);
266 } catch (Exception $e) {
267 // We don't support this mimetype, but let's guess the extension
268 $ext = substr(strrchr($mimetype, '/'), 1);
271 // Normalize and make the original filename more URL friendly.
272 $origname = basename($origname);
273 if (class_exists('Normalizer')) {
274 // http://php.net/manual/en/class.normalizer.php
275 // http://www.unicode.org/reports/tr15/
276 $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
278 $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
280 $nickname = $profile->nickname;
281 $datestamp = strftime('%Y%m%d', time());
283 // generate new random strings until we don't run into a filename collision.
284 $random = strtolower(common_confirmation_code(16));
285 $filename = "$nickname-$datestamp-$origname-$random.$ext";
286 } while (file_exists(self::path($filename)));
291 * Validation for as-saved base filenames
293 static function validFilename($filename)
295 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
299 * @throws ClientException on invalid filename
301 static function path($filename)
303 if (!self::validFilename($filename)) {
304 // TRANS: Client exception thrown if a file upload does not have a valid name.
305 throw new ClientException(_("Invalid filename."));
307 $dir = common_config('attachments', 'dir');
309 if ($dir[strlen($dir)-1] != '/') {
313 return $dir . $filename;
316 static function url($filename)
318 if (!self::validFilename($filename)) {
319 // TRANS: Client exception thrown if a file upload does not have a valid name.
320 throw new ClientException(_("Invalid filename."));
323 if (common_config('site','private')) {
325 return common_local_url('getfile',
326 array('filename' => $filename));
330 if (StatusNet::isHTTPS()) {
332 $sslserver = common_config('attachments', 'sslserver');
334 if (empty($sslserver)) {
335 // XXX: this assumes that background dir == site dir + /file/
336 // not true if there's another server
337 if (is_string(common_config('site', 'sslserver')) &&
338 mb_strlen(common_config('site', 'sslserver')) > 0) {
339 $server = common_config('site', 'sslserver');
340 } else if (common_config('site', 'server')) {
341 $server = common_config('site', 'server');
343 $path = common_config('site', 'path') . '/file/';
345 $server = $sslserver;
346 $path = common_config('attachments', 'sslpath');
348 $path = common_config('attachments', 'path');
354 $path = common_config('attachments', 'path');
355 $server = common_config('attachments', 'server');
357 if (empty($server)) {
358 $server = common_config('site', 'server');
361 $ssl = common_config('attachments', 'ssl');
363 $protocol = ($ssl) ? 'https' : 'http';
366 if ($path[strlen($path)-1] != '/') {
370 if ($path[0] != '/') {
374 return $protocol.'://'.$server.$path.$filename;
377 function getEnclosure(){
378 $enclosure = (object) array();
379 $enclosure->title=$this->title;
380 $enclosure->url=$this->url;
381 $enclosure->title=$this->title;
382 $enclosure->date=$this->date;
383 $enclosure->modified=$this->modified;
384 $enclosure->size=$this->size;
385 $enclosure->mimetype=$this->mimetype;
387 if(! isset($this->filename)){
388 $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
389 $mimetype = $this->mimetype;
390 if($mimetype != null){
391 $mimetype = strtolower($this->mimetype);
393 $semicolon = strpos($mimetype,';');
395 $mimetype = substr($mimetype,0,$semicolon);
397 if(in_array($mimetype,$notEnclosureMimeTypes)){
398 // Never treat generic HTML links as an enclosure type!
399 // But if we have oEmbed info, we'll consider it golden.
400 $oembed = File_oembed::getKV('file_id',$this->id);
401 if($oembed && in_array($oembed->type, array('photo', 'video'))){
402 $mimetype = strtolower($oembed->mimetype);
403 $semicolon = strpos($mimetype,';');
405 $mimetype = substr($mimetype,0,$semicolon);
407 // @fixme uncertain if this is right.
408 // we want to expose things like YouTube videos as
409 // viewable attachments, but don't expose them as
410 // downloadable enclosures.....?
411 //if (in_array($mimetype, $notEnclosureMimeTypes)) {
414 if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
415 if($oembed->url) $enclosure->url=$oembed->url;
416 if($oembed->title) $enclosure->title=$oembed->title;
417 if($oembed->modified) $enclosure->modified=$oembed->modified;
418 unset($oembed->size);
428 // quick back-compat hack, since there's still code using this
429 function isEnclosure()
431 $enclosure = $this->getEnclosure();
432 return !empty($enclosure);
436 * Get the attachment's thumbnail record, if any.
437 * Make sure you supply proper 'int' typed variables (or null).
439 * @param $width int Max width of thumbnail in pixels. (if null, use common_config values)
440 * @param $height int Max height of thumbnail in pixels. (if null, square-crop to $width)
441 * @param $crop bool Crop to the max-values' aspect ratio
443 * @return File_thumbnail
445 public function getThumbnail($width=null, $height=null, $crop=false)
447 if (intval($this->width) < 1 || intval($this->height) < 1) {
448 // Old files may have 0 until migrated with scripts/upgrade.php
449 // For any legitimately unrepresentable ones, we could generate our
450 // own image (like a square with MIME type in text)
451 throw new UnsupportedMediaException('No image geometry available.');
454 if ($width === null) {
455 $width = common_config('thumbnail', 'width');
456 $height = common_config('thumbnail', 'height');
457 $crop = common_config('thumbnail', 'crop');
460 if ($height === null) {
465 // Get proper aspect ratio width and height before lookup
466 list($width, $height, $x, $y, $w2, $h2) =
467 ImageFile::getScalingValues($this->width, $this->height, $width, $height, $crop);
469 // Doublecheck that parameters are sane and integers.
470 if ($width < 1 || $width > common_config('thumbnail', 'maxsize')
471 || $height < 1 || $height > common_config('thumbnail', 'maxsize')) {
472 // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile::getScalingValues
473 throw new ServerException('Bad thumbnail size parameters.');
476 $params = array('file_id'=> $this->id,
478 'height' => $height);
479 $thumb = File_thumbnail::pkeyGet($params);
480 if ($thumb === null) {
481 // throws exception on failure to generate thumbnail
482 $thumb = $this->generateThumbnail($width, $height, $crop);
488 * Generate and store a thumbnail image for the uploaded file, if applicable.
489 * Call this only if you know what you're doing.
491 * @param $width int Maximum thumbnail width in pixels
492 * @param $height int Maximum thumbnail height in pixels, if null, crop to $width
494 * @return File_thumbnail or null
496 protected function generateThumbnail($width, $height, $crop)
498 $width = intval($width);
499 if ($height === null) {
504 $image = ImageFile::fromFileObject($this);
506 list($width, $height, $x, $y, $w2, $h2) =
507 $image->scaleToFit($width, $height, $crop);
509 $outname = "thumb-{$width}x{$height}-" . $this->filename;
510 $outpath = self::path($outname);
512 $image->resizeTo($outpath, $width, $height, $x, $y, $w2, $h2);
514 // Avoid deleting the original
515 if ($image->getPath() != $this->getPath()) {
518 return File_thumbnail::saveThumbnail($this->id,
523 public function getPath()
525 return self::path($this->filename);
527 public function getUrl()
533 * Blow the cache of notices that link to this URL
535 * @param boolean $last Whether to blow the "last" cache too
540 function blowCache($last=false)
542 self::blow('file:notice-ids:%s', $this->url);
544 self::blow('file:notice-ids:%s;last', $this->url);
546 self::blow('file:notice-count:%d', $this->id);
550 * Stream of notices linking to this URL
552 * @param integer $offset Offset to show; default is 0
553 * @param integer $limit Limit of notices to show
554 * @param integer $since_id Since this notice
555 * @param integer $max_id Before this notice
557 * @return array ids of notices that link to this file
560 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
562 $stream = new FileNoticeStream($this);
563 return $stream->getNotices($offset, $limit, $since_id, $max_id);
566 function noticeCount()
568 $cacheKey = sprintf('file:notice-count:%d', $this->id);
570 $count = self::cacheGet($cacheKey);
572 if ($count === false) {
574 $f2p = new File_to_post();
576 $f2p->file_id = $this->id;
578 $count = $f2p->count();
580 self::cacheSet($cacheKey, $count);