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 $urlhash; // varchar(64) unique_key
31 public $mimetype; // varchar(50)
32 public $size; // int(4)
33 public $title; // varchar(191) not 255 because utf8mb4 takes more space
34 public $date; // int(4)
35 public $protected; // int(4)
36 public $filename; // varchar(191) not 255 because utf8mb4 takes more space
37 public $width; // int(4)
38 public $height; // int(4)
39 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
41 const URLHASH_ALG = 'sha256';
43 public static function schemaDef()
47 'id' => array('type' => 'serial', 'not null' => true),
48 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 of destination URL (url field)'),
49 'url' => array('type' => 'text', 'description' => 'destination URL after following possible redirections'),
50 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
51 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
52 'title' => array('type' => 'varchar', 'length' => 191, 'description' => 'title of resource when available'),
53 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
54 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
55 'filename' => array('type' => 'varchar', 'length' => 191, 'description' => 'if a local file, name of the file'),
56 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
57 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
59 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
61 'primary key' => array('id'),
62 'unique keys' => array(
63 'file_urlhash_key' => array('urlhash'),
68 function isProtected($url) {
69 return 'http://www.facebook.com/login.php' === $url;
73 * Save a new file record.
75 * @param array $redir_data lookup data eg from File_redirection::where()
76 * @param string $given_url
79 public static function saveNew(array $redir_data, $given_url) {
81 // I don't know why we have to keep doing this but I'm adding this last check to avoid
84 $file = File::getKV('urlhash', self::hashurl($given_url));
86 if (!$file instanceof File) {
88 $file->urlhash = self::hashurl($given_url);
89 $file->url = $given_url;
90 if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
91 if (!empty($redir_data['title'])) $file->title = $redir_data['title'];
92 if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type'];
93 if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']);
94 if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']);
95 $file_id = $file->insert();
98 Event::handle('EndFileSaveNew', array($file, $redir_data, $given_url));
99 assert ($file instanceof File);
104 * Go look at a URL and possibly save data about it if it's new:
105 * - follow redirect chains and store them in file_redirection
106 * - if a thumbnail is available, save it in file_thumbnail
107 * - save file record with basic info
108 * - optionally save a file_to_post record
109 * - return the File object with the full reference
111 * @fixme refactor this mess, it's gotten pretty scary.
112 * @param string $given_url the URL we're looking at
113 * @param int $notice_id (optional)
114 * @param bool $followRedirects defaults to true
116 * @return mixed File on success, -1 on some errors
118 * @throws ServerException on failure
120 public static function processNew($given_url, $notice_id=null, $followRedirects=true) {
121 if (empty($given_url)) {
122 throw new ServerException('No given URL to process');
125 $given_url = File_redirection::_canonUrl($given_url);
126 if (empty($given_url)) {
127 throw new ServerException('No canonical URL from given URL to process');
133 $file = File::getByUrl($given_url);
134 } catch (NoResultException $e) {
135 // First check if we have a lookup trace for this URL already
137 $file_redir = File_redirection::getByUrl($given_url);
138 $file = File::getKV('id', $file_redir->file_id);
139 if (!$file instanceof File) {
140 // File did not exist, let's clean up the File_redirection entry
141 $file_redir->delete();
143 } catch (NoResultException $e) {
144 // We just wanted to doublecheck whether a File_thumbnail we might've had
145 // actually referenced an existing File object.
149 // If we still don't have a File object, let's create one now!
150 if (!$file instanceof File) {
151 // @fixme for new URLs this also looks up non-redirect data
152 // such as target content type, size, etc, which we need
153 // for File::saveNew(); so we call it even if not following
155 $redir_data = File_redirection::where($given_url);
156 if (is_array($redir_data)) {
157 $redir_url = $redir_data['url'];
158 } elseif (is_string($redir_data)) {
159 $redir_url = $redir_data;
160 $redir_data = array();
162 // TRANS: Server exception thrown when a URL cannot be processed.
163 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
166 if ($redir_url === $given_url || !$followRedirects) {
167 // Save the File object based on our lookup trace
168 $file = File::saveNew($redir_data, $given_url);
170 // This seems kind of messed up... for now skipping this part
171 // if we're already under a redirect, so we don't go into
172 // horrible infinite loops if we've been given an unstable
173 // redirect (where the final destination of the first request
174 // doesn't match what we get when we ask for it again).
176 // Seen in the wild with clojure.org, which redirects through
177 // wikispaces for auth and appends session data in the URL params.
178 $file = self::processNew($redir_url, $notice_id, /*followRedirects*/false);
179 File_redirection::saveNew($redir_data, $file->id, $given_url);
182 if (!$file instanceof File) {
183 // This should only happen if File::saveNew somehow did not return a File object,
184 // though we have an assert for that in case the event there might've gone wrong.
185 // If anything else goes wrong, there should've been an exception thrown.
186 throw new ServerException('URL processing failed without new File object');
190 if (!empty($notice_id)) {
191 File_to_post::processNew($file->id, $notice_id);
196 public static function respectsQuota(Profile $scoped, $fileSize) {
197 if ($fileSize > common_config('attachments', 'file_quota')) {
198 // TRANS: Message used to be inserted as %2$s in the text "No file may
199 // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
200 // TRANS: %1$d is the number of bytes of an uploaded file.
201 $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
203 $fileQuota = common_config('attachments', 'file_quota');
204 // TRANS: Message given if an upload is larger than the configured maximum.
205 // TRANS: %1$d (used for plural) is the byte limit for uploads,
206 // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
207 // TRANS: gettext support multiple plurals in the same message, unfortunately...
208 throw new ClientException(
209 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.',
210 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
212 $fileQuota, $fileSizeText));
217 $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'";
218 $file->query($query);
220 $total = $file->total + $fileSize;
221 if ($total > common_config('attachments', 'user_quota')) {
222 // TRANS: Message given if an upload would exceed user quota.
223 // TRANS: %d (number) is the user quota in bytes and is used for plural.
224 throw new ClientException(
225 sprintf(_m('A file this large would exceed your user quota of %d byte.',
226 'A file this large would exceed your user quota of %d bytes.',
227 common_config('attachments', 'user_quota')),
228 common_config('attachments', 'user_quota')));
230 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
231 $file->query($query);
233 $total = $file->total + $fileSize;
234 if ($total > common_config('attachments', 'monthly_quota')) {
235 // TRANS: Message given id an upload would exceed a user's monthly quota.
236 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
237 throw new ClientException(
238 sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
239 'A file this large would exceed your monthly quota of %d bytes.',
240 common_config('attachments', 'monthly_quota')),
241 common_config('attachments', 'monthly_quota')));
246 // where should the file go?
248 static function filename(Profile $profile, $origname, $mimetype)
251 $ext = common_supported_mime_to_ext($mimetype);
252 } catch (Exception $e) {
253 // We don't support this mimetype, but let's guess the extension
254 $ext = substr(strrchr($mimetype, '/'), 1);
257 // Normalize and make the original filename more URL friendly.
258 $origname = basename($origname, ".$ext");
259 if (class_exists('Normalizer')) {
260 // http://php.net/manual/en/class.normalizer.php
261 // http://www.unicode.org/reports/tr15/
262 $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
264 $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
266 $nickname = $profile->getNickname();
267 $datestamp = strftime('%Y%m%d', time());
269 // generate new random strings until we don't run into a filename collision.
270 $random = strtolower(common_confirmation_code(16));
271 $filename = "$nickname-$datestamp-$origname-$random.$ext";
272 } while (file_exists(self::path($filename)));
277 * Validation for as-saved base filenames
279 static function validFilename($filename)
281 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
285 * @throws ClientException on invalid filename
287 static function path($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."));
293 $dir = common_config('attachments', 'dir');
295 if ($dir[strlen($dir)-1] != '/') {
299 return $dir . $filename;
302 static function url($filename)
304 if (!self::validFilename($filename)) {
305 // TRANS: Client exception thrown if a file upload does not have a valid name.
306 throw new ClientException(_("Invalid filename."));
309 if (common_config('site','private')) {
311 return common_local_url('getfile',
312 array('filename' => $filename));
316 if (StatusNet::useHTTPS()) {
318 $sslserver = common_config('attachments', 'sslserver');
320 if (empty($sslserver)) {
321 // XXX: this assumes that background dir == site dir + /file/
322 // not true if there's another server
323 if (is_string(common_config('site', 'sslserver')) &&
324 mb_strlen(common_config('site', 'sslserver')) > 0) {
325 $server = common_config('site', 'sslserver');
326 } else if (common_config('site', 'server')) {
327 $server = common_config('site', 'server');
329 $path = common_config('site', 'path') . '/file/';
331 $server = $sslserver;
332 $path = common_config('attachments', 'sslpath');
334 $path = common_config('attachments', 'path');
340 $path = common_config('attachments', 'path');
341 $server = common_config('attachments', 'server');
343 if (empty($server)) {
344 $server = common_config('site', 'server');
347 $ssl = common_config('attachments', 'ssl');
349 $protocol = ($ssl) ? 'https' : 'http';
352 if ($path[strlen($path)-1] != '/') {
356 if ($path[0] != '/') {
360 return $protocol.'://'.$server.$path.$filename;
363 function getEnclosure(){
364 $enclosure = (object) array();
365 foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype') as $key) {
366 $enclosure->$key = $this->$key;
369 $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml');
371 if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
372 // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
373 // which may be enriched through oEmbed or similar (implemented as plugins)
374 Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
376 if (empty($enclosure->mimetype) || in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
377 // This means we either don't know what it is, so it can't
378 // be shown as an enclosure, or it is an HTML link which
379 // does not link to a resource with further metadata.
380 throw new ServerException('Unknown enclosure mimetype, not enough metadata');
386 * Get the attachment's thumbnail record, if any.
387 * Make sure you supply proper 'int' typed variables (or null).
389 * @param $width int Max width of thumbnail in pixels. (if null, use common_config values)
390 * @param $height int Max height of thumbnail in pixels. (if null, square-crop to $width)
391 * @param $crop bool Crop to the max-values' aspect ratio
393 * @return File_thumbnail
395 public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true)
397 // Get some more information about this file through our ImageFile class
398 $image = ImageFile::fromFileObject($this);
399 if ($image->animated && !common_config('thumbnail', 'animated')) {
400 // null means "always use file as thumbnail"
401 // false means you get choice between frozen frame or original when calling getThumbnail
402 if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
403 throw new UseFileAsThumbnailException($this->id);
407 if ($width === null) {
408 $width = common_config('thumbnail', 'width');
409 $height = common_config('thumbnail', 'height');
410 $crop = common_config('thumbnail', 'crop');
413 if ($height === null || $height < 1) {
418 // Debug log (convert crop to int to have TRUE being displayed as 1 and FALSE as 0)
419 common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: width=' . $width . ',height=' . $height . ',crop=' . intval($crop));
421 // Get proper aspect ratio width and height before lookup
422 // We have to do it through an ImageFile object because of orientation etc.
423 // Only other solution would've been to rotate + rewrite uploaded files.
424 list($width, $height, $x, $y, $w, $h) =
425 $image->scaleToFit($width, $height, $crop);
427 $params = array('file_id'=> $this->id,
429 'height' => $height);
430 $thumb = File_thumbnail::pkeyGet($params);
431 if ($thumb instanceof File_thumbnail) {
435 // throws exception on failure to generate thumbnail
436 $outname = "thumb-{$width}x{$height}-" . $image->filename;
437 $outpath = self::path($outname);
439 // The boundary box for our resizing
440 $box = array('width'=>$width, 'height'=>$height,
444 // Doublecheck that parameters are sane and integers.
445 if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
446 || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
447 || $box['w'] < 1 || $box['x'] >= $image->width
448 || $box['h'] < 1 || $box['y'] >= $image->height) {
449 // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
450 common_debug("Boundary box parameters for resize of {$image->filepath} : ".var_export($box,true));
451 throw new ServerException('Bad thumbnail size parameters. maxsize=' .
452 common_config('thumbnail', 'maxsize') .
453 ',box[width]=' . $box['width'] .
454 ',box[height]=' . $box['height'] .
455 ',box[w]=' . $box['w'] .
456 ',box[h]=' . $box['h'] .
457 ',box[x]=' . $box['x'] .
458 ',box[y]=' . $box['y'] .
459 ',this->width=' . $this->width .
460 ',this->heigh=' . $this->height .
461 ',this->filepath=' . $this->filepath .
462 ',this->filename=' . $this->filename
466 common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', $this->id, $width, $height));
467 // Perform resize and store into file
468 $image->resizeTo($outpath, $box);
470 // Avoid deleting the original
471 if ($image->getPath() != self::path($image->filename)) {
474 return File_thumbnail::saveThumbnail($this->id,
480 public function getPath()
482 return self::path($this->filename);
485 public function getUrl()
487 if (!empty($this->filename)) {
488 // A locally stored file, so let's generate a URL for our instance.
489 $url = self::url($this->filename);
490 if (self::hashurl($url) !== $this->urlhash) {
491 // For indexing purposes, in case we do a lookup on the 'url' field.
492 // also we're fixing possible changes from http to https, or paths
493 $this->updateUrl($url);
498 // No local filename available, return the URL we have stored
502 static public function getByUrl($url)
505 $file->urlhash = self::hashurl($url);
506 if (!$file->find(true)) {
507 throw new NoResultException($file);
512 public function updateUrl($url)
514 $file = File::getKV('urlhash', self::hashurl($url));
515 if ($file instanceof File) {
516 throw new ServerException('URL already exists in DB');
518 $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
519 $result = $this->query(sprintf($sql, $this->__table,
520 $this->_quote((string)self::hashurl($url)),
521 $this->_quote((string)$url),
522 $this->_quote((string)$this->urlhash)));
523 if ($result === false) {
524 common_log_db_error($this, 'UPDATE', __FILE__);
525 throw new ServerException("Could not UPDATE {$this->__table}.url");
532 * Blow the cache of notices that link to this URL
534 * @param boolean $last Whether to blow the "last" cache too
539 function blowCache($last=false)
541 self::blow('file:notice-ids:%s', $this->urlhash);
543 self::blow('file:notice-ids:%s;last', $this->urlhash);
545 self::blow('file:notice-count:%d', $this->id);
549 * Stream of notices linking to this URL
551 * @param integer $offset Offset to show; default is 0
552 * @param integer $limit Limit of notices to show
553 * @param integer $since_id Since this notice
554 * @param integer $max_id Before this notice
556 * @return array ids of notices that link to this file
559 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
561 $stream = new FileNoticeStream($this);
562 return $stream->getNotices($offset, $limit, $since_id, $max_id);
565 function noticeCount()
567 $cacheKey = sprintf('file:notice-count:%d', $this->id);
569 $count = self::cacheGet($cacheKey);
571 if ($count === false) {
573 $f2p = new File_to_post();
575 $f2p->file_id = $this->id;
577 $count = $f2p->count();
579 self::cacheSet($cacheKey, $count);
585 public function isLocal()
587 return !empty($this->filename);
590 public function delete($useWhere=false)
592 // Delete the file, if it exists locally
593 if (!empty($this->filename) && file_exists(self::path($this->filename))) {
594 $deleted = @unlink(self::path($this->filename));
596 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
600 // Clear out related things in the database and filesystem, such as thumbnails
601 if (Event::handle('FileDeleteRelated', array($this))) {
602 $thumbs = new File_thumbnail();
603 $thumbs->file_id = $this->id;
604 if ($thumbs->find()) {
605 while ($thumbs->fetch()) {
611 // And finally remove the entry from the database
612 return parent::delete($useWhere);
615 public function getTitle()
617 $title = $this->title ?: $this->filename;
619 return $title ?: null;
622 static public function hashurl($url)
625 throw new Exception('No URL provided to hash algorithm.');
627 return hash(self::URLHASH_ALG, $url);
630 static public function beforeSchemaUpdate()
632 $table = strtolower(get_called_class());
633 $schema = Schema::get();
634 $schemadef = $schema->getTableDef($table);
636 // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
637 if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
638 // We already have the urlhash field, so no need to migrate it.
641 echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
642 // We have to create a urlhash that is _not_ the primary key,
643 // transfer data and THEN run checkSchema
644 $schemadef['fields']['urlhash'] = array (
648 'description' => 'sha256 of destination URL (url field)',
650 $schemadef['fields']['url'] = array (
652 'description' => 'destination URL after following possible redirections',
654 unset($schemadef['unique keys']);
655 $schema->ensureTable($table, $schemadef);
658 $classname = ucfirst($table);
659 $tablefix = new $classname;
660 // urlhash is hash('sha256', $url) in the File table
661 echo "Updating urlhash fields in $table table...";
662 // Maybe very MySQL specific :(
663 $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
664 $schema->quoteIdentifier($table),
666 // The line below is "result of sha256 on column `url`"
669 echo "Resuming core schema upgrade...";