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; // text()
35 public $date; // int(4)
36 public $protected; // int(4)
37 public $filename; // text()
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' => 'text', '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' => 'text', 'description' => 'if file is stored locally (too) this is the filename'),
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 public static function isProtected($url) {
76 $protected_urls_exps = array(
77 'https://www.facebook.com/login.php',
78 common_path('main/login')
81 foreach ($protected_urls_exps as $protected_url_exp) {
82 if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
91 * Save a new file record.
93 * @param array $redir_data lookup data eg from File_redirection::where()
94 * @param string $given_url
97 public static function saveNew(array $redir_data, $given_url)
101 // I don't know why we have to keep doing this but we run a last check to avoid
103 $file = File::getByUrl($given_url);
105 } catch (NoResultException $e) {
106 // We don't have the file's URL since before, so let's continue.
110 $file->url = $given_url;
111 if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
112 if (!empty($redir_data['title'])) $file->title = $redir_data['title'];
113 if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type'];
114 if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']);
115 if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']);
120 public function saveFile() {
121 $this->urlhash = self::hashurl($this->url);
123 if (!Event::handle('StartFileSaveNew', array(&$this))) {
124 throw new ServerException('File not saved due to an aborted StartFileSaveNew event.');
127 $this->id = $this->insert();
129 if ($this->id === false) {
130 throw new ServerException('File/URL metadata could not be saved to the database.');
133 Event::handle('EndFileSaveNew', array($this));
137 * Go look at a URL and possibly save data about it if it's new:
138 * - follow redirect chains and store them in file_redirection
139 * - if a thumbnail is available, save it in file_thumbnail
140 * - save file record with basic info
141 * - optionally save a file_to_post record
142 * - return the File object with the full reference
144 * @param string $given_url the URL we're looking at
145 * @param Notice $notice (optional)
146 * @param bool $followRedirects defaults to true
148 * @return mixed File on success, -1 on some errors
150 * @throws ServerException on failure
152 public static function processNew($given_url, Notice $notice=null, $followRedirects=true) {
153 if (empty($given_url)) {
154 throw new ServerException('No given URL to process');
157 $given_url = File_redirection::_canonUrl($given_url);
158 if (empty($given_url)) {
159 throw new ServerException('No canonical URL from given URL to process');
162 $redir = File_redirection::where($given_url);
163 $file = $redir->getFile();
165 if (!$file instanceof File || empty($file->id)) {
166 // This should not happen
167 throw new ServerException('URL processing failed without new File object');
170 if ($notice instanceof Notice) {
171 File_to_post::processNew($file, $notice);
177 public static function respectsQuota(Profile $scoped, $fileSize) {
178 if ($fileSize > common_config('attachments', 'file_quota')) {
179 // TRANS: Message used to be inserted as %2$s in the text "No file may
180 // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
181 // TRANS: %1$d is the number of bytes of an uploaded file.
182 $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
184 $fileQuota = common_config('attachments', 'file_quota');
185 // TRANS: Message given if an upload is larger than the configured maximum.
186 // TRANS: %1$d (used for plural) is the byte limit for uploads,
187 // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
188 // TRANS: gettext support multiple plurals in the same message, unfortunately...
189 throw new ClientException(
190 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.',
191 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
193 $fileQuota, $fileSizeText));
198 $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'";
199 $file->query($query);
201 $total = $file->total + $fileSize;
202 if ($total > common_config('attachments', 'user_quota')) {
203 // TRANS: Message given if an upload would exceed user quota.
204 // TRANS: %d (number) is the user quota in bytes and is used for plural.
205 throw new ClientException(
206 sprintf(_m('A file this large would exceed your user quota of %d byte.',
207 'A file this large would exceed your user quota of %d bytes.',
208 common_config('attachments', 'user_quota')),
209 common_config('attachments', 'user_quota')));
211 $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
212 $file->query($query);
214 $total = $file->total + $fileSize;
215 if ($total > common_config('attachments', 'monthly_quota')) {
216 // TRANS: Message given id an upload would exceed a user's monthly quota.
217 // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
218 throw new ClientException(
219 sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
220 'A file this large would exceed your monthly quota of %d bytes.',
221 common_config('attachments', 'monthly_quota')),
222 common_config('attachments', 'monthly_quota')));
227 public function getFilename()
229 if (!self::validFilename($this->filename)) {
230 // TRANS: Client exception thrown if a file upload does not have a valid name.
231 throw new ClientException(_("Invalid filename."));
233 return $this->filename;
236 // where should the file go?
238 static function filename(Profile $profile, $origname, $mimetype)
240 $ext = self::guessMimeExtension($mimetype, $origname);
242 // Normalize and make the original filename more URL friendly.
243 $origname = basename($origname, ".$ext");
244 if (class_exists('Normalizer')) {
245 // http://php.net/manual/en/class.normalizer.php
246 // http://www.unicode.org/reports/tr15/
247 $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
249 $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
251 $nickname = $profile->getNickname();
252 $datestamp = strftime('%Y%m%d', time());
254 // generate new random strings until we don't run into a filename collision.
255 $random = strtolower(common_confirmation_code(16));
256 $filename = "$nickname-$datestamp-$origname-$random.$ext";
257 } while (file_exists(self::path($filename)));
262 * @param $mimetype The mimetype we've discovered for this file.
263 * @param $filename An optional filename which we can use on failure.
265 static function guessMimeExtension($mimetype, $filename=null)
269 // first see if we know the extension for our mimetype
270 $ext = common_supported_mime_to_ext($mimetype);
273 } catch (Exception $e) { // FIXME: Make this exception more specific to "unknown mime=>ext relation"
274 // We don't know the extension for this mimetype, but let's guess.
276 // If we are very liberal with uploads ($config['attachments']['supported'] === true)
277 // then we try to do some guessing based on the filename, if it was supplied.
278 if (!is_null($filename) && common_config('attachments', 'supported')===true
279 && preg_match('/^.+\.([A-Za-z0-9]+)$/', $filename, $matches)) {
280 // we matched on a file extension, so let's see if it means something.
281 $ext = mb_strtolower($matches[1]);
283 $blacklist = common_config('attachments', 'extblacklist');
284 // If we got an extension from $filename we want to check if it's in a blacklist
285 // so we avoid people uploading .php files etc.
286 if (array_key_exists($ext, $blacklist)) {
287 if (!is_string($blacklist[$ext])) {
288 // we don't have a safe replacement extension
289 throw ClientException(_('Blacklisted file extension.'));
291 common_debug('Found replaced extension for filename '._ve($filename).': '._ve($ext));
293 // return a safe replacement extension ('php' => 'phps' for example)
294 return $blacklist[$ext];
296 // the attachment extension based on its filename was not blacklisted so it's ok to use it
301 // If nothing else has given us a result, try to extract it from
302 // the mimetype value (this turns .jpg to .jpeg for example...)
304 if (!preg_match('/\/([a-z0-9]+)/', mb_strtolower($mimetype), $matches)) {
305 throw new Exception('Malformed mimetype: '.$mimetype);
307 $ext = mb_strtolower($matches[1]);
312 * Validation for as-saved base filenames
314 static function validFilename($filename)
316 return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
320 * @throws ClientException on invalid filename
322 static function path($filename)
324 if (!self::validFilename($filename)) {
325 // TRANS: Client exception thrown if a file upload does not have a valid name.
326 throw new ClientException(_("Invalid filename."));
328 $dir = common_config('attachments', 'dir');
330 if ($dir[strlen($dir)-1] != '/') {
334 return $dir . $filename;
337 static function url($filename)
339 if (!self::validFilename($filename)) {
340 // TRANS: Client exception thrown if a file upload does not have a valid name.
341 throw new ClientException(_("Invalid filename."));
344 if (common_config('site','private')) {
346 return common_local_url('getfile',
347 array('filename' => $filename));
351 if (GNUsocial::useHTTPS()) {
353 $sslserver = common_config('attachments', 'sslserver');
355 if (empty($sslserver)) {
356 // XXX: this assumes that background dir == site dir + /file/
357 // not true if there's another server
358 if (is_string(common_config('site', 'sslserver')) &&
359 mb_strlen(common_config('site', 'sslserver')) > 0) {
360 $server = common_config('site', 'sslserver');
361 } else if (common_config('site', 'server')) {
362 $server = common_config('site', 'server');
364 $path = common_config('site', 'path') . '/file/';
366 $server = $sslserver;
367 $path = common_config('attachments', 'sslpath');
369 $path = common_config('attachments', 'path');
375 $path = common_config('attachments', 'path');
376 $server = common_config('attachments', 'server');
378 if (empty($server)) {
379 $server = common_config('site', 'server');
382 $ssl = common_config('attachments', 'ssl');
384 $protocol = ($ssl) ? 'https' : 'http';
387 if ($path[strlen($path)-1] != '/') {
391 if ($path[0] != '/') {
395 return $protocol.'://'.$server.$path.$filename;
398 static $_enclosures = array();
400 function getEnclosure(){
401 if (isset(self::$_enclosures[$this->getID()])) {
402 return self::$_enclosures[$this->getID()];
405 $enclosure = (object) array();
406 foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype', 'width', 'height') as $key) {
407 if ($this->$key !== '') {
408 $enclosure->$key = $this->$key;
412 $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml', 'text/html');
414 if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
415 // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
416 // which may be enriched through oEmbed or similar (implemented as plugins)
417 Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
419 if (empty($enclosure->mimetype)) {
420 // This means we either don't know what it is, so it can't
421 // be shown as an enclosure, or it is an HTML link which
422 // does not link to a resource with further metadata.
423 throw new ServerException('Unknown enclosure mimetype, not enough metadata');
426 self::$_enclosures[$this->getID()] = $enclosure;
430 public function hasThumbnail()
433 $this->getThumbnail();
434 } catch (Exception $e) {
441 * Get the attachment's thumbnail record, if any.
442 * Make sure you supply proper 'int' typed variables (or null).
444 * @param $width int Max width of thumbnail in pixels. (if null, use common_config values)
445 * @param $height int Max height of thumbnail in pixels. (if null, square-crop to $width)
446 * @param $crop bool Crop to the max-values' aspect ratio
448 * @return File_thumbnail
450 * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
451 * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
452 * @throws ServerException on various other errors
454 public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true, $upscale=null)
456 // Get some more information about this file through our ImageFile class
457 $image = ImageFile::fromFileObject($this);
458 if ($image->animated && !common_config('thumbnail', 'animated')) {
459 // null means "always use file as thumbnail"
460 // false means you get choice between frozen frame or original when calling getThumbnail
461 if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
462 throw new UseFileAsThumbnailException($this->id);
466 return $image->getFileThumbnail($width, $height, $crop,
467 !is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale'));
470 public function getPath()
472 $filepath = self::path($this->filename);
473 if (!file_exists($filepath)) {
474 throw new FileNotFoundException($filepath);
479 public function getUrl($prefer_local=true)
481 if ($prefer_local && !empty($this->filename)) {
482 // A locally stored file, so let's generate a URL for our instance.
483 return self::url($this->filename);
486 // No local filename available, return the URL we have stored
490 static public function getByUrl($url)
493 $file->urlhash = self::hashurl($url);
494 if (!$file->find(true)) {
495 throw new NoResultException($file);
501 * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
503 static public function getByHash($hashstr)
506 $file->filehash = strtolower($hashstr);
507 if (!$file->find(true)) {
508 throw new NoResultException($file);
513 public function updateUrl($url)
515 $file = File::getKV('urlhash', self::hashurl($url));
516 if ($file instanceof File) {
517 throw new ServerException('URL already exists in DB');
519 $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
520 $result = $this->query(sprintf($sql, $this->tableName(),
521 $this->_quote((string)self::hashurl($url)),
522 $this->_quote((string)$url),
523 $this->_quote((string)$this->urlhash)));
524 if ($result === false) {
525 common_log_db_error($this, 'UPDATE', __FILE__);
526 throw new ServerException("Could not UPDATE {$this->tableName()}.url");
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->id);
544 self::blow('file:notice-ids:%s;last', $this->id);
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);
586 public function isLocal()
588 return !empty($this->filename);
591 public function delete($useWhere=false)
593 // Delete the file, if it exists locally
594 if (!empty($this->filename) && file_exists(self::path($this->filename))) {
595 $deleted = @unlink(self::path($this->filename));
597 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
601 // Clear out related things in the database and filesystem, such as thumbnails
602 if (Event::handle('FileDeleteRelated', array($this))) {
603 $thumbs = new File_thumbnail();
604 $thumbs->file_id = $this->id;
605 if ($thumbs->find()) {
606 while ($thumbs->fetch()) {
611 $f2p = new File_to_post();
612 $f2p->file_id = $this->id;
614 while ($f2p->fetch()) {
620 // And finally remove the entry from the database
621 return parent::delete($useWhere);
624 public function getTitle()
626 $title = $this->title ?: $this->filename;
628 return $title ?: null;
631 static public function hashurl($url)
634 throw new Exception('No URL provided to hash algorithm.');
636 return hash(self::URLHASH_ALG, $url);
639 static public function beforeSchemaUpdate()
641 $table = strtolower(get_called_class());
642 $schema = Schema::get();
643 $schemadef = $schema->getTableDef($table);
645 // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
646 if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
647 // We already have the urlhash field, so no need to migrate it.
650 echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
653 $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)));
654 print "\nFound {$file->N} URLs with too long entries in file table\n";
655 while ($file->fetch()) {
656 // We've got a URL that is too long for our future file table
657 // so we'll cut it. We could save the original URL, but there is
658 // no guarantee it is complete anyway since the previous max was 255 chars.
659 $dupfile = new File();
660 // First we find file entries that would be duplicates of this when shortened
661 // ... and we'll just throw the dupes out the window for now! It's already so borken.
662 $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = "%1$s"', $file->shortenedurl));
663 // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
664 if ($dupfile->find(true)) {
665 print "\nShortening url entry for $table id: {$file->id} [";
666 $orig = clone($dupfile);
667 $dupfile->url = $file->shortenedurl; // make sure it's only 191 chars from now on
668 $dupfile->update($orig);
669 print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
670 // only start deleting with this fetch.
671 while($dupfile->fetch()) {
677 print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
680 echo "...and now all the non-duplicates which are longer than 191 characters...\n";
681 $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');
683 echo "\n...now running hacky pre-schemaupdate change for $table:";
684 // We have to create a urlhash that is _not_ the primary key,
685 // transfer data and THEN run checkSchema
686 $schemadef['fields']['urlhash'] = array (
689 'not null' => false, // this is because when adding column, all entries will _be_ NULL!
690 'description' => 'sha256 of destination URL (url field)',
692 $schemadef['fields']['url'] = array (
694 'description' => 'destination URL after following possible redirections',
696 unset($schemadef['unique keys']);
697 $schema->ensureTable($table, $schemadef);
700 $classname = ucfirst($table);
701 $tablefix = new $classname;
702 // urlhash is hash('sha256', $url) in the File table
703 echo "Updating urlhash fields in $table table...";
704 // Maybe very MySQL specific :(
705 $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
706 $schema->quoteIdentifier($table),
708 // The line below is "result of sha256 on column `url`"
711 echo "Resuming core schema upgrade...";