]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/upgrade.php
Merge remote-tracking branch 'upstream/master'
[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.php';
33
34 function main()
35 {
36     if (Event::handle('StartUpgrade')) {
37         updateSchemaCore();
38         updateSchemaPlugins();
39
40         // These replace old "fixup_*" scripts
41
42         fixupNoticeRendered();
43         fixupNoticeConversation();
44         initConversation();
45         fixupGroupURI();
46         fixupFileGeometry();
47         deleteLocalFileThumbnailsWithoutFilename();
48         deleteMissingLocalFileThumbnails();
49
50         initGroupProfileId();
51         initLocalGroup();
52         initNoticeReshare();
53     
54         initSubscriptionURI();
55         initGroupMemberURI();
56
57         initProfileLists();
58
59         Event::handle('EndUpgrade');
60     }
61 }
62
63 function tableDefs()
64 {
65         $schema = array();
66         require INSTALLDIR.'/db/core.php';
67         return $schema;
68 }
69
70 function updateSchemaCore()
71 {
72     printfnq("Upgrading core schema...");
73
74     $schema = Schema::get();
75     $schemaUpdater = new SchemaUpdater($schema);
76     foreach (tableDefs() as $table => $def) {
77         $schemaUpdater->register($table, $def);
78     }
79     $schemaUpdater->checkSchema();
80
81     printfnq("DONE.\n");
82 }
83
84 function updateSchemaPlugins()
85 {
86     printfnq("Upgrading plugin schema...");
87
88     Event::handle('CheckSchema');
89
90     printfnq("DONE.\n");
91 }
92
93 function fixupNoticeRendered()
94 {
95     printfnq("Ensuring all notices have rendered HTML...");
96
97     $notice = new Notice();
98
99     $notice->whereAdd('rendered IS NULL');
100     $notice->find();
101
102     while ($notice->fetch()) {
103         $original = clone($notice);
104         $notice->rendered = common_render_content($notice->content, $notice);
105         $notice->update($original);
106     }
107
108     printfnq("DONE.\n");
109 }
110
111 function fixupNoticeConversation()
112 {
113     printfnq("Ensuring all notices have a conversation ID...");
114
115     $notice = new Notice();
116     $notice->whereAdd('conversation is null');
117     $notice->orderBy('id'); // try to get originals before replies
118     $notice->find();
119
120     while ($notice->fetch()) {
121         try {
122             $cid = null;
123     
124             $orig = clone($notice);
125     
126             if (empty($notice->reply_to)) {
127                 $notice->conversation = $notice->id;
128             } else {
129                 $reply = Notice::getKV('id', $notice->reply_to);
130
131                 if (empty($reply)) {
132                     $notice->conversation = $notice->id;
133                 } else if (empty($reply->conversation)) {
134                     $notice->conversation = $notice->id;
135                 } else {
136                     $notice->conversation = $reply->conversation;
137                 }
138         
139                 unset($reply);
140                 $reply = null;
141             }
142
143             $result = $notice->update($orig);
144
145             $orig = null;
146             unset($orig);
147         } catch (Exception $e) {
148             printv("Error setting conversation: " . $e->getMessage());
149         }
150     }
151
152     printfnq("DONE.\n");
153 }
154
155 function fixupGroupURI()
156 {
157     printfnq("Ensuring all groups have an URI...");
158
159     $group = new User_group();
160     $group->whereAdd('uri IS NULL');
161
162     if ($group->find()) {
163         while ($group->fetch()) {
164             $orig = User_group::getKV('id', $group->id);
165             $group->uri = $group->getUri();
166             $group->update($orig);
167         }
168     }
169
170     printfnq("DONE.\n");
171 }
172
173 function initConversation()
174 {
175     printfnq("Ensuring all conversations have a row in conversation table...");
176
177     $notice = new Notice();
178     $notice->query('select distinct notice.conversation from notice '.
179                    'where notice.conversation is not null '.
180                    'and not exists (select conversation.id from conversation where id = notice.conversation)');
181
182     while ($notice->fetch()) {
183
184         $id = $notice->conversation;
185
186         $uri = common_local_url('conversation', array('id' => $id));
187
188         // @fixme db_dataobject won't save our value for an autoincrement
189         // so we're bypassing the insert wrappers
190         $conv = new Conversation();
191         $sql = "insert into conversation (id,uri,created) values(%d,'%s','%s')";
192         $sql = sprintf($sql,
193                        $id,
194                        $conv->escape($uri),
195                        $conv->escape(common_sql_now()));
196         $conv->query($sql);
197     }
198
199     printfnq("DONE.\n");
200 }
201
202 function initGroupProfileId()
203 {
204     printfnq("Ensuring all User_group entries have a Profile and profile_id...");
205
206     $group = new User_group();
207     $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)');
208     $group->find();
209
210     while ($group->fetch()) {
211         try {
212             // We must create a new, incrementally assigned profile_id
213             $profile = new Profile();
214             $profile->nickname   = $group->nickname;
215             $profile->fullname   = $group->fullname;
216             $profile->profileurl = $group->mainpage;
217             $profile->homepage   = $group->homepage;
218             $profile->bio        = $group->description;
219             $profile->location   = $group->location;
220             $profile->created    = $group->created;
221             $profile->modified   = $group->modified;
222
223             $profile->query('BEGIN');
224             $id = $profile->insert();
225             if (empty($id)) {
226                 $profile->query('ROLLBACK');
227                 throw new Exception('Profile insertion failed, profileurl: '.$profile->profileurl);
228             }
229             $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}");
230             $profile->query('COMMIT');
231
232             $profile->free();
233         } catch (Exception $e) {
234             printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage());
235         }
236     }
237
238     printfnq("DONE.\n");
239 }
240
241 function initLocalGroup()
242 {
243     printfnq("Ensuring all local user groups have a local_group...");
244
245     $group = new User_group();
246     $group->whereAdd('NOT EXISTS (select group_id from local_group where group_id = user_group.id)');
247     $group->find();
248
249     while ($group->fetch()) {
250         try {
251             // Hack to check for local groups
252             if ($group->getUri() == common_local_url('groupbyid', array('id' => $group->id))) {
253                 $lg = new Local_group();
254
255                 $lg->group_id = $group->id;
256                 $lg->nickname = $group->nickname;
257                 $lg->created  = $group->created; // XXX: common_sql_now() ?
258                 $lg->modified = $group->modified;
259
260                 $lg->insert();
261             }
262         } catch (Exception $e) {
263             printfv("Error initializing local group for {$group->nickname}:" . $e->getMessage());
264         }
265     }
266
267     printfnq("DONE.\n");
268 }
269
270 function initNoticeReshare()
271 {
272     printfnq("Ensuring all reshares have the correct verb and object-type...");
273     
274     $notice = new Notice();
275     $notice->whereAdd('repeat_of is not null');
276     $notice->whereAdd('(verb != "'.ActivityVerb::SHARE.'" OR object_type != "'.ActivityObject::ACTIVITY.'")');
277
278     if ($notice->find()) {
279         while ($notice->fetch()) {
280             try {
281                 $orig = Notice::getKV('id', $notice->id);
282                 $notice->verb = ActivityVerb::SHARE;
283                 $notice->object_type = ActivityObject::ACTIVITY;
284                 $notice->update($orig);
285             } catch (Exception $e) {
286                 printfv("Error updating verb and object_type for {$notice->id}:" . $e->getMessage());
287             }
288         }
289     }
290
291     printfnq("DONE.\n");
292 }
293
294 function initSubscriptionURI()
295 {
296     printfnq("Ensuring all subscriptions have a URI...");
297
298     $sub = new Subscription();
299     $sub->whereAdd('uri IS NULL');
300
301     if ($sub->find()) {
302         while ($sub->fetch()) {
303             try {
304                 $sub->decache();
305                 $sub->query(sprintf('update subscription '.
306                                     'set uri = "%s" '.
307                                     'where subscriber = %d '.
308                                     'and subscribed = %d',
309                                     Subscription::newURI($sub->subscriber, $sub->subscribed, $sub->created),
310                                     $sub->subscriber,
311                                     $sub->subscribed));
312             } catch (Exception $e) {
313                 common_log(LOG_ERR, "Error updated subscription URI: " . $e->getMessage());
314             }
315         }
316     }
317
318     printfnq("DONE.\n");
319 }
320
321 function initGroupMemberURI()
322 {
323     printfnq("Ensuring all group memberships have a URI...");
324
325     $mem = new Group_member();
326     $mem->whereAdd('uri IS NULL');
327
328     if ($mem->find()) {
329         while ($mem->fetch()) {
330             try {
331                 $mem->decache();
332                 $mem->query(sprintf('update group_member set uri = "%s" '.
333                                     'where profile_id = %d ' . 
334                                     'and group_id = %d ',
335                                     Group_member::newURI($mem->profile_id, $mem->group_id, $mem->created),
336                                     $mem->profile_id,
337                                     $mem->group_id));
338             } catch (Exception $e) {
339                 common_log(LOG_ERR, "Error updated membership URI: " . $e->getMessage());  
340           }
341         }
342     }
343
344     printfnq("DONE.\n");
345 }
346
347 function initProfileLists()
348 {
349     printfnq("Ensuring all profile tags have a corresponding list...");
350
351     $ptag = new Profile_tag();
352     $ptag->selectAdd();
353     $ptag->selectAdd('tagger, tag, count(*) as tagged_count');
354     $ptag->whereAdd('NOT EXISTS (SELECT tagger, tagged from profile_list '.
355                     'where profile_tag.tagger = profile_list.tagger '.
356                     'and profile_tag.tag = profile_list.tag)');
357     $ptag->groupBy('tagger, tag');
358     $ptag->orderBy('tagger, tag');
359
360     if ($ptag->find()) {
361         while ($ptag->fetch()) {
362             $plist = new Profile_list();
363
364             $plist->tagger   = $ptag->tagger;
365             $plist->tag      = $ptag->tag;
366             $plist->private  = 0;
367             $plist->created  = common_sql_now();
368             $plist->modified = $plist->created;
369             $plist->mainpage = common_local_url('showprofiletag',
370                                                 array('tagger' => $plist->getTagger()->nickname,
371                                                       'tag'    => $plist->tag));;
372
373             $plist->tagged_count     = $ptag->tagged_count;
374             $plist->subscriber_count = 0;
375
376             $plist->insert();
377
378             $orig = clone($plist);
379             // After insert since it uses auto-generated ID
380             $plist->uri      = common_local_url('profiletagbyid',
381                                         array('id' => $plist->id, 'tagger_id' => $plist->tagger));
382
383             $plist->update($orig);
384         }
385     }
386
387     printfnq("DONE.\n");
388 }
389
390 /*
391  * Added as we now store interpretd width and height in File table.
392  */
393 function fixupFileGeometry()
394 {
395     printfnq("Ensuring width and height is set for supported local File objects...");
396
397     $file = new File();
398     $file->whereAdd('filename IS NOT NULL');    // local files
399     $file->whereAdd('width IS NULL OR width = 0');
400
401     if ($file->find()) {
402         while ($file->fetch()) {
403             // Set file geometrical properties if available
404             try {
405                 $image = ImageFile::fromFileObject($file);
406             } catch (ServerException $e) {
407                 // We couldn't make out an image from the file.
408                 continue;
409             }
410             $orig = clone($file);
411             $file->width = $image->width;
412             $file->height = $image->height;
413             $file->update($orig);
414
415             // FIXME: Do this more automagically inside ImageFile or so.
416             if ($image->getPath() != $file->getPath()) {
417                 $image->unlink();
418             }
419             unset($image);
420         }
421     }
422
423     printfnq("DONE.\n");
424 }
425
426 /*
427  * File_thumbnail objects for local Files store their own filenames in the database.
428  */
429 function deleteLocalFileThumbnailsWithoutFilename()
430 {
431     printfnq("Removing all local File_thumbnail entries without filename property...");
432
433     $file = new File();
434     $file->whereAdd('filename IS NOT NULL');    // local files
435
436     if ($file->find()) {
437         // Looping through local File entries
438         while ($file->fetch()) {
439             $thumbs = new File_thumbnail();
440             $thumbs->file_id = $file->id;
441             $thumbs->whereAdd('filename IS NULL');
442             // Checking if there were any File_thumbnail entries without filename
443             if (!$thumbs->find()) {
444                 continue;
445             }
446             // deleting incomplete entry to allow regeneration
447             while ($thumbs->fetch()) {
448                 $thumbs->delete();
449             }
450         }
451     }
452
453     printfnq("DONE.\n");
454 }
455
456 /*
457  * Delete File_thumbnail entries where the referenced file does not exist.
458  */
459 function deleteMissingLocalFileThumbnails()
460 {
461     printfnq("Removing all local File_thumbnail entries without existing files...");
462
463     $thumbs = new File_thumbnail();
464     $thumbs->whereAdd('filename IS NOT NULL');  // only fill in names where they're missing
465     // Checking if there were any File_thumbnail entries without filename
466     if ($thumbs->find()) {
467         while ($thumbs->fetch()) {
468             if (!file_exists(File_thumbnail::path($thumbs->filename))) {
469                 $thumbs->delete();
470             }
471         }
472     }
473
474     printfnq("DONE.\n");
475 }
476
477 main();