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