upgrade.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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->selectAdd();
  137. $notice->selectAdd('DISTINCT conversation');
  138. $notice->joinAdd(['conversation', 'conversation:id'], 'LEFT'); // LEFT to get the null values for conversation.id
  139. $notice->whereAdd('conversation.id IS NULL');
  140. if ($notice->find()) {
  141. printfnq(" fixing {$notice->N} missing conversation entries...");
  142. }
  143. while ($notice->fetch()) {
  144. $id = $notice->conversation;
  145. $uri = common_local_url('conversation', array('id' => $id));
  146. // @fixme db_dataobject won't save our value for an autoincrement
  147. // so we're bypassing the insert wrappers
  148. $conv = new Conversation();
  149. $sql = "insert into conversation (id,uri,created) values(%d,'%s','%s')";
  150. $sql = sprintf($sql,
  151. $id,
  152. $conv->escape($uri),
  153. $conv->escape(common_sql_now()));
  154. $conv->query($sql);
  155. }
  156. printfnq("DONE.\n");
  157. }
  158. function fixupConversationURIs()
  159. {
  160. printfnq("Ensuring all conversations have a URI...");
  161. $conv = new Conversation();
  162. $conv->whereAdd('uri IS NULL');
  163. if ($conv->find()) {
  164. $rounds = 0;
  165. while ($conv->fetch()) {
  166. $uri = common_local_url('conversation', array('id' => $conv->id));
  167. $sql = sprintf('UPDATE conversation SET uri="%1$s" WHERE id="%2$d";',
  168. $conv->escape($uri), $conv->id);
  169. $conv->query($sql);
  170. if (($conv->N-++$rounds) % 500 == 0) {
  171. printfnq(sprintf(' %d items left...', $conv->N-$rounds));
  172. }
  173. }
  174. }
  175. printfnq("DONE.\n");
  176. }
  177. function initGroupProfileId()
  178. {
  179. printfnq("Ensuring all User_group entries have a Profile and profile_id...");
  180. $group = new User_group();
  181. $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)');
  182. $group->find();
  183. while ($group->fetch()) {
  184. try {
  185. // We must create a new, incrementally assigned profile_id
  186. $profile = new Profile();
  187. $profile->nickname = $group->nickname;
  188. $profile->fullname = $group->fullname;
  189. $profile->profileurl = $group->mainpage;
  190. $profile->homepage = $group->homepage;
  191. $profile->bio = $group->description;
  192. $profile->location = $group->location;
  193. $profile->created = $group->created;
  194. $profile->modified = $group->modified;
  195. $profile->query('BEGIN');
  196. $id = $profile->insert();
  197. if (empty($id)) {
  198. $profile->query('ROLLBACK');
  199. throw new Exception('Profile insertion failed, profileurl: '.$profile->profileurl);
  200. }
  201. $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}");
  202. $profile->query('COMMIT');
  203. $profile->free();
  204. } catch (Exception $e) {
  205. printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage());
  206. }
  207. }
  208. printfnq("DONE.\n");
  209. }
  210. function initLocalGroup()
  211. {
  212. printfnq("Ensuring all local user groups have a local_group...");
  213. $group = new User_group();
  214. $group->whereAdd('NOT EXISTS (select group_id from local_group where group_id = user_group.id)');
  215. $group->find();
  216. while ($group->fetch()) {
  217. try {
  218. // Hack to check for local groups
  219. if ($group->getUri() == common_local_url('groupbyid', array('id' => $group->id))) {
  220. $lg = new Local_group();
  221. $lg->group_id = $group->id;
  222. $lg->nickname = $group->nickname;
  223. $lg->created = $group->created; // XXX: common_sql_now() ?
  224. $lg->modified = $group->modified;
  225. $lg->insert();
  226. }
  227. } catch (Exception $e) {
  228. printfv("Error initializing local group for {$group->nickname}:" . $e->getMessage());
  229. }
  230. }
  231. printfnq("DONE.\n");
  232. }
  233. function initNoticeReshare()
  234. {
  235. printfnq("Ensuring all reshares have the correct verb and object-type...");
  236. $notice = new Notice();
  237. $notice->whereAdd('repeat_of is not null');
  238. $notice->whereAdd('(verb != "'.ActivityVerb::SHARE.'" OR object_type != "'.ActivityObject::ACTIVITY.'")');
  239. if ($notice->find()) {
  240. while ($notice->fetch()) {
  241. try {
  242. $orig = Notice::getKV('id', $notice->id);
  243. $notice->verb = ActivityVerb::SHARE;
  244. $notice->object_type = ActivityObject::ACTIVITY;
  245. $notice->update($orig);
  246. } catch (Exception $e) {
  247. printfv("Error updating verb and object_type for {$notice->id}:" . $e->getMessage());
  248. }
  249. }
  250. }
  251. printfnq("DONE.\n");
  252. }
  253. function initSubscriptionURI()
  254. {
  255. printfnq("Ensuring all subscriptions have a URI...");
  256. $sub = new Subscription();
  257. $sub->whereAdd('uri IS NULL');
  258. if ($sub->find()) {
  259. while ($sub->fetch()) {
  260. try {
  261. $sub->decache();
  262. $sub->query(sprintf('update subscription '.
  263. 'set uri = "%s" '.
  264. 'where subscriber = %d '.
  265. 'and subscribed = %d',
  266. $sub->escape(Subscription::newUri($sub->getSubscriber(), $sub->getSubscribed(), $sub->created)),
  267. $sub->subscriber,
  268. $sub->subscribed));
  269. } catch (Exception $e) {
  270. common_log(LOG_ERR, "Error updated subscription URI: " . $e->getMessage());
  271. }
  272. }
  273. }
  274. printfnq("DONE.\n");
  275. }
  276. function initGroupMemberURI()
  277. {
  278. printfnq("Ensuring all group memberships have a URI...");
  279. $mem = new Group_member();
  280. $mem->whereAdd('uri IS NULL');
  281. if ($mem->find()) {
  282. while ($mem->fetch()) {
  283. try {
  284. $mem->decache();
  285. $mem->query(sprintf('update group_member set uri = "%s" '.
  286. 'where profile_id = %d ' .
  287. 'and group_id = %d ',
  288. Group_member::newUri(Profile::getByID($mem->profile_id), User_group::getByID($mem->group_id), $mem->created),
  289. $mem->profile_id,
  290. $mem->group_id));
  291. } catch (Exception $e) {
  292. common_log(LOG_ERR, "Error updated membership URI: " . $e->getMessage());
  293. }
  294. }
  295. }
  296. printfnq("DONE.\n");
  297. }
  298. function initProfileLists()
  299. {
  300. printfnq("Ensuring all profile tags have a corresponding list...");
  301. $ptag = new Profile_tag();
  302. $ptag->selectAdd();
  303. $ptag->selectAdd('tagger, tag, count(*) as tagged_count');
  304. $ptag->whereAdd('NOT EXISTS (SELECT tagger, tagged from profile_list '.
  305. 'where profile_tag.tagger = profile_list.tagger '.
  306. 'and profile_tag.tag = profile_list.tag)');
  307. $ptag->groupBy('tagger, tag');
  308. $ptag->orderBy('tagger, tag');
  309. if ($ptag->find()) {
  310. while ($ptag->fetch()) {
  311. $plist = new Profile_list();
  312. $plist->tagger = $ptag->tagger;
  313. $plist->tag = $ptag->tag;
  314. $plist->private = 0;
  315. $plist->created = common_sql_now();
  316. $plist->modified = $plist->created;
  317. $plist->mainpage = common_local_url('showprofiletag',
  318. array('tagger' => $plist->getTagger()->nickname,
  319. 'tag' => $plist->tag));;
  320. $plist->tagged_count = $ptag->tagged_count;
  321. $plist->subscriber_count = 0;
  322. $plist->insert();
  323. $orig = clone($plist);
  324. // After insert since it uses auto-generated ID
  325. $plist->uri = common_local_url('profiletagbyid',
  326. array('id' => $plist->id, 'tagger_id' => $plist->tagger));
  327. $plist->update($orig);
  328. }
  329. }
  330. printfnq("DONE.\n");
  331. }
  332. /*
  333. * Added as we now store interpretd width and height in File table.
  334. */
  335. function fixupFileGeometry()
  336. {
  337. printfnq("Ensuring width and height is set for supported local File objects...");
  338. $file = new File();
  339. $file->whereAdd('filename IS NOT NULL'); // local files
  340. $file->whereAdd('width IS NULL OR width = 0');
  341. if ($file->find()) {
  342. while ($file->fetch()) {
  343. // Set file geometrical properties if available
  344. try {
  345. $image = ImageFile::fromFileObject($file);
  346. } catch (ServerException $e) {
  347. // We couldn't make out an image from the file.
  348. continue;
  349. }
  350. $orig = clone($file);
  351. $file->width = $image->width;
  352. $file->height = $image->height;
  353. $file->update($orig);
  354. // FIXME: Do this more automagically inside ImageFile or so.
  355. if ($image->getPath() != $file->getPath()) {
  356. $image->unlink();
  357. }
  358. unset($image);
  359. }
  360. }
  361. printfnq("DONE.\n");
  362. }
  363. /*
  364. * File_thumbnail objects for local Files store their own filenames in the database.
  365. */
  366. function deleteLocalFileThumbnailsWithoutFilename()
  367. {
  368. printfnq("Removing all local File_thumbnail entries without filename property...");
  369. $file = new File();
  370. $file->whereAdd('filename IS NOT NULL'); // local files
  371. if ($file->find()) {
  372. // Looping through local File entries
  373. while ($file->fetch()) {
  374. $thumbs = new File_thumbnail();
  375. $thumbs->file_id = $file->id;
  376. $thumbs->whereAdd('filename IS NULL OR filename = ""');
  377. // Checking if there were any File_thumbnail entries without filename
  378. if (!$thumbs->find()) {
  379. continue;
  380. }
  381. // deleting incomplete entry to allow regeneration
  382. while ($thumbs->fetch()) {
  383. $thumbs->delete();
  384. }
  385. }
  386. }
  387. printfnq("DONE.\n");
  388. }
  389. /*
  390. * Delete File_thumbnail entries where the referenced file does not exist.
  391. */
  392. function deleteMissingLocalFileThumbnails()
  393. {
  394. printfnq("Removing all local File_thumbnail entries without existing files...");
  395. $thumbs = new File_thumbnail();
  396. $thumbs->whereAdd('filename IS NOT NULL AND filename != ""');
  397. // Checking if there were any File_thumbnail entries without filename
  398. if ($thumbs->find()) {
  399. while ($thumbs->fetch()) {
  400. try {
  401. $thumbs->getPath();
  402. } catch (FileNotFoundException $e) {
  403. $thumbs->delete();
  404. }
  405. }
  406. }
  407. printfnq("DONE.\n");
  408. }
  409. /*
  410. * Files are now stored with their hash, so let's generate for previously uploaded files.
  411. */
  412. function setFilehashOnLocalFiles()
  413. {
  414. printfnq('Ensuring all local files have the filehash field set...');
  415. $file = new File();
  416. $file->whereAdd('filename IS NOT NULL AND filename != ""'); // local files
  417. $file->whereAdd('filehash IS NULL', 'AND'); // without filehash value
  418. if ($file->find()) {
  419. while ($file->fetch()) {
  420. try {
  421. $orig = clone($file);
  422. $file->filehash = hash_file(File::FILEHASH_ALG, $file->getPath());
  423. $file->update($orig);
  424. } catch (FileNotFoundException $e) {
  425. 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";
  426. }
  427. }
  428. }
  429. printfnq("DONE.\n");
  430. }
  431. function fixupFileThumbnailUrlhash()
  432. {
  433. printfnq("Setting urlhash for File_thumbnail entries: ");
  434. $thumb = new File_thumbnail();
  435. $thumb->query('UPDATE '.$thumb->escapedTableName().' SET urlhash=SHA2(url, 256) WHERE'.
  436. ' url IS NOT NULL AND'. // find all entries with a url value
  437. ' url != "" AND'. // precaution against non-null empty strings
  438. ' urlhash IS NULL'); // but don't touch those we've already calculated
  439. printfnq("DONE.\n");
  440. }
  441. function migrateProfilePrefs()
  442. {
  443. printfnq("Finding and possibly migrating Profile_prefs entries: ");
  444. $prefs = array(); // ['qvitter' => ['cover_photo'=>'profile_banner_url', ...], ...]
  445. Event::handle('GetProfilePrefsMigrations', array(&$prefs));
  446. foreach($prefs as $namespace=>$mods) {
  447. echo "$namespace... ";
  448. assert(is_array($mods));
  449. $p = new Profile_prefs();
  450. $p->namespace = $namespace;
  451. // find all entries in all modified topics given in this namespace
  452. $p->whereAddIn('topic', array_keys($mods), $p->columnType('topic'));
  453. $p->find();
  454. while ($p->fetch()) {
  455. // for each entry, update 'topic' to the new key value
  456. $orig = clone($p);
  457. $p->topic = $mods[$p->topic];
  458. $p->updateWithKeys($orig);
  459. }
  460. }
  461. printfnq("DONE.\n");
  462. }
  463. main();