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 $filehash; // varchar(64) indexed
32 public $mimetype; // varchar(50)
33 public $size; // int(4)
34 public $title; // varchar(191) not 255 because utf8mb4 takes more space
35 public $date; // int(4)
36 public $protected; // int(4)
37 public $filename; // varchar(191) not 255 because utf8mb4 takes more space
38 public $width; // int(4)
39 public $height; // int(4)
40 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
42 const URLHASH_ALG = 'sha256';
43 const FILEHASH_ALG = 'sha256';
45 public static function schemaDef()
49 'id' => array('type' => 'serial', 'not null' => true),
50 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 of destination URL (url field)'),
51 'url' => array('type' => 'text', 'description' => 'destination URL after following possible redirections'),
52 'filehash' => array('type' => 'varchar', 'length' => 64, 'not null' => false, 'description' => 'sha256 of the file contents, only for locally stored files of course'),
53 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
54 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
55 'title' => array('type' => 'varchar', 'length' => 191, 'description' => 'title of resource when available'),
56 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
57 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
58 'filename' => array('type' => 'varchar', 'length' => 191, 'description' => 'if a local file, name of the file'),
59 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
60 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
62 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
64 'primary key' => array('id'),
65 'unique keys' => array(
66 'file_urlhash_key' => array('urlhash'),
69 'file_filehash_idx' => array('filehash'),
74 function isProtected($url) {
75 return 'http://www.facebook.com/login.php' === $url;
79 * Save a new file record.
81 * @param array $redir_data lookup data eg from File_redirection::where()
82 * @param string $given_url
85 public static function saveNew(array $redir_data, $given_url)
90 // I don't know why we have to keep doing this but we run a last check to avoid
92 $file = File::getByUrl($given_url);
93 } catch (NoResultException $e) {
95 $file->urlhash = self::hashurl($given_url);
96 $file->url = $given_url;
97 if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
98 if (!empty($redir_data['title'])) $file->title = $redir_data['title'];
99 if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type'];
100 if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']);
101 if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']);
102 $file_id = $file->insert();
104 if ($file_id === false) {
105 throw new ServerException('File/URL metadata could not be saved to the database.');
109 Event::handle('EndFileSaveNew', array($file, $redir_data, $given_url));
110 assert ($file instanceof File);
115 * Go look at a URL and possibly save data about it if it's new:
116 * - follow redirect chains and store them in file_redirection
117 * - if a thumbnail is available, save it in file_thumbnail
118 * - save file record with basic info
119 * - optionally save a file_to_post record
120 * - return the File object with the full reference
122 * @fixme refactor this mess, it's gotten pretty scary.
123 * @param string $given_url the URL we're looking at
124 * @param Notice $notice (optional)
125 * @param bool $followRedirects defaults to true
127 * @return mixed File on success, -1 on some errors
129 * @throws ServerException on failure
131 public static function processNew($given_url, Notice $notice=null, $followRedirects=true) {
132 if (empty($given_url)) {
133 throw new ServerException('No given URL to process');
136 $given_url = File_redirection::_canonUrl($given_url);
137 if (empty($given_url)) {
138 throw new ServerException('No canonical URL from given URL to process');
144 $file = File::getByUrl($given_url);
145 } catch (NoResultException $e) {
146 // First check if we have a lookup trace for this URL already
148 $file_redir = File_redirection::getByUrl($given_url);
149 $file = File::getKV('id', $file_redir->file_id);
150 if (!$file instanceof File) {
151 // File did not exist, let's clean up the File_redirection entry
152 $file_redir->delete();
154 } catch (NoResultException $e) {
155 // We just wanted to doublecheck whether a File_thumbnail we might've had
156 // actually referenced an existing File object.
160 // If we still don't have a File object, let's create one now!
161 if (!$file instanceof File) {
162 // @fixme for new URLs this also looks up non-redirect data
163 // such as target content type, size, etc, which we need
164 // for File::saveNew(); so we call it even if not following
166 $redir_data = File_redirection::where($given_url);
167 if (is_array($redir_data)) {
168 $redir_url = $redir_data['url'];
169 } elseif (is_string($redir_data)) {
170 $redir_url = $redir_data;
171 $redir_data = array();
173 // TRANS: Server exception thrown when a URL cannot be processed.
174 throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
177 if ($redir_url === $given_url || !$followRedirects) {
178 // Save the File object based on our lookup trace
179 $file = File::saveNew($redir_data, $given_url);
181 // This seems kind of messed up... for now skipping this part
182 // if we're already under a redirect, so we don't go into
183 // horrible infinite loops if we've been given an unstable
184 // redirect (where the final destination of the first request
185 // doesn't match what we get when we ask for it again).
187 // Seen in the wild with clojure.org, which redirects through
188 // wikispaces for auth and appends session data in the URL params.
189 $file = self::processNew($redir_url, $notice, /*followRedirects*/false);
190 File_redirection::saveNew($redir_data, $file->id, $given_url);
193 if (!$file instanceof File) {
194 // This should only happen if File::saveNew somehow did not return a File object,
195 // though we have an assert for that in case the event there might've gone wrong.
196 // If anything else goes wrong, there should've been an exception thrown.
197 throw new ServerException('URL processing failed without new File object');
201 if ($notice instanceof Notice) {
202 File_to_post::processNew($file, $notice);
207 public static function respectsQuota(Profile $scoped, $fileSize) {
208 if ($fileSize > common_config('attachments', 'file_quota')) {
209 // TRANS: Message used to be inserted as %2$s in the text "No file may
210 // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
211 // TRANS: %1$d is the number of bytes of an uploaded file.
212 $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
214 $fileQuota = common_config('attachments', 'file_quota');
215 // TRANS: Message given if an upload is larger than the configured maximum.
216 // TRANS: %1$d (used for plural) is the byte limit for uploads,
217 // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
218 // TRANS: gettext support multiple plurals in the same message, unfortunately...
219 throw new ClientException(
220 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.',
221 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
223 $fileQuota, $fileSizeText));
228 $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'";
229 $file->query($query);
231 $total = $file->total + $fileSize;
232 if ($total > common_config('attachments', 'user_quota')) {
233 // TRANS: Message given if an upload would exceed user quota.
234 // TRANS: %d (number) is the user quota in bytes and is used for plural.
235 throw new ClientException(
236 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 $file->query($query);
244 $total = $file->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 throw new ClientException(
249 sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
250 'A file this large would exceed your monthly quota of %d bytes.',
251 common_config('attachments', 'monthly_quota')),
252 common_config('attachments', 'monthly_quota')));
257 public function getFilename()
259 if (!self::validFilename($this->filename)) {
260 // TRANS: Client exception thrown if a file upload does not have a valid name.
261 throw new ClientException(_("Invalid filename."));
263 return $this->filename;
266 // where should the file go?
268 static function filename(Profile $profile, $origname, $mimetype)
270 $ext = self::guessMimeExtension($mimetype);
272 // Normalize and make the original filename more URL friendly.
273 $origname = basename($origname, ".$ext");
274 if (class_exists('Normalizer')) {
275 // http://php.net/manual/en/class.normalizer.php
276 // http://www.unicode.org/reports/tr15/
277 $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
279 $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
281 $nickname = $profile->getNickname();
282 $datestamp = strftime('%Y%m%d', time());
284 // generate new random strings until we don't run into a filename collision.
285 $random = strtolower(common_confirmation_code(16));
286 $filename = "$nickname-$datestamp-$origname-$random.$ext";
287 } while (file_exists(self::path($filename)));
291 static function guessMimeExtension($mimetype)
294 $ext = common_supported_mime_to_ext($mimetype);
295 } catch (Exception $e) {
296 // We don't support this mimetype, but let's guess the extension
297 $ext = substr(strrchr($mimetype, '/'), 1);
299 return strtolower($ext);
303 * Validation for as-saved base filenames
305 static function validFilename($filename)
307 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
311 * @throws ClientException on invalid filename
313 static function path($filename)
315 if (!self::validFilename($filename)) {
316 // TRANS: Client exception thrown if a file upload does not have a valid name.
317 throw new ClientException(_("Invalid filename."));
319 $dir = common_config('attachments', 'dir');
321 if ($dir[strlen($dir)-1] != '/') {
325 return $dir . $filename;
328 static function url($filename)
330 if (!self::validFilename($filename)) {
331 // TRANS: Client exception thrown if a file upload does not have a valid name.
332 throw new ClientException(_("Invalid filename."));
335 if (common_config('site','private')) {
337 return common_local_url('getfile',
338 array('filename' => $filename));
342 if (GNUsocial::useHTTPS()) {
344 $sslserver = common_config('attachments', 'sslserver');
346 if (empty($sslserver)) {
347 // XXX: this assumes that background dir == site dir + /file/
348 // not true if there's another server
349 if (is_string(common_config('site', 'sslserver')) &&
350 mb_strlen(common_config('site', 'sslserver')) > 0) {
351 $server = common_config('site', 'sslserver');
352 } else if (common_config('site', 'server')) {
353 $server = common_config('site', 'server');
355 $path = common_config('site', 'path') . '/file/';
357 $server = $sslserver;
358 $path = common_config('attachments', 'sslpath');
360 $path = common_config('attachments', 'path');
366 $path = common_config('attachments', 'path');
367 $server = common_config('attachments', 'server');
369 if (empty($server)) {
370 $server = common_config('site', 'server');
373 $ssl = common_config('attachments', 'ssl');
375 $protocol = ($ssl) ? 'https' : 'http';
378 if ($path[strlen($path)-1] != '/') {
382 if ($path[0] != '/') {
386 return $protocol.'://'.$server.$path.$filename;
389 function getEnclosure(){
390 $enclosure = (object) array();
391 foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype') as $key) {
392 $enclosure->$key = $this->$key;
395 $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml');
397 if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
398 // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
399 // which may be enriched through oEmbed or similar (implemented as plugins)
400 Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
402 if (empty($enclosure->mimetype) || in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
403 // This means we either don't know what it is, so it can't
404 // be shown as an enclosure, or it is an HTML link which
405 // does not link to a resource with further metadata.
406 throw new ServerException('Unknown enclosure mimetype, not enough metadata');
412 * Get the attachment's thumbnail record, if any.
413 * Make sure you supply proper 'int' typed variables (or null).
415 * @param $width int Max width of thumbnail in pixels. (if null, use common_config values)
416 * @param $height int Max height of thumbnail in pixels. (if null, square-crop to $width)
417 * @param $crop bool Crop to the max-values' aspect ratio
419 * @return File_thumbnail
421 * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
422 * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
423 * @throws ServerException on various other errors
425 public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true)
427 // Get some more information about this file through our ImageFile class
428 $image = ImageFile::fromFileObject($this);
429 if ($image->animated && !common_config('thumbnail', 'animated')) {
430 // null means "always use file as thumbnail"
431 // false means you get choice between frozen frame or original when calling getThumbnail
432 if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
433 throw new UseFileAsThumbnailException($this->id);
437 return $image->getFileThumbnail($width, $height, $crop);
440 public function getPath()
442 $filepath = self::path($this->filename);
443 if (!file_exists($filepath)) {
444 throw new FileNotFoundException($filepath);
449 public function getUrl()
451 if (!empty($this->filename)) {
452 // A locally stored file, so let's generate a URL for our instance.
453 $url = self::url($this->filename);
454 if (self::hashurl($url) !== $this->urlhash) {
455 // For indexing purposes, in case we do a lookup on the 'url' field.
456 // also we're fixing possible changes from http to https, or paths
457 $this->updateUrl($url);
462 // No local filename available, return the URL we have stored
466 static public function getByUrl($url)
469 $file->urlhash = self::hashurl($url);
470 if (!$file->find(true)) {
471 throw new NoResultException($file);
477 * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
479 static public function getByHash($hashstr, $alg=File::FILEHASH_ALG)
482 $file->filehash = strtolower($hashstr);
483 if (!$file->find(true)) {
484 throw new NoResultException($file);
489 public function updateUrl($url)
491 $file = File::getKV('urlhash', self::hashurl($url));
492 if ($file instanceof File) {
493 throw new ServerException('URL already exists in DB');
495 $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
496 $result = $this->query(sprintf($sql, $this->tableName(),
497 $this->_quote((string)self::hashurl($url)),
498 $this->_quote((string)$url),
499 $this->_quote((string)$this->urlhash)));
500 if ($result === false) {
501 common_log_db_error($this, 'UPDATE', __FILE__);
502 throw new ServerException("Could not UPDATE {$this->tableName()}.url");
509 * Blow the cache of notices that link to this URL
511 * @param boolean $last Whether to blow the "last" cache too
516 function blowCache($last=false)
518 self::blow('file:notice-ids:%s', $this->id);
520 self::blow('file:notice-ids:%s;last', $this->id);
522 self::blow('file:notice-count:%d', $this->id);
526 * Stream of notices linking to this URL
528 * @param integer $offset Offset to show; default is 0
529 * @param integer $limit Limit of notices to show
530 * @param integer $since_id Since this notice
531 * @param integer $max_id Before this notice
533 * @return array ids of notices that link to this file
536 function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
538 $stream = new FileNoticeStream($this);
539 return $stream->getNotices($offset, $limit, $since_id, $max_id);
542 function noticeCount()
544 $cacheKey = sprintf('file:notice-count:%d', $this->id);
546 $count = self::cacheGet($cacheKey);
548 if ($count === false) {
550 $f2p = new File_to_post();
552 $f2p->file_id = $this->id;
554 $count = $f2p->count();
556 self::cacheSet($cacheKey, $count);
562 public function isLocal()
564 return !empty($this->filename);
567 public function delete($useWhere=false)
569 // Delete the file, if it exists locally
570 if (!empty($this->filename) && file_exists(self::path($this->filename))) {
571 $deleted = @unlink(self::path($this->filename));
573 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
577 // Clear out related things in the database and filesystem, such as thumbnails
578 if (Event::handle('FileDeleteRelated', array($this))) {
579 $thumbs = new File_thumbnail();
580 $thumbs->file_id = $this->id;
581 if ($thumbs->find()) {
582 while ($thumbs->fetch()) {
587 $f2p = new File_to_post();
588 $f2p->file_id = $this->id;
590 while ($f2p->fetch()) {
596 // And finally remove the entry from the database
597 return parent::delete($useWhere);
600 public function getTitle()
602 $title = $this->title ?: $this->filename;
604 return $title ?: null;
607 static public function hashurl($url)
610 throw new Exception('No URL provided to hash algorithm.');
612 return hash(self::URLHASH_ALG, $url);
615 static public function beforeSchemaUpdate()
617 $table = strtolower(get_called_class());
618 $schema = Schema::get();
619 $schemadef = $schema->getTableDef($table);
621 // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
622 if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
623 // We already have the urlhash field, so no need to migrate it.
626 echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
629 $file->query(sprintf('SELECT id, LEFT(url, 191) AS shortenedurl, COUNT(*) AS c FROM %1$s WHERE LENGTH(url)>191 GROUP BY shortenedurl HAVING c > 1', $schema->quoteIdentifier($table)));
630 print "\nFound {$file->N} URLs with too long entries in file table\n";
631 while ($file->fetch()) {
632 // We've got a URL that is too long for our future file table
633 // so we'll cut it. We could save the original URL, but there is
634 // no guarantee it is complete anyway since the previous max was 255 chars.
635 $dupfile = new File();
636 // First we find file entries that would be duplicates of this when shortened
637 // ... and we'll just throw the dupes out the window for now! It's already so borken.
638 $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = "%1$s"', $file->shortenedurl));
639 // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
640 if ($dupfile->find(true)) {
641 print "\nShortening url entry for $table id: {$file->id} [";
642 $orig = clone($dupfile);
643 $dupfile->url = $file->shortenedurl; // make sure it's only 191 chars from now on
644 $dupfile->update($orig);
645 print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
646 // only start deleting with this fetch.
647 while($dupfile->fetch()) {
653 print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
656 echo "...and now all the non-duplicates which are longer than 191 characters...\n";
657 $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');
659 echo "\n...now running hacky pre-schemaupdate change for $table:";
660 // We have to create a urlhash that is _not_ the primary key,
661 // transfer data and THEN run checkSchema
662 $schemadef['fields']['urlhash'] = array (
665 'not null' => false, // this is because when adding column, all entries will _be_ NULL!
666 'description' => 'sha256 of destination URL (url field)',
668 $schemadef['fields']['url'] = array (
670 'description' => 'destination URL after following possible redirections',
672 unset($schemadef['unique keys']);
673 $schema->ensureTable($table, $schemadef);
676 $classname = ucfirst($table);
677 $tablefix = new $classname;
678 // urlhash is hash('sha256', $url) in the File table
679 echo "Updating urlhash fields in $table table...";
680 // Maybe very MySQL specific :(
681 $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
682 $schema->quoteIdentifier($table),
684 // The line below is "result of sha256 on column `url`"
687 echo "Resuming core schema upgrade...";