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