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