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