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