upgrade.php 17 KB

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