]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/upgrade.php
File_redirection also got urlhash column
[quix0rs-gnu-social.git] / scripts / upgrade.php
1 #!/usr/bin/env php
2 <?php
3 /*
4  * StatusNet - a distributed open-source microblogging tool
5  * Copyright (C) 2008-2011 StatusNet, Inc.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
22
23 $shortoptions = 'x::';
24 $longoptions = array('extensions=');
25
26 $helptext = <<<END_OF_UPGRADE_HELP
27 php upgrade.php [options]
28 Upgrade database schema and data to latest software
29
30 END_OF_UPGRADE_HELP;
31
32 require_once INSTALLDIR.'/scripts/commandline.inc';
33
34 function main()
35 {
36     if (Event::handle('StartUpgrade')) {
37         fixupConversationURIs();
38
39         updateSchemaCore();
40         updateSchemaPlugins();
41
42         // These replace old "fixup_*" scripts
43
44         fixupNoticeRendered();
45         fixupNoticeConversation();
46         initConversation();
47         fixupGroupURI();
48         fixupFileGeometry();
49         deleteLocalFileThumbnailsWithoutFilename();
50         deleteMissingLocalFileThumbnails();
51
52         initGroupProfileId();
53         initLocalGroup();
54         initNoticeReshare();
55     
56         initSubscriptionURI();
57         initGroupMemberURI();
58
59         initProfileLists();
60
61         Event::handle('EndUpgrade');
62     }
63 }
64
65 function tableDefs()
66 {
67         $schema = array();
68         require INSTALLDIR.'/db/core.php';
69         return $schema;
70 }
71
72 function updateSchemaCore()
73 {
74     printfnq("Upgrading core schema...");
75
76     $schema = Schema::get();
77     $schemaUpdater = new SchemaUpdater($schema);
78     foreach (tableDefs() as $table => $def) {
79         preAlterFixes($schemaUpdater, $table);
80         $schemaUpdater->register($table, $def);
81     }
82     $schemaUpdater->checkSchema();
83
84     printfnq("DONE.\n");
85 }
86
87 function preAlterFixes($schemaUpdater, $table)
88 {
89     switch ($table) {
90     case 'file':
91     case 'file_redirection':
92         $schemadef = $schemaUpdater->schema->getTableDef($table);
93         if (isset($schemadef['fields']['urlhash'])) {
94             // We already have the urlhash field, so no need to migrate it.
95             break;
96         }
97         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...\n";
98         // We have to create a urlhash that is _not_ the primary key,
99         // transfer data and THEN run checkSchema
100         $schemadef['fields']['urlhash'] = array (
101                                               'type' => 'varchar',
102                                               'length' => 64,
103                                               'description' => 'sha256 of destination URL after following redirections',
104                                             );
105         $schemaUpdater->schema->ensureTable($table, $schemadef);
106         echo "DONE.\n";
107
108         $classname = ucfirst($table);
109         $tablefix = new $classname;
110         // urlhash is hash('sha256', $url) in the File table
111         echo "Updating urlhash fields in $table table...\n";
112         // Maybe very MySQL specific :(
113         $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
114                             $schemaUpdater->schema->quoteIdentifier($table),
115                             'urlhash',
116                             // The line below is "result of sha256 on column `url`"
117                             'SHA2(url, 256)'));
118         echo "DONE.\n";
119         echo "Resuming core schema upgrade...";
120         break;
121     }
122 }
123
124 function updateSchemaPlugins()
125 {
126     printfnq("Upgrading plugin schema...");
127
128     Event::handle('CheckSchema');
129
130     printfnq("DONE.\n");
131 }
132
133 function fixupNoticeRendered()
134 {
135     printfnq("Ensuring all notices have rendered HTML...");
136
137     $notice = new Notice();
138
139     $notice->whereAdd('rendered IS NULL');
140     $notice->find();
141
142     while ($notice->fetch()) {
143         $original = clone($notice);
144         $notice->rendered = common_render_content($notice->content, $notice);
145         $notice->update($original);
146     }
147
148     printfnq("DONE.\n");
149 }
150
151 function fixupNoticeConversation()
152 {
153     printfnq("Ensuring all notices have a conversation ID...");
154
155     $notice = new Notice();
156     $notice->whereAdd('conversation is null');
157     $notice->orderBy('id'); // try to get originals before replies
158     $notice->find();
159
160     while ($notice->fetch()) {
161         try {
162             $cid = null;
163     
164             $orig = clone($notice);
165     
166             if (empty($notice->reply_to)) {
167                 $notice->conversation = $notice->id;
168             } else {
169                 $reply = Notice::getKV('id', $notice->reply_to);
170
171                 if (empty($reply)) {
172                     $notice->conversation = $notice->id;
173                 } else if (empty($reply->conversation)) {
174                     $notice->conversation = $notice->id;
175                 } else {
176                     $notice->conversation = $reply->conversation;
177                 }
178         
179                 unset($reply);
180                 $reply = null;
181             }
182
183             $result = $notice->update($orig);
184
185             $orig = null;
186             unset($orig);
187         } catch (Exception $e) {
188             printv("Error setting conversation: " . $e->getMessage());
189         }
190     }
191
192     printfnq("DONE.\n");
193 }
194
195 function fixupGroupURI()
196 {
197     printfnq("Ensuring all groups have an URI...");
198
199     $group = new User_group();
200     $group->whereAdd('uri IS NULL');
201
202     if ($group->find()) {
203         while ($group->fetch()) {
204             $orig = User_group::getKV('id', $group->id);
205             $group->uri = $group->getUri();
206             $group->update($orig);
207         }
208     }
209
210     printfnq("DONE.\n");
211 }
212
213 function initConversation()
214 {
215     printfnq("Ensuring all conversations have a row in conversation table...");
216
217     $notice = new Notice();
218     $notice->query('select distinct notice.conversation from notice '.
219                    'where notice.conversation is not null '.
220                    'and not exists (select conversation.id from conversation where id = notice.conversation)');
221
222     while ($notice->fetch()) {
223
224         $id = $notice->conversation;
225
226         $uri = common_local_url('conversation', array('id' => $id));
227
228         // @fixme db_dataobject won't save our value for an autoincrement
229         // so we're bypassing the insert wrappers
230         $conv = new Conversation();
231         $sql = "insert into conversation (id,uri,created) values(%d,'%s','%s')";
232         $sql = sprintf($sql,
233                        $id,
234                        $conv->escape($uri),
235                        $conv->escape(common_sql_now()));
236         $conv->query($sql);
237     }
238
239     printfnq("DONE.\n");
240 }
241
242 function fixupConversationURIs()
243 {
244     printfnq("Ensuring all conversations have a URI...");
245
246     $conv = new Conversation();
247     $conv->whereAdd('uri IS NULL');
248
249     if ($conv->find()) {
250         $rounds = 0;
251         while ($conv->fetch()) {
252             $uri = common_local_url('conversation', array('id' => $conv->id));
253             $sql = sprintf('UPDATE conversation SET uri="%1$s" WHERE id="%2$d";',
254                             $conv->escape($uri), $conv->id);
255             $conv->query($sql);
256             if (($conv->N-++$rounds) % 500 == 0) {
257                 printfnq(sprintf(' %d items left...', $conv->N-$rounds));
258             }
259         }
260     }
261
262     printfnq("DONE.\n");
263 }
264
265 function initGroupProfileId()
266 {
267     printfnq("Ensuring all User_group entries have a Profile and profile_id...");
268
269     $group = new User_group();
270     $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)');
271     $group->find();
272
273     while ($group->fetch()) {
274         try {
275             // We must create a new, incrementally assigned profile_id
276             $profile = new Profile();
277             $profile->nickname   = $group->nickname;
278             $profile->fullname   = $group->fullname;
279             $profile->profileurl = $group->mainpage;
280             $profile->homepage   = $group->homepage;
281             $profile->bio        = $group->description;
282             $profile->location   = $group->location;
283             $profile->created    = $group->created;
284             $profile->modified   = $group->modified;
285
286             $profile->query('BEGIN');
287             $id = $profile->insert();
288             if (empty($id)) {
289                 $profile->query('ROLLBACK');
290                 throw new Exception('Profile insertion failed, profileurl: '.$profile->profileurl);
291             }
292             $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}");
293             $profile->query('COMMIT');
294
295             $profile->free();
296         } catch (Exception $e) {
297             printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage());
298         }
299     }
300
301     printfnq("DONE.\n");
302 }
303
304 function initLocalGroup()
305 {
306     printfnq("Ensuring all local user groups have a local_group...");
307
308     $group = new User_group();
309     $group->whereAdd('NOT EXISTS (select group_id from local_group where group_id = user_group.id)');
310     $group->find();
311
312     while ($group->fetch()) {
313         try {
314             // Hack to check for local groups
315             if ($group->getUri() == common_local_url('groupbyid', array('id' => $group->id))) {
316                 $lg = new Local_group();
317
318                 $lg->group_id = $group->id;
319                 $lg->nickname = $group->nickname;
320                 $lg->created  = $group->created; // XXX: common_sql_now() ?
321                 $lg->modified = $group->modified;
322
323                 $lg->insert();
324             }
325         } catch (Exception $e) {
326             printfv("Error initializing local group for {$group->nickname}:" . $e->getMessage());
327         }
328     }
329
330     printfnq("DONE.\n");
331 }
332
333 function initNoticeReshare()
334 {
335     printfnq("Ensuring all reshares have the correct verb and object-type...");
336     
337     $notice = new Notice();
338     $notice->whereAdd('repeat_of is not null');
339     $notice->whereAdd('(verb != "'.ActivityVerb::SHARE.'" OR object_type != "'.ActivityObject::ACTIVITY.'")');
340
341     if ($notice->find()) {
342         while ($notice->fetch()) {
343             try {
344                 $orig = Notice::getKV('id', $notice->id);
345                 $notice->verb = ActivityVerb::SHARE;
346                 $notice->object_type = ActivityObject::ACTIVITY;
347                 $notice->update($orig);
348             } catch (Exception $e) {
349                 printfv("Error updating verb and object_type for {$notice->id}:" . $e->getMessage());
350             }
351         }
352     }
353
354     printfnq("DONE.\n");
355 }
356
357 function initSubscriptionURI()
358 {
359     printfnq("Ensuring all subscriptions have a URI...");
360
361     $sub = new Subscription();
362     $sub->whereAdd('uri IS NULL');
363
364     if ($sub->find()) {
365         while ($sub->fetch()) {
366             try {
367                 $sub->decache();
368                 $sub->query(sprintf('update subscription '.
369                                     'set uri = "%s" '.
370                                     'where subscriber = %d '.
371                                     'and subscribed = %d',
372                                     Subscription::newURI($sub->subscriber, $sub->subscribed, $sub->created),
373                                     $sub->subscriber,
374                                     $sub->subscribed));
375             } catch (Exception $e) {
376                 common_log(LOG_ERR, "Error updated subscription URI: " . $e->getMessage());
377             }
378         }
379     }
380
381     printfnq("DONE.\n");
382 }
383
384 function initGroupMemberURI()
385 {
386     printfnq("Ensuring all group memberships have a URI...");
387
388     $mem = new Group_member();
389     $mem->whereAdd('uri IS NULL');
390
391     if ($mem->find()) {
392         while ($mem->fetch()) {
393             try {
394                 $mem->decache();
395                 $mem->query(sprintf('update group_member set uri = "%s" '.
396                                     'where profile_id = %d ' . 
397                                     'and group_id = %d ',
398                                     Group_member::newURI($mem->profile_id, $mem->group_id, $mem->created),
399                                     $mem->profile_id,
400                                     $mem->group_id));
401             } catch (Exception $e) {
402                 common_log(LOG_ERR, "Error updated membership URI: " . $e->getMessage());  
403           }
404         }
405     }
406
407     printfnq("DONE.\n");
408 }
409
410 function initProfileLists()
411 {
412     printfnq("Ensuring all profile tags have a corresponding list...");
413
414     $ptag = new Profile_tag();
415     $ptag->selectAdd();
416     $ptag->selectAdd('tagger, tag, count(*) as tagged_count');
417     $ptag->whereAdd('NOT EXISTS (SELECT tagger, tagged from profile_list '.
418                     'where profile_tag.tagger = profile_list.tagger '.
419                     'and profile_tag.tag = profile_list.tag)');
420     $ptag->groupBy('tagger, tag');
421     $ptag->orderBy('tagger, tag');
422
423     if ($ptag->find()) {
424         while ($ptag->fetch()) {
425             $plist = new Profile_list();
426
427             $plist->tagger   = $ptag->tagger;
428             $plist->tag      = $ptag->tag;
429             $plist->private  = 0;
430             $plist->created  = common_sql_now();
431             $plist->modified = $plist->created;
432             $plist->mainpage = common_local_url('showprofiletag',
433                                                 array('tagger' => $plist->getTagger()->nickname,
434                                                       'tag'    => $plist->tag));;
435
436             $plist->tagged_count     = $ptag->tagged_count;
437             $plist->subscriber_count = 0;
438
439             $plist->insert();
440
441             $orig = clone($plist);
442             // After insert since it uses auto-generated ID
443             $plist->uri      = common_local_url('profiletagbyid',
444                                         array('id' => $plist->id, 'tagger_id' => $plist->tagger));
445
446             $plist->update($orig);
447         }
448     }
449
450     printfnq("DONE.\n");
451 }
452
453 /*
454  * Added as we now store interpretd width and height in File table.
455  */
456 function fixupFileGeometry()
457 {
458     printfnq("Ensuring width and height is set for supported local File objects...");
459
460     $file = new File();
461     $file->whereAdd('filename IS NOT NULL');    // local files
462     $file->whereAdd('width IS NULL OR width = 0');
463
464     if ($file->find()) {
465         while ($file->fetch()) {
466             // Set file geometrical properties if available
467             try {
468                 $image = ImageFile::fromFileObject($file);
469             } catch (ServerException $e) {
470                 // We couldn't make out an image from the file.
471                 continue;
472             }
473             $orig = clone($file);
474             $file->width = $image->width;
475             $file->height = $image->height;
476             $file->update($orig);
477
478             // FIXME: Do this more automagically inside ImageFile or so.
479             if ($image->getPath() != $file->getPath()) {
480                 $image->unlink();
481             }
482             unset($image);
483         }
484     }
485
486     printfnq("DONE.\n");
487 }
488
489 /*
490  * File_thumbnail objects for local Files store their own filenames in the database.
491  */
492 function deleteLocalFileThumbnailsWithoutFilename()
493 {
494     printfnq("Removing all local File_thumbnail entries without filename property...");
495
496     $file = new File();
497     $file->whereAdd('filename IS NOT NULL');    // local files
498
499     if ($file->find()) {
500         // Looping through local File entries
501         while ($file->fetch()) {
502             $thumbs = new File_thumbnail();
503             $thumbs->file_id = $file->id;
504             $thumbs->whereAdd('filename IS NULL');
505             // Checking if there were any File_thumbnail entries without filename
506             if (!$thumbs->find()) {
507                 continue;
508             }
509             // deleting incomplete entry to allow regeneration
510             while ($thumbs->fetch()) {
511                 $thumbs->delete();
512             }
513         }
514     }
515
516     printfnq("DONE.\n");
517 }
518
519 /*
520  * Delete File_thumbnail entries where the referenced file does not exist.
521  */
522 function deleteMissingLocalFileThumbnails()
523 {
524     printfnq("Removing all local File_thumbnail entries without existing files...");
525
526     $thumbs = new File_thumbnail();
527     $thumbs->whereAdd('filename IS NOT NULL');  // only fill in names where they're missing
528     // Checking if there were any File_thumbnail entries without filename
529     if ($thumbs->find()) {
530         while ($thumbs->fetch()) {
531             if (!file_exists(File_thumbnail::path($thumbs->filename))) {
532                 $thumbs->delete();
533             }
534         }
535     }
536
537     printfnq("DONE.\n");
538 }
539
540 main();