]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/upgrade.php
Merge branch 'nightly' into file_urlhash
[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         $schemadef = $schemaUpdater->schema->getTableDef($table);
92         if (isset($schemadef['fields']['urlhash'])) {
93             // We already have the urlhash field, so no need to migrate it.
94             break;
95         }
96         printfnq("\nFound old $table table, upgrading it to contain 'urlhash' field...\n");
97         // We have to create a urlhash that is _not_ the primary key,
98         // transfer data and THEN run checkSchema
99         $schemadef['fields']['urlhash'] = array (
100                                               'type' => 'varchar',
101                                               'length' => 64,
102                                               'description' => 'sha256 of destination URL after following redirections',
103                                             );
104         $schemaUpdater->schema->ensureTable($table, $schemadef);
105         printfnq("DONE.\n");
106
107         $filefix = new File();
108         // urlhash is hash('sha256', $url) in the File table
109         printfnq("Updating urlhash fields in $table table...\n");
110         $filefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
111                             $schemaUpdater->schema->quoteIdentifier($table),
112                             'urlhash',
113                             // The line below is "result of sha256 on column `url`"
114                             'SHA2(url, 256)'));
115         printfnq("DONE.\n");
116         printfnq("Resuming core schema upgrade...");
117         break;
118     }
119 }
120
121 function updateSchemaPlugins()
122 {
123     printfnq("Upgrading plugin schema...");
124
125     Event::handle('CheckSchema');
126
127     printfnq("DONE.\n");
128 }
129
130 function fixupNoticeRendered()
131 {
132     printfnq("Ensuring all notices have rendered HTML...");
133
134     $notice = new Notice();
135
136     $notice->whereAdd('rendered IS NULL');
137     $notice->find();
138
139     while ($notice->fetch()) {
140         $original = clone($notice);
141         $notice->rendered = common_render_content($notice->content, $notice);
142         $notice->update($original);
143     }
144
145     printfnq("DONE.\n");
146 }
147
148 function fixupNoticeConversation()
149 {
150     printfnq("Ensuring all notices have a conversation ID...");
151
152     $notice = new Notice();
153     $notice->whereAdd('conversation is null');
154     $notice->orderBy('id'); // try to get originals before replies
155     $notice->find();
156
157     while ($notice->fetch()) {
158         try {
159             $cid = null;
160     
161             $orig = clone($notice);
162     
163             if (empty($notice->reply_to)) {
164                 $notice->conversation = $notice->id;
165             } else {
166                 $reply = Notice::getKV('id', $notice->reply_to);
167
168                 if (empty($reply)) {
169                     $notice->conversation = $notice->id;
170                 } else if (empty($reply->conversation)) {
171                     $notice->conversation = $notice->id;
172                 } else {
173                     $notice->conversation = $reply->conversation;
174                 }
175         
176                 unset($reply);
177                 $reply = null;
178             }
179
180             $result = $notice->update($orig);
181
182             $orig = null;
183             unset($orig);
184         } catch (Exception $e) {
185             printv("Error setting conversation: " . $e->getMessage());
186         }
187     }
188
189     printfnq("DONE.\n");
190 }
191
192 function fixupGroupURI()
193 {
194     printfnq("Ensuring all groups have an URI...");
195
196     $group = new User_group();
197     $group->whereAdd('uri IS NULL');
198
199     if ($group->find()) {
200         while ($group->fetch()) {
201             $orig = User_group::getKV('id', $group->id);
202             $group->uri = $group->getUri();
203             $group->update($orig);
204         }
205     }
206
207     printfnq("DONE.\n");
208 }
209
210 function initConversation()
211 {
212     printfnq("Ensuring all conversations have a row in conversation table...");
213
214     $notice = new Notice();
215     $notice->query('select distinct notice.conversation from notice '.
216                    'where notice.conversation is not null '.
217                    'and not exists (select conversation.id from conversation where id = notice.conversation)');
218
219     while ($notice->fetch()) {
220
221         $id = $notice->conversation;
222
223         $uri = common_local_url('conversation', array('id' => $id));
224
225         // @fixme db_dataobject won't save our value for an autoincrement
226         // so we're bypassing the insert wrappers
227         $conv = new Conversation();
228         $sql = "insert into conversation (id,uri,created) values(%d,'%s','%s')";
229         $sql = sprintf($sql,
230                        $id,
231                        $conv->escape($uri),
232                        $conv->escape(common_sql_now()));
233         $conv->query($sql);
234     }
235
236     printfnq("DONE.\n");
237 }
238
239 function fixupConversationURIs()
240 {
241     printfnq("Ensuring all conversations have a URI...");
242
243     $conv = new Conversation();
244     $conv->whereAdd('uri IS NULL');
245
246     if ($conv->find()) {
247         $rounds = 0;
248         while ($conv->fetch()) {
249             $uri = common_local_url('conversation', array('id' => $conv->id));
250             $sql = sprintf('UPDATE conversation SET uri="%1$s" WHERE id="%2$d";',
251                             $conv->escape($uri), $conv->id);
252             $conv->query($sql);
253             if (($conv->N-++$rounds) % 500 == 0) {
254                 printfnq(sprintf(' %d items left...', $conv->N-$rounds));
255             }
256         }
257     }
258
259     printfnq("DONE.\n");
260 }
261
262 function initGroupProfileId()
263 {
264     printfnq("Ensuring all User_group entries have a Profile and profile_id...");
265
266     $group = new User_group();
267     $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)');
268     $group->find();
269
270     while ($group->fetch()) {
271         try {
272             // We must create a new, incrementally assigned profile_id
273             $profile = new Profile();
274             $profile->nickname   = $group->nickname;
275             $profile->fullname   = $group->fullname;
276             $profile->profileurl = $group->mainpage;
277             $profile->homepage   = $group->homepage;
278             $profile->bio        = $group->description;
279             $profile->location   = $group->location;
280             $profile->created    = $group->created;
281             $profile->modified   = $group->modified;
282
283             $profile->query('BEGIN');
284             $id = $profile->insert();
285             if (empty($id)) {
286                 $profile->query('ROLLBACK');
287                 throw new Exception('Profile insertion failed, profileurl: '.$profile->profileurl);
288             }
289             $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}");
290             $profile->query('COMMIT');
291
292             $profile->free();
293         } catch (Exception $e) {
294             printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage());
295         }
296     }
297
298     printfnq("DONE.\n");
299 }
300
301 function initLocalGroup()
302 {
303     printfnq("Ensuring all local user groups have a local_group...");
304
305     $group = new User_group();
306     $group->whereAdd('NOT EXISTS (select group_id from local_group where group_id = user_group.id)');
307     $group->find();
308
309     while ($group->fetch()) {
310         try {
311             // Hack to check for local groups
312             if ($group->getUri() == common_local_url('groupbyid', array('id' => $group->id))) {
313                 $lg = new Local_group();
314
315                 $lg->group_id = $group->id;
316                 $lg->nickname = $group->nickname;
317                 $lg->created  = $group->created; // XXX: common_sql_now() ?
318                 $lg->modified = $group->modified;
319
320                 $lg->insert();
321             }
322         } catch (Exception $e) {
323             printfv("Error initializing local group for {$group->nickname}:" . $e->getMessage());
324         }
325     }
326
327     printfnq("DONE.\n");
328 }
329
330 function initNoticeReshare()
331 {
332     printfnq("Ensuring all reshares have the correct verb and object-type...");
333     
334     $notice = new Notice();
335     $notice->whereAdd('repeat_of is not null');
336     $notice->whereAdd('(verb != "'.ActivityVerb::SHARE.'" OR object_type != "'.ActivityObject::ACTIVITY.'")');
337
338     if ($notice->find()) {
339         while ($notice->fetch()) {
340             try {
341                 $orig = Notice::getKV('id', $notice->id);
342                 $notice->verb = ActivityVerb::SHARE;
343                 $notice->object_type = ActivityObject::ACTIVITY;
344                 $notice->update($orig);
345             } catch (Exception $e) {
346                 printfv("Error updating verb and object_type for {$notice->id}:" . $e->getMessage());
347             }
348         }
349     }
350
351     printfnq("DONE.\n");
352 }
353
354 function initSubscriptionURI()
355 {
356     printfnq("Ensuring all subscriptions have a URI...");
357
358     $sub = new Subscription();
359     $sub->whereAdd('uri IS NULL');
360
361     if ($sub->find()) {
362         while ($sub->fetch()) {
363             try {
364                 $sub->decache();
365                 $sub->query(sprintf('update subscription '.
366                                     'set uri = "%s" '.
367                                     'where subscriber = %d '.
368                                     'and subscribed = %d',
369                                     Subscription::newURI($sub->subscriber, $sub->subscribed, $sub->created),
370                                     $sub->subscriber,
371                                     $sub->subscribed));
372             } catch (Exception $e) {
373                 common_log(LOG_ERR, "Error updated subscription URI: " . $e->getMessage());
374             }
375         }
376     }
377
378     printfnq("DONE.\n");
379 }
380
381 function initGroupMemberURI()
382 {
383     printfnq("Ensuring all group memberships have a URI...");
384
385     $mem = new Group_member();
386     $mem->whereAdd('uri IS NULL');
387
388     if ($mem->find()) {
389         while ($mem->fetch()) {
390             try {
391                 $mem->decache();
392                 $mem->query(sprintf('update group_member set uri = "%s" '.
393                                     'where profile_id = %d ' . 
394                                     'and group_id = %d ',
395                                     Group_member::newURI($mem->profile_id, $mem->group_id, $mem->created),
396                                     $mem->profile_id,
397                                     $mem->group_id));
398             } catch (Exception $e) {
399                 common_log(LOG_ERR, "Error updated membership URI: " . $e->getMessage());  
400           }
401         }
402     }
403
404     printfnq("DONE.\n");
405 }
406
407 function initProfileLists()
408 {
409     printfnq("Ensuring all profile tags have a corresponding list...");
410
411     $ptag = new Profile_tag();
412     $ptag->selectAdd();
413     $ptag->selectAdd('tagger, tag, count(*) as tagged_count');
414     $ptag->whereAdd('NOT EXISTS (SELECT tagger, tagged from profile_list '.
415                     'where profile_tag.tagger = profile_list.tagger '.
416                     'and profile_tag.tag = profile_list.tag)');
417     $ptag->groupBy('tagger, tag');
418     $ptag->orderBy('tagger, tag');
419
420     if ($ptag->find()) {
421         while ($ptag->fetch()) {
422             $plist = new Profile_list();
423
424             $plist->tagger   = $ptag->tagger;
425             $plist->tag      = $ptag->tag;
426             $plist->private  = 0;
427             $plist->created  = common_sql_now();
428             $plist->modified = $plist->created;
429             $plist->mainpage = common_local_url('showprofiletag',
430                                                 array('tagger' => $plist->getTagger()->nickname,
431                                                       'tag'    => $plist->tag));;
432
433             $plist->tagged_count     = $ptag->tagged_count;
434             $plist->subscriber_count = 0;
435
436             $plist->insert();
437
438             $orig = clone($plist);
439             // After insert since it uses auto-generated ID
440             $plist->uri      = common_local_url('profiletagbyid',
441                                         array('id' => $plist->id, 'tagger_id' => $plist->tagger));
442
443             $plist->update($orig);
444         }
445     }
446
447     printfnq("DONE.\n");
448 }
449
450 /*
451  * Added as we now store interpretd width and height in File table.
452  */
453 function fixupFileGeometry()
454 {
455     printfnq("Ensuring width and height is set for supported local File objects...");
456
457     $file = new File();
458     $file->whereAdd('filename IS NOT NULL');    // local files
459     $file->whereAdd('width IS NULL OR width = 0');
460
461     if ($file->find()) {
462         while ($file->fetch()) {
463             // Set file geometrical properties if available
464             try {
465                 $image = ImageFile::fromFileObject($file);
466             } catch (ServerException $e) {
467                 // We couldn't make out an image from the file.
468                 continue;
469             }
470             $orig = clone($file);
471             $file->width = $image->width;
472             $file->height = $image->height;
473             $file->update($orig);
474
475             // FIXME: Do this more automagically inside ImageFile or so.
476             if ($image->getPath() != $file->getPath()) {
477                 $image->unlink();
478             }
479             unset($image);
480         }
481     }
482
483     printfnq("DONE.\n");
484 }
485
486 /*
487  * File_thumbnail objects for local Files store their own filenames in the database.
488  */
489 function deleteLocalFileThumbnailsWithoutFilename()
490 {
491     printfnq("Removing all local File_thumbnail entries without filename property...");
492
493     $file = new File();
494     $file->whereAdd('filename IS NOT NULL');    // local files
495
496     if ($file->find()) {
497         // Looping through local File entries
498         while ($file->fetch()) {
499             $thumbs = new File_thumbnail();
500             $thumbs->file_id = $file->id;
501             $thumbs->whereAdd('filename IS NULL');
502             // Checking if there were any File_thumbnail entries without filename
503             if (!$thumbs->find()) {
504                 continue;
505             }
506             // deleting incomplete entry to allow regeneration
507             while ($thumbs->fetch()) {
508                 $thumbs->delete();
509             }
510         }
511     }
512
513     printfnq("DONE.\n");
514 }
515
516 /*
517  * Delete File_thumbnail entries where the referenced file does not exist.
518  */
519 function deleteMissingLocalFileThumbnails()
520 {
521     printfnq("Removing all local File_thumbnail entries without existing files...");
522
523     $thumbs = new File_thumbnail();
524     $thumbs->whereAdd('filename IS NOT NULL');  // only fill in names where they're missing
525     // Checking if there were any File_thumbnail entries without filename
526     if ($thumbs->find()) {
527         while ($thumbs->fetch()) {
528             if (!file_exists(File_thumbnail::path($thumbs->filename))) {
529                 $thumbs->delete();
530             }
531         }
532     }
533
534     printfnq("DONE.\n");
535 }
536
537 main();