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