]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
function is hashurl, variable is urlhash
[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 $mimetype;                        // varchar(50)
32     public $size;                            // int(4)
33     public $title;                           // varchar(255)
34     public $date;                            // int(4)
35     public $protected;                       // int(4)
36     public $filename;                        // varchar(255)
37     public $width;                           // int(4)
38     public $height;                          // int(4)
39     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
40
41     const URLHASH_ALG = 'sha256';
42
43     public static function schemaDef()
44     {
45         return array(
46             'fields' => array(
47                 'id' => array('type' => 'serial', 'not null' => true),
48                 'urlhash' => array('type' => 'varchar', 'length' => 64, 'description' => 'sha256 of destination URL (url field)'),
49                 'url' => array('type' => 'text', 'description' => 'destination URL after following 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' => 255, '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' => 255, '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'),
58
59                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
60             ),
61             'primary key' => array('id'),
62             'unique keys' => array(
63                 'file_urlhash_key' => array('urlhash'),
64             ),
65         );
66     }
67
68     function isProtected($url) {
69         return 'http://www.facebook.com/login.php' === $url;
70     }
71
72     /**
73      * Save a new file record.
74      *
75      * @param array $redir_data lookup data eg from File_redirection::where()
76      * @param string $given_url
77      * @return File
78      */
79     public static function saveNew(array $redir_data, $given_url) {
80
81         // I don't know why we have to keep doing this but I'm adding this last check to avoid
82         // uniqueness bugs.
83
84         $file = File::getKV('urlhash', self::hashurl($given_url));
85         
86         if (!$file instanceof File) {
87             $file = new 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();
96         }
97
98         Event::handle('EndFileSaveNew', array($file, $redir_data, $given_url));
99         assert ($file instanceof File);
100         return $file;
101     }
102
103     /**
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
110      *
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
115      *
116      * @return mixed File on success, -1 on some errors
117      *
118      * @throws ServerException on failure
119      */
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');
123         }
124
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');
128         }
129
130         $file = File::getKV('url', $given_url);
131         if (!$file instanceof File) {
132             // First check if we have a lookup trace for this URL already
133             $file_redir = File_redirection::getKV('url', $given_url);
134             if ($file_redir instanceof File_redirection) {
135                 $file = File::getKV('id', $file_redir->file_id);
136                 if (!$file instanceof File) {
137                     // File did not exist, let's clean up the File_redirection entry
138                     $file_redir->delete();
139                 }
140             }
141
142             // If we still don't have a File object, let's create one now!
143             if (!$file instanceof File) {
144                 // @fixme for new URLs this also looks up non-redirect data
145                 // such as target content type, size, etc, which we need
146                 // for File::saveNew(); so we call it even if not following
147                 // new redirects.
148                 $redir_data = File_redirection::where($given_url);
149                 if (is_array($redir_data)) {
150                     $redir_url = $redir_data['url'];
151                 } elseif (is_string($redir_data)) {
152                     $redir_url = $redir_data;
153                     $redir_data = array();
154                 } else {
155                     // TRANS: Server exception thrown when a URL cannot be processed.
156                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
157                 }
158
159                 // TODO: max field length
160                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
161                     // Save the File object based on our lookup trace
162                     $file = File::saveNew($redir_data, $given_url);
163                 } else {
164                     // This seems kind of messed up... for now skipping this part
165                     // if we're already under a redirect, so we don't go into
166                     // horrible infinite loops if we've been given an unstable
167                     // redirect (where the final destination of the first request
168                     // doesn't match what we get when we ask for it again).
169                     //
170                     // Seen in the wild with clojure.org, which redirects through
171                     // wikispaces for auth and appends session data in the URL params.
172                     $file = self::processNew($redir_url, $notice_id, /*followRedirects*/false);
173                     File_redirection::saveNew($redir_data, $file->id, $given_url);
174                 }
175             }
176
177             if (!$file instanceof File) {
178                 // This should only happen if File::saveNew somehow did not return a File object,
179                 // though we have an assert for that in case the event there might've gone wrong.
180                 // If anything else goes wrong, there should've been an exception thrown.
181                 throw new ServerException('URL processing failed without new File object');
182             }
183         }
184
185         if (!empty($notice_id)) {
186             File_to_post::processNew($file->id, $notice_id);
187         }
188         return $file;
189     }
190
191     public static function respectsQuota(Profile $scoped, $fileSize) {
192         if ($fileSize > common_config('attachments', 'file_quota')) {
193             // TRANS: Message used to be inserted as %2$s in  the text "No file may
194             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
195             // TRANS: %1$d is the number of bytes of an uploaded file.
196             $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
197
198             $fileQuota = common_config('attachments', 'file_quota');
199             // TRANS: Message given if an upload is larger than the configured maximum.
200             // TRANS: %1$d (used for plural) is the byte limit for uploads,
201             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
202             // TRANS: gettext support multiple plurals in the same message, unfortunately...
203             throw new ClientException(
204                     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.',
205                               'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
206                               $fileQuota),
207                     $fileQuota, $fileSizeText));
208         }
209
210         $file = new File;
211
212         $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'";
213         $file->query($query);
214         $file->fetch();
215         $total = $file->total + $fileSize;
216         if ($total > common_config('attachments', 'user_quota')) {
217             // TRANS: Message given if an upload would exceed user quota.
218             // TRANS: %d (number) is the user quota in bytes and is used for plural.
219             throw new ClientException(
220                     sprintf(_m('A file this large would exceed your user quota of %d byte.',
221                               'A file this large would exceed your user quota of %d bytes.',
222                               common_config('attachments', 'user_quota')),
223                     common_config('attachments', 'user_quota')));
224         }
225         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
226         $file->query($query);
227         $file->fetch();
228         $total = $file->total + $fileSize;
229         if ($total > common_config('attachments', 'monthly_quota')) {
230             // TRANS: Message given id an upload would exceed a user's monthly quota.
231             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
232             throw new ClientException(
233                     sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
234                               'A file this large would exceed your monthly quota of %d bytes.',
235                               common_config('attachments', 'monthly_quota')),
236                     common_config('attachments', 'monthly_quota')));
237         }
238         return true;
239     }
240
241     // where should the file go?
242
243     static function filename(Profile $profile, $origname, $mimetype)
244     {
245         try {
246             $ext = common_supported_mime_to_ext($mimetype);
247         } catch (Exception $e) {
248             // We don't support this mimetype, but let's guess the extension
249             $ext = substr(strrchr($mimetype, '/'), 1);
250         }
251
252         // Normalize and make the original filename more URL friendly.
253         $origname = basename($origname, ".$ext");
254         if (class_exists('Normalizer')) {
255             // http://php.net/manual/en/class.normalizer.php
256             // http://www.unicode.org/reports/tr15/
257             $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
258         }
259         $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
260
261         $nickname = $profile->getNickname();
262         $datestamp = strftime('%Y%m%d', time());
263         do {
264             // generate new random strings until we don't run into a filename collision.
265             $random = strtolower(common_confirmation_code(16));
266             $filename = "$nickname-$datestamp-$origname-$random.$ext";
267         } while (file_exists(self::path($filename)));
268         return $filename;
269     }
270
271     /**
272      * Validation for as-saved base filenames
273      */
274     static function validFilename($filename)
275     {
276         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
277     }
278
279     /**
280      * @throws ClientException on invalid filename
281      */
282     static function path($filename)
283     {
284         if (!self::validFilename($filename)) {
285             // TRANS: Client exception thrown if a file upload does not have a valid name.
286             throw new ClientException(_("Invalid filename."));
287         }
288         $dir = common_config('attachments', 'dir');
289
290         if ($dir[strlen($dir)-1] != '/') {
291             $dir .= '/';
292         }
293
294         return $dir . $filename;
295     }
296
297     static function url($filename)
298     {
299         if (!self::validFilename($filename)) {
300             // TRANS: Client exception thrown if a file upload does not have a valid name.
301             throw new ClientException(_("Invalid filename."));
302         }
303
304         if (common_config('site','private')) {
305
306             return common_local_url('getfile',
307                                 array('filename' => $filename));
308
309         }
310
311         if (StatusNet::useHTTPS()) {
312
313             $sslserver = common_config('attachments', 'sslserver');
314
315             if (empty($sslserver)) {
316                 // XXX: this assumes that background dir == site dir + /file/
317                 // not true if there's another server
318                 if (is_string(common_config('site', 'sslserver')) &&
319                     mb_strlen(common_config('site', 'sslserver')) > 0) {
320                     $server = common_config('site', 'sslserver');
321                 } else if (common_config('site', 'server')) {
322                     $server = common_config('site', 'server');
323                 }
324                 $path = common_config('site', 'path') . '/file/';
325             } else {
326                 $server = $sslserver;
327                 $path   = common_config('attachments', 'sslpath');
328                 if (empty($path)) {
329                     $path = common_config('attachments', 'path');
330                 }
331             }
332
333             $protocol = 'https';
334         } else {
335             $path = common_config('attachments', 'path');
336             $server = common_config('attachments', 'server');
337
338             if (empty($server)) {
339                 $server = common_config('site', 'server');
340             }
341
342             $ssl = common_config('attachments', 'ssl');
343
344             $protocol = ($ssl) ? 'https' : 'http';
345         }
346
347         if ($path[strlen($path)-1] != '/') {
348             $path .= '/';
349         }
350
351         if ($path[0] != '/') {
352             $path = '/'.$path;
353         }
354
355         return $protocol.'://'.$server.$path.$filename;
356     }
357
358     function getEnclosure(){
359         $enclosure = (object) array();
360         foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype') as $key) {
361             $enclosure->$key = $this->$key;
362         }
363
364         $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml');
365
366         if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
367             // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
368             // which may be enriched through oEmbed or similar (implemented as plugins)
369             Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
370         }
371         if (empty($enclosure->mimetype) || in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
372             // This means we either don't know what it is, so it can't
373             // be shown as an enclosure, or it is an HTML link which
374             // does not link to a resource with further metadata.
375             throw new ServerException('Unknown enclosure mimetype, not enough metadata');
376         }
377         return $enclosure;
378     }
379
380     /**
381      * Get the attachment's thumbnail record, if any.
382      * Make sure you supply proper 'int' typed variables (or null).
383      *
384      * @param $width  int   Max width of thumbnail in pixels. (if null, use common_config values)
385      * @param $height int   Max height of thumbnail in pixels. (if null, square-crop to $width)
386      * @param $crop   bool  Crop to the max-values' aspect ratio
387      *
388      * @return File_thumbnail
389      */
390     public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true)
391     {
392         // Get some more information about this file through our ImageFile class
393         $image = ImageFile::fromFileObject($this);
394         if ($image->animated && !common_config('thumbnail', 'animated')) {
395             // null  means "always use file as thumbnail"
396             // false means you get choice between frozen frame or original when calling getThumbnail
397             if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
398                 throw new UseFileAsThumbnailException($this->id);
399             }
400         }
401
402         if ($width === null) {
403             $width = common_config('thumbnail', 'width');
404             $height = common_config('thumbnail', 'height');
405             $crop = common_config('thumbnail', 'crop');
406         }
407
408         if ($height === null) {
409             $height = $width;
410             $crop = true;
411         }
412
413         // Get proper aspect ratio width and height before lookup
414         // We have to do it through an ImageFile object because of orientation etc.
415         // Only other solution would've been to rotate + rewrite uploaded files.
416         list($width, $height, $x, $y, $w, $h) =
417                                 $image->scaleToFit($width, $height, $crop);
418
419         $params = array('file_id'=> $this->id,
420                         'width'  => $width,
421                         'height' => $height);
422         $thumb = File_thumbnail::pkeyGet($params);
423         if ($thumb instanceof File_thumbnail) {
424             return $thumb;
425         }
426
427         // throws exception on failure to generate thumbnail
428         $outname = "thumb-{$width}x{$height}-" . $image->filename;
429         $outpath = self::path($outname);
430
431         // The boundary box for our resizing
432         $box = array('width'=>$width, 'height'=>$height,
433                      'x'=>$x,         'y'=>$y,
434                      'w'=>$w,         'h'=>$h);
435
436         // Doublecheck that parameters are sane and integers.
437         if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
438                 || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
439                 || $box['w'] < 1 || $box['x'] >= $image->width
440                 || $box['h'] < 1 || $box['y'] >= $image->height) {
441             // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
442             common_debug("Boundary box parameters for resize of {$image->filepath} : ".var_export($box,true));
443             throw new ServerException('Bad thumbnail size parameters.');
444         }
445
446         common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', $this->id, $width, $height));
447         // Perform resize and store into file
448         $image->resizeTo($outpath, $box);
449
450         // Avoid deleting the original
451         if ($image->getPath() != self::path($image->filename)) {
452             $image->unlink();
453         }
454         return File_thumbnail::saveThumbnail($this->id,
455                                       self::url($outname),
456                                       $width, $height,
457                                       $outname);
458     }
459
460     public function getPath()
461     {
462         return self::path($this->filename);
463     }
464
465     public function getUrl()
466     {
467         if (!empty($this->filename)) {
468             // A locally stored file, so let's generate a URL for our instance.
469             $url = self::url($this->filename);
470             if (self::hashurl($url) !== $this->urlhash) {
471                 // For indexing purposes, in case we do a lookup on the 'url' field.
472                 // also we're fixing possible changes from http to https, or paths
473                 $this->updateUrl($url);
474             }
475             return $url;
476         }
477
478         // No local filename available, return the URL we have stored
479         return $this->url;
480     }
481
482     static public function getByUrl($url)
483     {
484         $file = new File();
485         $file->urlhash = self::hashurl($url);
486         if (!$file->find(true)) {
487             throw new NoResultException($file);
488         }
489         return $file;
490     }
491
492     public function updateUrl($url)
493     {
494         $file = File::getKV('urlhash', self::hashurl($url));
495         if ($file instanceof File) {
496             throw new ServerException('URL already exists in DB');
497         }
498         $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
499         $result = $this->query(sprintf($sql, $this->__table,
500                                              $this->_quote((string)self::hashurl($url)),
501                                              $this->_quote((string)$url),
502                                              $this->_quote((string)$this->urlhash)));
503         if ($result === false) {
504             common_log_db_error($this, 'UPDATE', __FILE__);
505             throw new ServerException("Could not UPDATE {$this->__table}.url");
506         }
507
508         return $result;
509     }
510
511     /**
512      * Blow the cache of notices that link to this URL
513      *
514      * @param boolean $last Whether to blow the "last" cache too
515      *
516      * @return void
517      */
518
519     function blowCache($last=false)
520     {
521         self::blow('file:notice-ids:%s', $this->urlhash);
522         if ($last) {
523             self::blow('file:notice-ids:%s;last', $this->urlhash);
524         }
525         self::blow('file:notice-count:%d', $this->id);
526     }
527
528     /**
529      * Stream of notices linking to this URL
530      *
531      * @param integer $offset   Offset to show; default is 0
532      * @param integer $limit    Limit of notices to show
533      * @param integer $since_id Since this notice
534      * @param integer $max_id   Before this notice
535      *
536      * @return array ids of notices that link to this file
537      */
538
539     function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
540     {
541         $stream = new FileNoticeStream($this);
542         return $stream->getNotices($offset, $limit, $since_id, $max_id);
543     }
544
545     function noticeCount()
546     {
547         $cacheKey = sprintf('file:notice-count:%d', $this->id);
548         
549         $count = self::cacheGet($cacheKey);
550
551         if ($count === false) {
552
553             $f2p = new File_to_post();
554
555             $f2p->file_id = $this->id;
556
557             $count = $f2p->count();
558
559             self::cacheSet($cacheKey, $count);
560         } 
561
562         return $count;
563     }
564
565     public function isLocal()
566     {
567         return !empty($this->filename);
568     }
569
570     public function delete($useWhere=false)
571     {
572         // Delete the file, if it exists locally
573         if (!empty($this->filename) && file_exists(self::path($this->filename))) {
574             $deleted = @unlink(self::path($this->filename));
575             if (!$deleted) {
576                 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
577             }
578         }
579
580         // Clear out related things in the database and filesystem, such as thumbnails
581         if (Event::handle('FileDeleteRelated', array($this))) {
582             $thumbs = new File_thumbnail();
583             $thumbs->file_id = $this->id;
584             if ($thumbs->find()) {
585                 while ($thumbs->fetch()) {
586                     $thumbs->delete();
587                 }
588             }
589         }
590
591         // And finally remove the entry from the database
592         return parent::delete($useWhere);
593     }
594
595     public function getTitle()
596     {
597         $title = $this->title ?: $this->filename;
598
599         return $title ?: null;
600     }
601
602     static public function hashurl($url)
603     {
604         if (empty($url)) {
605             throw new Exception('No URL provided to hash algorithm.');
606         }
607         return hash(self::URLHASH_ALG, $url);
608     }
609
610     static public function beforeSchemaUpdate()
611     {
612         $table = strtolower(get_called_class());
613         $schema = Schema::get();
614         $schemadef = $schema->getTableDef($table);
615
616         // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
617         if (isset($schemadef['fields']['urlhash']) && in_array('file_urlhash_key', $schemadef['unique keys'])) {
618             // We already have the urlhash field, so no need to migrate it.
619             return;
620         }
621         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...\n";
622         // We have to create a urlhash that is _not_ the primary key,
623         // transfer data and THEN run checkSchema
624         $schemadef['fields']['urlhash'] = array (
625                                               'type' => 'varchar',
626                                               'length' => 64,
627                                               'description' => 'sha256 of destination URL after following redirections',
628                                             );
629         $schema->ensureTable($table, $schemadef);
630         echo "DONE.\n";
631
632         $classname = ucfirst($table);
633         $tablefix = new $classname;
634         // urlhash is hash('sha256', $url) in the File table
635         echo "Updating urlhash fields in $table table...\n";
636         // Maybe very MySQL specific :(
637         $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
638                             $schema->quoteIdentifier($table),
639                             'urlhash',
640                             // The line below is "result of sha256 on column `url`"
641                             'SHA2(url, 256)'));
642         echo "DONE.\n";
643         echo "Resuming core schema upgrade...";
644     }
645 }