]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
File and File_redirection records are saved in File_redirection::where() now
[quix0rs-gnu-social.git] / classes / File.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Table Definition for file
24  */
25 class File extends Managed_DataObject
26 {
27     public $__table = 'file';                            // table name
28     public $id;                              // int(4)  primary_key not_null
29     public $urlhash;                         // varchar(64)  unique_key
30     public $url;                             // text
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
41
42     const URLHASH_ALG = 'sha256';
43     const FILEHASH_ALG = 'sha256';
44
45     public static function schemaDef()
46     {
47         return array(
48             'fields' => array(
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'),
61
62                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
63             ),
64             'primary key' => array('id'),
65             'unique keys' => array(
66                 'file_urlhash_key' => array('urlhash'),
67             ),
68             'indexes' => array(
69                 'file_filehash_idx' => array('filehash'),
70             ),
71         );
72     }
73
74     function isProtected($url) {
75         return 'http://www.facebook.com/login.php' === $url;
76     }
77
78     /**
79      * Save a new file record.
80      *
81      * @param array $redir_data lookup data eg from File_redirection::where()
82      * @param string $given_url
83      * @return File
84      */
85     public static function saveNew(array $redir_data, $given_url)
86     {
87         $file = null;
88         try {
89             // I don't know why we have to keep doing this but we run a last check to avoid
90             // uniqueness bugs.
91             $file = File::getByUrl($given_url);
92             return $file;
93         } catch (NoResultException $e) {
94             // We don't have the file's URL since before, so let's continue.
95         }
96
97         $file = new File;
98         $file->url = $given_url;
99         if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
100         if (!empty($redir_data['title'])) $file->title = $redir_data['title'];
101         if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type'];
102         if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']);
103         if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']);
104         $file->saveFile();
105         return $file;
106     }
107
108     public function saveFile() {
109         $this->urlhash = self::hashurl($this->url);
110
111         if (!Event::handle('StartFileSaveNew', array(&$this))) {
112             throw new ServerException('File not saved due to an aborted StartFileSaveNew event.');
113         }
114
115         $this->id = $this->insert();
116
117         if ($this->id === false) {
118             throw new ServerException('File/URL metadata could not be saved to the database.');
119         }
120
121         Event::handle('EndFileSaveNew', array($this));
122     }
123
124     /**
125      * Go look at a URL and possibly save data about it if it's new:
126      * - follow redirect chains and store them in file_redirection
127      * - if a thumbnail is available, save it in file_thumbnail
128      * - save file record with basic info
129      * - optionally save a file_to_post record
130      * - return the File object with the full reference
131      *
132      * @param string $given_url the URL we're looking at
133      * @param Notice $notice (optional)
134      * @param bool $followRedirects defaults to true
135      *
136      * @return mixed File on success, -1 on some errors
137      *
138      * @throws ServerException on failure
139      */
140     public static function processNew($given_url, Notice $notice=null, $followRedirects=true) {
141         if (empty($given_url)) {
142             throw new ServerException('No given URL to process');
143         }
144
145         $given_url = File_redirection::_canonUrl($given_url);
146         if (empty($given_url)) {
147             throw new ServerException('No canonical URL from given URL to process');
148         }
149
150         $redir = File_redirection::where($given_url);
151         $file = $redir->getFile();
152
153         if (!$file instanceof File || empty($file->id)) {
154             // This should not happen
155             throw new ServerException('URL processing failed without new File object');
156         }
157
158         if ($notice instanceof Notice) {
159             File_to_post::processNew($file, $notice);
160         }
161
162         return $file;
163     }
164
165     public static function respectsQuota(Profile $scoped, $fileSize) {
166         if ($fileSize > common_config('attachments', 'file_quota')) {
167             // TRANS: Message used to be inserted as %2$s in  the text "No file may
168             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
169             // TRANS: %1$d is the number of bytes of an uploaded file.
170             $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
171
172             $fileQuota = common_config('attachments', 'file_quota');
173             // TRANS: Message given if an upload is larger than the configured maximum.
174             // TRANS: %1$d (used for plural) is the byte limit for uploads,
175             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
176             // TRANS: gettext support multiple plurals in the same message, unfortunately...
177             throw new ClientException(
178                     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.',
179                               'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
180                               $fileQuota),
181                     $fileQuota, $fileSizeText));
182         }
183
184         $file = new File;
185
186         $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'";
187         $file->query($query);
188         $file->fetch();
189         $total = $file->total + $fileSize;
190         if ($total > common_config('attachments', 'user_quota')) {
191             // TRANS: Message given if an upload would exceed user quota.
192             // TRANS: %d (number) is the user quota in bytes and is used for plural.
193             throw new ClientException(
194                     sprintf(_m('A file this large would exceed your user quota of %d byte.',
195                               'A file this large would exceed your user quota of %d bytes.',
196                               common_config('attachments', 'user_quota')),
197                     common_config('attachments', 'user_quota')));
198         }
199         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
200         $file->query($query);
201         $file->fetch();
202         $total = $file->total + $fileSize;
203         if ($total > common_config('attachments', 'monthly_quota')) {
204             // TRANS: Message given id an upload would exceed a user's monthly quota.
205             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
206             throw new ClientException(
207                     sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
208                               'A file this large would exceed your monthly quota of %d bytes.',
209                               common_config('attachments', 'monthly_quota')),
210                     common_config('attachments', 'monthly_quota')));
211         }
212         return true;
213     }
214
215     public function getFilename()
216     {
217         if (!self::validFilename($this->filename)) {
218             // TRANS: Client exception thrown if a file upload does not have a valid name.
219             throw new ClientException(_("Invalid filename."));
220         }
221         return $this->filename;
222     }
223
224     // where should the file go?
225
226     static function filename(Profile $profile, $origname, $mimetype)
227     {
228         $ext = self::guessMimeExtension($mimetype);
229
230         // Normalize and make the original filename more URL friendly.
231         $origname = basename($origname, ".$ext");
232         if (class_exists('Normalizer')) {
233             // http://php.net/manual/en/class.normalizer.php
234             // http://www.unicode.org/reports/tr15/
235             $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
236         }
237         $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
238
239         $nickname = $profile->getNickname();
240         $datestamp = strftime('%Y%m%d', time());
241         do {
242             // generate new random strings until we don't run into a filename collision.
243             $random = strtolower(common_confirmation_code(16));
244             $filename = "$nickname-$datestamp-$origname-$random.$ext";
245         } while (file_exists(self::path($filename)));
246         return $filename;
247     }
248
249     static function guessMimeExtension($mimetype)
250     {
251         try {
252             $ext = common_supported_mime_to_ext($mimetype);
253         } catch (Exception $e) {
254             // We don't support this mimetype, but let's guess the extension
255             $matches = array();
256             if (!preg_match('/\/([a-z0-9]+)/', mb_strtolower($mimetype), $matches)) {
257                 throw new Exception('Malformed mimetype: '.$mimetype);
258             }
259             $ext = $matches[1];
260         }
261         return mb_strtolower($ext);
262     }
263
264     /**
265      * Validation for as-saved base filenames
266      */
267     static function validFilename($filename)
268     {
269         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
270     }
271
272     /**
273      * @throws ClientException on invalid filename
274      */
275     static function path($filename)
276     {
277         if (!self::validFilename($filename)) {
278             // TRANS: Client exception thrown if a file upload does not have a valid name.
279             throw new ClientException(_("Invalid filename."));
280         }
281         $dir = common_config('attachments', 'dir');
282
283         if ($dir[strlen($dir)-1] != '/') {
284             $dir .= '/';
285         }
286
287         return $dir . $filename;
288     }
289
290     static function url($filename)
291     {
292         if (!self::validFilename($filename)) {
293             // TRANS: Client exception thrown if a file upload does not have a valid name.
294             throw new ClientException(_("Invalid filename."));
295         }
296
297         if (common_config('site','private')) {
298
299             return common_local_url('getfile',
300                                 array('filename' => $filename));
301
302         }
303
304         if (GNUsocial::useHTTPS()) {
305
306             $sslserver = common_config('attachments', 'sslserver');
307
308             if (empty($sslserver)) {
309                 // XXX: this assumes that background dir == site dir + /file/
310                 // not true if there's another server
311                 if (is_string(common_config('site', 'sslserver')) &&
312                     mb_strlen(common_config('site', 'sslserver')) > 0) {
313                     $server = common_config('site', 'sslserver');
314                 } else if (common_config('site', 'server')) {
315                     $server = common_config('site', 'server');
316                 }
317                 $path = common_config('site', 'path') . '/file/';
318             } else {
319                 $server = $sslserver;
320                 $path   = common_config('attachments', 'sslpath');
321                 if (empty($path)) {
322                     $path = common_config('attachments', 'path');
323                 }
324             }
325
326             $protocol = 'https';
327         } else {
328             $path = common_config('attachments', 'path');
329             $server = common_config('attachments', 'server');
330
331             if (empty($server)) {
332                 $server = common_config('site', 'server');
333             }
334
335             $ssl = common_config('attachments', 'ssl');
336
337             $protocol = ($ssl) ? 'https' : 'http';
338         }
339
340         if ($path[strlen($path)-1] != '/') {
341             $path .= '/';
342         }
343
344         if ($path[0] != '/') {
345             $path = '/'.$path;
346         }
347
348         return $protocol.'://'.$server.$path.$filename;
349     }
350
351     static $_enclosures = array();
352
353     function getEnclosure(){
354         if (isset(self::$_enclosures[$this->getID()])) {
355             return self::$_enclosures[$this->getID()];
356         }
357
358         $enclosure = (object) array();
359         foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype', 'width', 'height') as $key) {
360             if ($this->$key !== '') {
361                 $enclosure->$key = $this->$key;
362             }
363         }
364
365         $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml', 'text/html');
366
367         if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
368             // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
369             // which may be enriched through oEmbed or similar (implemented as plugins)
370             Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
371         }
372         if (empty($enclosure->mimetype)) {
373             // This means we either don't know what it is, so it can't
374             // be shown as an enclosure, or it is an HTML link which
375             // does not link to a resource with further metadata.
376             throw new ServerException('Unknown enclosure mimetype, not enough metadata');
377         }
378
379         self::$_enclosures[$this->getID()] = $enclosure;
380         return $enclosure;
381     }
382
383     public function hasThumbnail()
384     {
385         try {
386             $this->getThumbnail();
387         } catch (Exception $e) {
388             return false;
389         }
390         return true;
391     }
392
393     /**
394      * Get the attachment's thumbnail record, if any.
395      * Make sure you supply proper 'int' typed variables (or null).
396      *
397      * @param $width  int   Max width of thumbnail in pixels. (if null, use common_config values)
398      * @param $height int   Max height of thumbnail in pixels. (if null, square-crop to $width)
399      * @param $crop   bool  Crop to the max-values' aspect ratio
400      *
401      * @return File_thumbnail
402      *
403      * @throws UseFileAsThumbnailException  if the file is considered an image itself and should be itself as thumbnail
404      * @throws UnsupportedMediaException    if, despite trying, we can't understand how to make a thumbnail for this format
405      * @throws ServerException              on various other errors
406      */
407     public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true)
408     {
409         // Get some more information about this file through our ImageFile class
410         $image = ImageFile::fromFileObject($this);
411         if ($image->animated && !common_config('thumbnail', 'animated')) {
412             // null  means "always use file as thumbnail"
413             // false means you get choice between frozen frame or original when calling getThumbnail
414             if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
415                 throw new UseFileAsThumbnailException($this->id);
416             }
417         }
418
419         return $image->getFileThumbnail($width, $height, $crop);
420     }
421
422     public function getPath()
423     {
424         $filepath = self::path($this->filename);
425         if (!file_exists($filepath)) {
426             throw new FileNotFoundException($filepath);
427         }
428         return $filepath;
429     }
430
431     public function getUrl($prefer_local=true)
432     {
433         if ($prefer_local && !empty($this->filename)) {
434             // A locally stored file, so let's generate a URL for our instance.
435             return self::url($this->filename);
436         }
437
438         // No local filename available, return the URL we have stored
439         return $this->url;
440     }
441
442     static public function getByUrl($url)
443     {
444         $file = new File();
445         $file->urlhash = self::hashurl($url);
446         if (!$file->find(true)) {
447             throw new NoResultException($file);
448         }
449         return $file;
450     }
451
452     /**
453      * @param   string  $hashstr    String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
454      */
455     static public function getByHash($hashstr)
456     {
457         $file = new File();
458         $file->filehash = strtolower($hashstr);
459         if (!$file->find(true)) {
460             throw new NoResultException($file);
461         }
462         return $file;
463     }
464
465     public function updateUrl($url)
466     {
467         $file = File::getKV('urlhash', self::hashurl($url));
468         if ($file instanceof File) {
469             throw new ServerException('URL already exists in DB');
470         }
471         $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
472         $result = $this->query(sprintf($sql, $this->tableName(),
473                                              $this->_quote((string)self::hashurl($url)),
474                                              $this->_quote((string)$url),
475                                              $this->_quote((string)$this->urlhash)));
476         if ($result === false) {
477             common_log_db_error($this, 'UPDATE', __FILE__);
478             throw new ServerException("Could not UPDATE {$this->tableName()}.url");
479         }
480
481         return $result;
482     }
483
484     /**
485      * Blow the cache of notices that link to this URL
486      *
487      * @param boolean $last Whether to blow the "last" cache too
488      *
489      * @return void
490      */
491
492     function blowCache($last=false)
493     {
494         self::blow('file:notice-ids:%s', $this->id);
495         if ($last) {
496             self::blow('file:notice-ids:%s;last', $this->id);
497         }
498         self::blow('file:notice-count:%d', $this->id);
499     }
500
501     /**
502      * Stream of notices linking to this URL
503      *
504      * @param integer $offset   Offset to show; default is 0
505      * @param integer $limit    Limit of notices to show
506      * @param integer $since_id Since this notice
507      * @param integer $max_id   Before this notice
508      *
509      * @return array ids of notices that link to this file
510      */
511
512     function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
513     {
514         $stream = new FileNoticeStream($this);
515         return $stream->getNotices($offset, $limit, $since_id, $max_id);
516     }
517
518     function noticeCount()
519     {
520         $cacheKey = sprintf('file:notice-count:%d', $this->id);
521         
522         $count = self::cacheGet($cacheKey);
523
524         if ($count === false) {
525
526             $f2p = new File_to_post();
527
528             $f2p->file_id = $this->id;
529
530             $count = $f2p->count();
531
532             self::cacheSet($cacheKey, $count);
533         } 
534
535         return $count;
536     }
537
538     public function isLocal()
539     {
540         return !empty($this->filename);
541     }
542
543     public function delete($useWhere=false)
544     {
545         // Delete the file, if it exists locally
546         if (!empty($this->filename) && file_exists(self::path($this->filename))) {
547             $deleted = @unlink(self::path($this->filename));
548             if (!$deleted) {
549                 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
550             }
551         }
552
553         // Clear out related things in the database and filesystem, such as thumbnails
554         if (Event::handle('FileDeleteRelated', array($this))) {
555             $thumbs = new File_thumbnail();
556             $thumbs->file_id = $this->id;
557             if ($thumbs->find()) {
558                 while ($thumbs->fetch()) {
559                     $thumbs->delete();
560                 }
561             }
562
563             $f2p = new File_to_post();
564             $f2p->file_id = $this->id;
565             if ($f2p->find()) {
566                 while ($f2p->fetch()) {
567                     $f2p->delete();
568                 }
569             }
570         }
571
572         // And finally remove the entry from the database
573         return parent::delete($useWhere);
574     }
575
576     public function getTitle()
577     {
578         $title = $this->title ?: $this->filename;
579
580         return $title ?: null;
581     }
582
583     static public function hashurl($url)
584     {
585         if (empty($url)) {
586             throw new Exception('No URL provided to hash algorithm.');
587         }
588         return hash(self::URLHASH_ALG, $url);
589     }
590
591     static public function beforeSchemaUpdate()
592     {
593         $table = strtolower(get_called_class());
594         $schema = Schema::get();
595         $schemadef = $schema->getTableDef($table);
596
597         // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
598         if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
599             // We already have the urlhash field, so no need to migrate it.
600             return;
601         }
602         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
603
604         $file = new File();
605         $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)));
606         print "\nFound {$file->N} URLs with too long entries in file table\n";
607         while ($file->fetch()) {
608             // We've got a URL that is too long for our future file table
609             // so we'll cut it. We could save the original URL, but there is
610             // no guarantee it is complete anyway since the previous max was 255 chars.
611             $dupfile = new File();
612             // First we find file entries that would be duplicates of this when shortened
613             // ... and we'll just throw the dupes out the window for now! It's already so borken.
614             $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = "%1$s"', $file->shortenedurl));
615             // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
616             if ($dupfile->find(true)) {
617                 print "\nShortening url entry for $table id: {$file->id} [";
618                 $orig = clone($dupfile);
619                 $dupfile->url = $file->shortenedurl;    // make sure it's only 191 chars from now on
620                 $dupfile->update($orig);
621                 print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
622                 // only start deleting with this fetch.
623                 while($dupfile->fetch()) {
624                     print ".";
625                     $dupfile->delete();
626                 }
627                 print "]\n";
628             } else {
629                 print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
630             }
631         }
632         echo "...and now all the non-duplicates which are longer than 191 characters...\n";
633         $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');
634
635         echo "\n...now running hacky pre-schemaupdate change for $table:";
636         // We have to create a urlhash that is _not_ the primary key,
637         // transfer data and THEN run checkSchema
638         $schemadef['fields']['urlhash'] = array (
639                                               'type' => 'varchar',
640                                               'length' => 64,
641                                               'not null' => false,  // this is because when adding column, all entries will _be_ NULL!
642                                               'description' => 'sha256 of destination URL (url field)',
643                                             );
644         $schemadef['fields']['url'] = array (
645                                               'type' => 'text',
646                                               'description' => 'destination URL after following possible redirections',
647                                             );
648         unset($schemadef['unique keys']);
649         $schema->ensureTable($table, $schemadef);
650         echo "DONE.\n";
651
652         $classname = ucfirst($table);
653         $tablefix = new $classname;
654         // urlhash is hash('sha256', $url) in the File table
655         echo "Updating urlhash fields in $table table...";
656         // Maybe very MySQL specific :(
657         $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
658                             $schema->quoteIdentifier($table),
659                             'urlhash',
660                             // The line below is "result of sha256 on column `url`"
661                             'SHA2(url, 256)'));
662         echo "DONE.\n";
663         echo "Resuming core schema upgrade...";
664     }
665 }