]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Added type-hint for StartShowNoticeFormData hook
[quix0rs-gnu-social.git] / classes / File.php
1 <?php
2 /**
3  * GNU social - a federating social network
4  *
5  * Abstraction for files
6  *
7  * LICENCE: This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  * @category  Files
21  * @package   GNUsocial
22  * @author    Mikael Nordfeldth <mmn@hethane.se>
23  * @author    Miguel Dantas <biodantas@gmail.com>
24  * @copyright 2008-2009, 2019 Free Software Foundation http://fsf.org
25  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
26  * @link      https://www.gnu.org/software/social/
27  */
28
29 defined('GNUSOCIAL') || die();
30
31 /**
32  * Table Definition for file
33  */
34 class File extends Managed_DataObject
35 {
36     public $__table = 'file';                            // table name
37     public $id;                              // int(4)  primary_key not_null
38     public $urlhash;                         // varchar(64)  unique_key
39     public $url;                             // text
40     public $filehash;                        // varchar(64)     indexed
41     public $mimetype;                        // varchar(50)
42     public $size;                            // int(4)
43     public $title;                           // text()
44     public $date;                            // int(4)
45     public $protected;                       // int(4)
46     public $filename;                        // text()
47     public $width;                           // int(4)
48     public $height;                          // int(4)
49     public $modified;                        // datetime()   not_null default_CURRENT_TIMESTAMP
50
51     const URLHASH_ALG = 'sha256';
52     const FILEHASH_ALG = 'sha256';
53
54     public static function schemaDef()
55     {
56         return array(
57             'fields' => array(
58                 'id' => array('type' => 'serial', 'not null' => true),
59                 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 of destination URL (url field)'),
60                 'url' => array('type' => 'text', 'description' => 'destination URL after following possible redirections'),
61                 'filehash' => array('type' => 'varchar', 'length' => 64, 'not null' => false, 'description' => 'sha256 of the file contents, only for locally stored files of course'),
62                 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
63                 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
64                 'title' => array('type' => 'text', 'description' => 'title of resource when available'),
65                 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
66                 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
67                 'filename' => array('type' => 'text', 'description' => 'if file is stored locally (too) this is the filename'),
68                 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
69                 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
70                 'modified' => array('type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'),
71             ),
72             'primary key' => array('id'),
73             'unique keys' => array(
74                 'file_urlhash_key' => array('urlhash'),
75             ),
76             'indexes' => array(
77                 'file_filehash_idx' => array('filehash'),
78             ),
79         );
80     }
81
82     public static function isProtected($url)
83     {
84         $protected_urls_exps = array(
85             'https://www.facebook.com/login.php',
86             common_path('main/login')
87             );
88
89         foreach ($protected_urls_exps as $protected_url_exp) {
90             if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
91                 return true;
92             }
93         }
94
95         return false;
96     }
97
98     /**
99      * Save a new file record.
100      *
101      * @param array $redir_data lookup data eg from File_redirection::where()
102      * @param string $given_url
103      * @return File
104      * @throws ServerException
105      */
106     public static function saveNew(array $redir_data, $given_url)
107     {
108         $file = null;
109         try {
110             // I don't know why we have to keep doing this but we run a last check to avoid
111             // uniqueness bugs.
112             $file = File::getByUrl($given_url);
113             return $file;
114         } catch (NoResultException $e) {
115             // We don't have the file's URL since before, so let's continue.
116         }
117
118         // if the given url is an local attachment url and the id already exists, don't
119         // save a new file record. This should never happen, but let's make it foolproof
120         // FIXME: how about attachments servers?
121         $u = parse_url($given_url);
122         if (isset($u['host']) && $u['host'] === common_config('site', 'server')) {
123             $r = Router::get();
124             // Skip the / in the beginning or $r->map won't match
125             try {
126                 $args = $r->map(mb_substr($u['path'], 1));
127                 if ($args['action'] === 'attachment') {
128                     try {
129                         if (!empty($args['attachment'])) {
130                             return File::getByID($args['attachment']);
131                         } elseif ($args['filehash']) {
132                             return File::getByHash($args['filehash']);
133                         }
134                     } catch (NoResultException $e) {
135                         // apparently this link goes to us, but is _not_ an existing attachment (File) ID?
136                     }
137                 }
138             } catch (Exception $e) {
139                 // Some other exception was thrown from $r->map, likely a
140                 // ClientException (404) because of some malformed link to
141                 // our own instance. It's still a valid URL however, so we
142                 // won't abort anything... I noticed this when linking:
143                 // https://social.umeahackerspace.se/mmn/foaf' (notice the
144                 // apostrophe in the end, making it unrecognizable for our
145                 // URL routing.
146                 // That specific issue (the apostrophe being part of a link
147                 // is something that may or may not have been fixed since,
148                 // in lib/util.php in common_replace_urls_callback().
149             }
150         }
151
152         $file = new File;
153         $file->url = $given_url;
154         if (!empty($redir_data['protected'])) {
155             $file->protected = $redir_data['protected'];
156         }
157         if (!empty($redir_data['title'])) {
158             $file->title = $redir_data['title'];
159         }
160         if (!empty($redir_data['type'])) {
161             $file->mimetype = $redir_data['type'];
162         }
163         if (!empty($redir_data['size'])) {
164             $file->size = intval($redir_data['size']);
165         }
166         if (isset($redir_data['time']) && $redir_data['time'] > 0) {
167             $file->date = intval($redir_data['time']);
168         }
169         $file->saveFile();
170         return $file;
171     }
172
173     public function saveFile()
174     {
175         $this->urlhash = self::hashurl($this->url);
176
177         if (!Event::handle('StartFileSaveNew', array(&$this))) {
178             throw new ServerException('File not saved due to an aborted StartFileSaveNew event.');
179         }
180
181         $this->id = $this->insert();
182
183         if ($this->id === false) {
184             throw new ServerException('File/URL metadata could not be saved to the database.');
185         }
186
187         Event::handle('EndFileSaveNew', array($this));
188     }
189
190     /**
191      * Go look at a URL and possibly save data about it if it's new:
192      * - follow redirect chains and store them in file_redirection
193      * - if a thumbnail is available, save it in file_thumbnail
194      * - save file record with basic info
195      * - optionally save a file_to_post record
196      * - return the File object with the full reference
197      *
198      * @param string $given_url the URL we're looking at
199      * @param Notice $notice (optional)
200      * @param bool $followRedirects defaults to true
201      *
202      * @return mixed File on success, -1 on some errors
203      *
204      * @throws ServerException on failure
205      */
206     public static function processNew($given_url, Notice $notice=null, $followRedirects=true)
207     {
208         if (empty($given_url)) {
209             throw new ServerException('No given URL to process');
210         }
211
212         $given_url = File_redirection::_canonUrl($given_url);
213         if (empty($given_url)) {
214             throw new ServerException('No canonical URL from given URL to process');
215         }
216
217         $redir = File_redirection::where($given_url);
218         try {
219             $file = $redir->getFile();
220         } catch (EmptyPkeyValueException $e) {
221             common_log(LOG_ERR, 'File_redirection::where gave object with empty file_id for given_url '._ve($given_url));
222             throw new ServerException('URL processing failed without new File object');
223         } catch (NoResultException $e) {
224             // This should not happen
225             common_log(LOG_ERR, 'File_redirection after discovery could still not return a File object.');
226             throw new ServerException('URL processing failed without new File object');
227         }
228
229         if ($notice instanceof Notice) {
230             File_to_post::processNew($file, $notice);
231         }
232
233         return $file;
234     }
235
236     public static function respectsQuota(Profile $scoped, $fileSize)
237     {
238         if ($fileSize > common_config('attachments', 'file_quota')) {
239             // TRANS: Message used to be inserted as %2$s in  the text "No file may
240             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
241             // TRANS: %1$d is the number of bytes of an uploaded file.
242             $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);
243
244             $fileQuota = common_config('attachments', 'file_quota');
245             // TRANS: Message given if an upload is larger than the configured maximum.
246             // TRANS: %1$d (used for plural) is the byte limit for uploads,
247             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
248             // TRANS: gettext support multiple plurals in the same message, unfortunately...
249             throw new ClientException(
250                 sprintf(
251                         _m(
252                         'No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
253                         'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
254                         $fileQuota
255                     ),
256                         $fileQuota,
257                         $fileSizeText
258                     )
259             );
260         }
261
262         $file = new File;
263
264         $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'";
265         $file->query($query);
266         $file->fetch();
267         $total = $file->total + $fileSize;
268         if ($total > common_config('attachments', 'user_quota')) {
269             // TRANS: Message given if an upload would exceed user quota.
270             // TRANS: %d (number) is the user quota in bytes and is used for plural.
271             throw new ClientException(
272                 sprintf(
273                         _m(
274                         'A file this large would exceed your user quota of %d byte.',
275                         'A file this large would exceed your user quota of %d bytes.',
276                         common_config('attachments', 'user_quota')
277                     ),
278                         common_config('attachments', 'user_quota')
279                     )
280             );
281         }
282         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
283         $file->query($query);
284         $file->fetch();
285         $total = $file->total + $fileSize;
286         if ($total > common_config('attachments', 'monthly_quota')) {
287             // TRANS: Message given id an upload would exceed a user's monthly quota.
288             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
289             throw new ClientException(
290                 sprintf(
291                         _m(
292                         'A file this large would exceed your monthly quota of %d byte.',
293                         'A file this large would exceed your monthly quota of %d bytes.',
294                         common_config('attachments', 'monthly_quota')
295                     ),
296                         common_config('attachments', 'monthly_quota')
297                     )
298             );
299         }
300         return true;
301     }
302
303     public function getFilename()
304     {
305         return self::tryFilename($this->filename);
306     }
307
308     public function getSize()
309     {
310         return intval($this->size);
311     }
312
313     // where should the file go?
314
315     public static function filename(Profile $profile, $origname, $mimetype)
316     {
317         $ext = self::guessMimeExtension($mimetype, $origname);
318
319         // Normalize and make the original filename more URL friendly.
320         $origname = basename($origname, ".$ext");
321         if (class_exists('Normalizer')) {
322             // http://php.net/manual/en/class.normalizer.php
323             // http://www.unicode.org/reports/tr15/
324             $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
325         }
326         $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
327
328         $nickname = $profile->getNickname();
329         $datestamp = strftime('%Y%m%d', time());
330         do {
331             // generate new random strings until we don't run into a filename collision.
332             $random = strtolower(common_confirmation_code(16));
333             $filename = "$nickname-$datestamp-$origname-$random.$ext";
334         } while (file_exists(self::path($filename)));
335         return $filename;
336     }
337
338     /**
339      * @param string $filename
340      * @return string|bool Value from the 'extblacklist' array, in the config
341      */
342     public static function getSafeExtension(string $filename) {
343         if (preg_match('/^.+?\.([A-Za-z0-9]+)$/', $filename, $matches) === 1) {
344             // we matched on a file extension, so let's see if it means something.
345             $ext = mb_strtolower($matches[1]);
346             $blacklist = common_config('attachments', 'extblacklist');
347             // If we got an extension from $filename we want to check if it's in a blacklist
348             // so we avoid people uploading restricted files
349             if (array_key_exists($ext, $blacklist)) {
350                 if (!is_string($blacklist[$ext])) {
351                     // Blocked
352                     return false;
353                 }
354                 // return a safe replacement extension ('php' => 'phps' for example)
355                 return $blacklist[$ext];
356             } else {
357                 // the attachment extension based on its filename was not blacklisted so it's ok to use it
358                 return $ext;
359             }
360         } else {
361             // No extension
362             return null;
363         }
364     }
365
366     /**
367      * @param $mimetype string The mimetype we've discovered for this file.
368      * @param $filename string An optional filename which we can use on failure.
369      * @return mixed|string
370      * @throws ClientException
371      */
372     public static function guessMimeExtension($mimetype, $filename=null)
373     {
374         try {
375             // first see if we know the extension for our mimetype
376             $ext = common_supported_mime_to_ext($mimetype);
377             // we do, so use it!
378             return $ext;
379         } catch (UnknownMimeExtensionException $e) {
380             // We don't know the extension for this mimetype, but let's guess.
381             // If we can't recognize the extension from the MIME, we try
382             // to guess based on filename, if one was supplied.
383             if (!is_null($filename)) {
384                 $ext = getSafeExtension($filename);
385                 if ($ext === false) {
386                     // we don't have a safe replacement extension
387                     throw new ClientException(_('Blacklisted file extension.'));
388                 } else {
389                     return $ext;
390                 }
391             }
392         } catch (Exception $e) {
393             common_log(LOG_INFO, 'Problem when figuring out extension for mimetype: '._ve($e));
394         }
395
396         // If nothing else has given us a result, try to extract it from
397         // the mimetype value (this turns .jpg to .jpeg for example...)
398         $matches = array();
399         // Will get jpeg from image/jpeg as well as json from application/jrd+json
400         if (!preg_match('/[\/+-\.]([a-z0-9]+)/', mb_strtolower($mimetype), $matches)) {
401             throw new Exception("Malformed mimetype: {$mimetype}");
402         }
403         return mb_strtolower($matches[1]);
404     }
405
406     /**
407      * Validation for as-saved base filenames
408      * @param $filename
409      * @return false|int
410      */
411     public static function validFilename($filename)
412     {
413         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
414     }
415
416     public static function tryFilename($filename)
417     {
418         if (!self::validFilename($filename)) {
419             throw new InvalidFilenameException($filename);
420         }
421         // if successful, return the filename for easy if-statementing
422         return $filename;
423     }
424
425     /**
426      * @param $filename
427      * @return string
428      * @throws InvalidFilenameException
429      */
430     public static function path($filename)
431     {
432         self::tryFilename($filename);
433
434         $dir = common_config('attachments', 'dir');
435
436         if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
437             $dir .= DIRECTORY_SEPARATOR;
438         }
439
440         return $dir . $filename;
441     }
442
443     public static function url($filename)
444     {
445         self::tryFilename($filename);
446
447         if (common_config('site', 'private')) {
448             return common_local_url(
449                 'getfile',
450                 array('filename' => $filename)
451             );
452         }
453
454         if (GNUsocial::useHTTPS()) {
455             $sslserver = common_config('attachments', 'sslserver');
456
457             if (empty($sslserver)) {
458                 // XXX: this assumes that background dir == site dir + /file/
459                 // not true if there's another server
460                 if (is_string(common_config('site', 'sslserver')) &&
461                     mb_strlen(common_config('site', 'sslserver')) > 0) {
462                     $server = common_config('site', 'sslserver');
463                 } elseif (common_config('site', 'server')) {
464                     $server = common_config('site', 'server');
465                 }
466                 $path = common_config('site', 'path') . '/file/';
467             } else {
468                 $server = $sslserver;
469                 $path   = common_config('attachments', 'sslpath');
470                 if (empty($path)) {
471                     $path = common_config('attachments', 'path');
472                 }
473             }
474
475             $protocol = 'https';
476         } else {
477             $path = common_config('attachments', 'path');
478             $server = common_config('attachments', 'server');
479
480             if (empty($server)) {
481                 $server = common_config('site', 'server');
482             }
483
484             $ssl = common_config('attachments', 'ssl');
485
486             $protocol = ($ssl) ? 'https' : 'http';
487         }
488
489         if ($path[strlen($path)-1] != '/') {
490             $path .= '/';
491         }
492
493         if ($path[0] != '/') {
494             $path = '/'.$path;
495         }
496
497         return $protocol.'://'.$server.$path.$filename;
498     }
499
500     public static $_enclosures = array();
501
502     public function getEnclosure()
503     {
504         if (isset(self::$_enclosures[$this->getID()])) {
505             return self::$_enclosures[$this->getID()];
506         }
507
508         $enclosure = (object) array();
509         foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype', 'width', 'height') as $key) {
510             if ($this->$key !== '') {
511                 $enclosure->$key = $this->$key;
512             }
513         }
514
515         $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml', 'text/html');
516
517         if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
518             // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
519             // which may be enriched through oEmbed or similar (implemented as plugins)
520             Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
521         }
522         if (empty($enclosure->mimetype)) {
523             // This means we either don't know what it is, so it can't
524             // be shown as an enclosure, or it is an HTML link which
525             // does not link to a resource with further metadata.
526             throw new ServerException('Unknown enclosure mimetype, not enough metadata');
527         }
528
529         self::$_enclosures[$this->getID()] = $enclosure;
530         return $enclosure;
531     }
532
533     public function hasThumbnail()
534     {
535         try {
536             $this->getThumbnail();
537         } catch (Exception $e) {
538             return false;
539         }
540         return true;
541     }
542
543     /**
544      * Get the attachment's thumbnail record, if any.
545      * Make sure you supply proper 'int' typed variables (or null).
546      *
547      * @param $width  int   Max width of thumbnail in pixels. (if null, use common_config values)
548      * @param $height int   Max height of thumbnail in pixels. (if null, square-crop to $width)
549      * @param $crop   bool  Crop to the max-values' aspect ratio
550      * @param $force_still  bool    Don't allow fallback to showing original (such as animated GIF)
551      * @param $upscale      mixed   Whether or not to scale smaller images up to larger thumbnail sizes. (null = site default)
552      *
553      * @return File_thumbnail
554      *
555      * @throws UseFileAsThumbnailException  if the file is considered an image itself and should be itself as thumbnail
556      * @throws UnsupportedMediaException    if, despite trying, we can't understand how to make a thumbnail for this format
557      * @throws ServerException              on various other errors
558      */
559     public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true, $upscale=null)
560     {
561         // Get some more information about this file through our ImageFile class
562         $image = ImageFile::fromFileObject($this);
563         if ($image->animated && !common_config('thumbnail', 'animated')) {
564             // null  means "always use file as thumbnail"
565             // false means you get choice between frozen frame or original when calling getThumbnail
566             if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
567                 try {
568                     // remote files with animated GIFs as thumbnails will match this
569                     return File_thumbnail::byFile($this);
570                 } catch (NoResultException $e) {
571                     // and if it's not a remote file, it'll be safe to use the locally stored File
572                     throw new UseFileAsThumbnailException($this);
573                 }
574             }
575         }
576
577         return $image->getFileThumbnail(
578             $width,
579             $height,
580             $crop,
581             !is_null($upscale) ? $upscale : common_config('thumbnail', 'upscale')
582         );
583     }
584
585     public function getPath()
586     {
587         $filepath = self::path($this->filename);
588         if (!file_exists($filepath)) {
589             throw new FileNotFoundException($filepath);
590         }
591         return $filepath;
592     }
593
594     /**
595      * Returns the path to either a file, or it's thumbnail if the file doesn't exist.
596      * This is useful in case the original file is deleted, or, as is the case for Embed
597      * thumbnails, we only have a thumbnail and not a file
598      * @return string Path
599      * @throws FileNotFoundException
600      * @throws FileNotStoredLocallyException
601      * @throws InvalidFilenameException
602      * @throws ServerException
603      */
604     public function getFileOrThumbnailPath($thumbnail = null) : string
605     {
606         if (!empty($thumbnail)) {
607             return $thumbnail->getPath();
608         }
609         if (!empty($this->filename)) {
610             $filepath = self::path($this->filename);
611             if (file_exists($filepath)) {
612                 return $filepath;
613             } else {
614                 throw new FileNotFoundException($filepath);
615             }
616         } else {
617             try {
618                 return File_thumbnail::byFile($this, true)->getPath();
619             } catch (NoResultException $e) {
620                 // File not stored locally
621                 throw new FileNotStoredLocallyException($this);
622             }
623         }
624     }
625
626     /**
627      * Return the mime type of the thumbnail if we have it, or, if not, of the File
628      * @return string
629      * @throws FileNotFoundException
630      * @throws NoResultException
631      * @throws ServerException
632      * @throws UnsupportedMediaException
633      */
634     public function getFileOrThumbnailMimetype($thumbnail = null) : string
635     {
636         if (!empty($thumbnail)) {
637             $filepath = $thumbnail->getPath();
638         } elseif (!empty($this->filename)) {
639             return $this->mimetype;
640         } else {
641             $filepath = File_thumbnail::byFile($this, true)->getPath();
642         }
643
644         $info = @getimagesize($filepath);
645         if ($info !== false) {
646             return $info['mime'];
647         } else {
648             throw new UnsupportedMediaException(_("Thumbnail is not an image."));
649         }
650     }
651
652     /**
653      * Return the size of the thumbnail if we have it, or, if not, of the File
654      * @return int
655      * @throws FileNotFoundException
656      * @throws NoResultException
657      * @throws ServerException
658      */
659     public function getFileOrThumbnailSize($thumbnail = null) : int
660     {
661         if (!empty($thumbnail)) {
662             return filesize($thumbnail->getPath());
663         } elseif (!empty($this->filename)) {
664             return $this->size;
665         } else {
666             return filesize(File_thumbnail::byFile($this)->getPath());
667         }
668     }
669
670     public function getAttachmentUrl()
671     {
672         return common_local_url('attachment', array('attachment'=>$this->getID()));
673     }
674
675     public function getAttachmentDownloadUrl()
676     {
677         return common_local_url('attachment_download', array('attachment'=>$this->getID()));
678     }
679
680     public function getAttachmentViewUrl()
681     {
682         return common_local_url('attachment_view', array('attachment'=>$this->getID()));
683     }
684
685     /**
686      * @param mixed $use_local true means require local, null means prefer local, false means use whatever is stored
687      * @return string
688      * @throws FileNotStoredLocallyException
689      */
690     public function getUrl($use_local=null)
691     {
692         if ($use_local !== false) {
693             if (is_string($this->filename) || !empty($this->filename)) {
694                 // A locally stored file, so let's generate a URL for our instance.
695                 return $this->getAttachmentViewUrl();
696             }
697             if ($use_local) {
698                 // if the file wasn't stored locally (has filename) and we require a local URL
699                 throw new FileNotStoredLocallyException($this);
700             }
701         }
702
703
704         // No local filename available, return the URL we have stored
705         return $this->url;
706     }
707
708     public static function getByUrl($url)
709     {
710         $file = new File();
711         $file->urlhash = self::hashurl($url);
712         if (!$file->find(true)) {
713             throw new NoResultException($file);
714         }
715         return $file;
716     }
717
718     /**
719      * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
720      * @return File
721      * @throws NoResultException
722      */
723     public static function getByHash($hashstr)
724     {
725         $file = new File();
726         $file->filehash = strtolower($hashstr);
727         if (!$file->find(true)) {
728             throw new NoResultException($file);
729         }
730         return $file;
731     }
732
733     public function updateUrl($url)
734     {
735         $file = File::getKV('urlhash', self::hashurl($url));
736         if ($file instanceof File) {
737             throw new ServerException('URL already exists in DB');
738         }
739         $sql = 'UPDATE %1$s SET urlhash=%2$s, url=%3$s WHERE urlhash=%4$s;';
740         $result = $this->query(sprintf(
741             $sql,
742             $this->tableName(),
743             $this->_quote((string)self::hashurl($url)),
744             $this->_quote((string)$url),
745             $this->_quote((string)$this->urlhash)
746         ));
747         if ($result === false) {
748             common_log_db_error($this, 'UPDATE', __FILE__);
749             throw new ServerException("Could not UPDATE {$this->tableName()}.url");
750         }
751
752         return $result;
753     }
754
755     /**
756      * Blow the cache of notices that link to this URL
757      *
758      * @param boolean $last Whether to blow the "last" cache too
759      *
760      * @return void
761      */
762
763     public function blowCache($last=false)
764     {
765         self::blow('file:notice-ids:%s', $this->id);
766         if ($last) {
767             self::blow('file:notice-ids:%s;last', $this->id);
768         }
769         self::blow('file:notice-count:%d', $this->id);
770     }
771
772     /**
773      * Stream of notices linking to this URL
774      *
775      * @param integer $offset   Offset to show; default is 0
776      * @param integer $limit    Limit of notices to show
777      * @param integer $since_id Since this notice
778      * @param integer $max_id   Before this notice
779      *
780      * @return array ids of notices that link to this file
781      */
782
783     public function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
784     {
785         // FIXME: Try to get the Profile::current() here in some other way to avoid mixing
786         // the current session user with possibly background/queue processing.
787         $stream = new FileNoticeStream($this, Profile::current());
788         return $stream->getNotices($offset, $limit, $since_id, $max_id);
789     }
790
791     public function noticeCount()
792     {
793         $cacheKey = sprintf('file:notice-count:%d', $this->id);
794         
795         $count = self::cacheGet($cacheKey);
796
797         if ($count === false) {
798             $f2p = new File_to_post();
799
800             $f2p->file_id = $this->id;
801
802             $count = $f2p->count();
803
804             self::cacheSet($cacheKey, $count);
805         }
806
807         return $count;
808     }
809
810     public function isLocal()
811     {
812         return !empty($this->filename);
813     }
814
815     public function delete($useWhere=false)
816     {
817         // Delete the file, if it exists locally
818         if (!empty($this->filename) && file_exists(self::path($this->filename))) {
819             $deleted = @unlink(self::path($this->filename));
820             if (!$deleted) {
821                 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
822             }
823         }
824
825         // Clear out related things in the database and filesystem, such as thumbnails
826         if (Event::handle('FileDeleteRelated', array($this))) {
827             $thumbs = new File_thumbnail();
828             $thumbs->file_id = $this->id;
829             if ($thumbs->find()) {
830                 while ($thumbs->fetch()) {
831                     $thumbs->delete();
832                 }
833             }
834
835             $f2p = new File_to_post();
836             $f2p->file_id = $this->id;
837             if ($f2p->find()) {
838                 while ($f2p->fetch()) {
839                     $f2p->delete();
840                 }
841             }
842         }
843
844         // And finally remove the entry from the database
845         return parent::delete($useWhere);
846     }
847
848     public function getTitle()
849     {
850         $title = $this->title ?: MediaFile::getDisplayName($this);
851
852         return $title ?: null;
853     }
854
855     public function setTitle($title)
856     {
857         $orig = clone($this);
858         $this->title = mb_strlen($title) > 0 ? $title : null;
859         return $this->update($orig);
860     }
861
862     public static function hashurl($url)
863     {
864         if (empty($url)) {
865             throw new Exception('No URL provided to hash algorithm.');
866         }
867         return hash(self::URLHASH_ALG, $url);
868     }
869
870     public static function beforeSchemaUpdate()
871     {
872         $table = strtolower(get_called_class());
873         $schema = Schema::get();
874         $schemadef = $schema->getTableDef($table);
875
876         // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
877         if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
878             // We already have the urlhash field, so no need to migrate it.
879             return;
880         }
881         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
882
883         $file = new File();
884         $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)));
885         print "\nFound {$file->N} URLs with too long entries in file table\n";
886         while ($file->fetch()) {
887             // We've got a URL that is too long for our future file table
888             // so we'll cut it. We could save the original URL, but there is
889             // no guarantee it is complete anyway since the previous max was 255 chars.
890             $dupfile = new File();
891             // First we find file entries that would be duplicates of this when shortened
892             // ... and we'll just throw the dupes out the window for now! It's already so borken.
893             $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = %1$s', $dupfile->_quote($file->shortenedurl)));
894             // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
895             if ($dupfile->find(true)) {
896                 print "\nShortening url entry for $table id: {$file->id} [";
897                 $orig = clone($dupfile);
898                 $origurl = $dupfile->url;   // save for logging purposes
899                 $dupfile->url = $file->shortenedurl;    // make sure it's only 191 chars from now on
900                 $dupfile->update($orig);
901                 print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
902                 // only start deleting with this fetch.
903                 while ($dupfile->fetch()) {
904                     common_log(LOG_INFO, sprintf('Deleting duplicate File entry of %1$d: %2$d (original URL: %3$s collides with these first 191 characters: %4$s', $dupfile->id, $file->id, $origurl, $file->shortenedurl));
905                     print ".";
906                     $dupfile->delete();
907                 }
908                 print "]\n";
909             } else {
910                 print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
911             }
912         }
913         echo "...and now all the non-duplicates which are longer than 191 characters...\n";
914         $file->query('UPDATE file SET url=LEFT(url, 191) WHERE LENGTH(url)>191');
915
916         echo "\n...now running hacky pre-schemaupdate change for $table:";
917         // We have to create a urlhash that is _not_ the primary key,
918         // transfer data and THEN run checkSchema
919         $schemadef['fields']['urlhash'] = array(
920                                               'type' => 'varchar',
921                                               'length' => 64,
922                                               'not null' => false,  // this is because when adding column, all entries will _be_ NULL!
923                                               'description' => 'sha256 of destination URL (url field)',
924                                             );
925         $schemadef['fields']['url'] = array(
926                                               'type' => 'text',
927                                               'description' => 'destination URL after following possible redirections',
928                                             );
929         unset($schemadef['unique keys']);
930         $schema->ensureTable($table, $schemadef);
931         echo "DONE.\n";
932
933         $classname = ucfirst($table);
934         $tablefix = new $classname;
935         // urlhash is hash('sha256', $url) in the File table
936         echo "Updating urlhash fields in $table table...";
937         // Maybe very MySQL specific :(
938         $tablefix->query(sprintf(
939             'UPDATE %1$s SET %2$s=%3$s;',
940             $schema->quoteIdentifier($table),
941             'urlhash',
942                             // The line below is "result of sha256 on column `url`"
943                             'SHA2(url, 256)'
944         ));
945         echo "DONE.\n";
946         echo "Resuming core schema upgrade...";
947     }
948 }