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