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