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