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