upgrade.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. #!/usr/bin/env php
  2. <?php
  3. // This file is part of GNU social - https://www.gnu.org/software/social
  4. //
  5. // GNU social is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GNU social is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  17. /**
  18. * Upgrade database schema and data to latest software and check DB integrity
  19. * Usage: php upgrade.php [options]
  20. *
  21. * @package GNUsocial
  22. * @author Bhuvan Krishna <bhuvan@swecha.net>
  23. * @author Evan Prodromou <evan@status.net>
  24. * @author Mikael Nordfeldth <mmn@hethane.se>
  25. * @copyright 2010-2019 Free Software Foundation, Inc http://www.fsf.org
  26. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  27. */
  28. define('INSTALLDIR', dirname(__DIR__));
  29. define('PUBLICDIR', INSTALLDIR . DIRECTORY_SEPARATOR . 'public');
  30. $shortoptions = 'dfx::';
  31. $longoptions = ['debug', 'files', 'extensions='];
  32. $helptext = <<<END_OF_UPGRADE_HELP
  33. php upgrade.php [options]
  34. Upgrade database schema and data to latest software
  35. END_OF_UPGRADE_HELP;
  36. require_once INSTALLDIR.'/scripts/commandline.inc';
  37. if (!defined('DEBUG')) {
  38. define('DEBUG', (bool)have_option('d', 'debug'));
  39. }
  40. function main()
  41. {
  42. // "files" option enables possibly disk/resource intensive operations
  43. // that aren't really _required_ for the upgrade
  44. $iterate_files = (bool)have_option('f', 'files');
  45. if (Event::handle('StartUpgrade')) {
  46. fixupConversationURIs();
  47. updateSchemaCore();
  48. updateSchemaPlugins();
  49. // These replace old "fixup_*" scripts
  50. fixupNoticeConversation();
  51. initConversation();
  52. fixupUserBadNulls();
  53. fixupGroupURI();
  54. if ($iterate_files) {
  55. printfnq("* "); fixupFileGeometry();
  56. printfnq("* "); deleteLocalFileThumbnailsWithoutFilename();
  57. printfnq("* "); deleteMissingLocalFileThumbnails();
  58. printfnq("* "); fixupFileThumbnailUrlhash();
  59. printfnq("* "); setFilehashOnLocalFiles();
  60. printfnq("DONE.\n");
  61. } else {
  62. printfnq("Skipping intensive/long-running file iteration functions (enable with -f, should be done at least once!)\n");
  63. }
  64. initGroupProfileId();
  65. initLocalGroup();
  66. initNoticeReshare();
  67. initSubscriptionURI();
  68. initGroupMemberURI();
  69. initProfileLists();
  70. migrateProfilePrefs();
  71. Event::handle('EndUpgrade');
  72. }
  73. }
  74. function tableDefs()
  75. {
  76. $schema = [];
  77. require INSTALLDIR . '/db/core.php';
  78. return $schema;
  79. }
  80. function updateSchemaCore()
  81. {
  82. printfnq("Upgrading core schema...");
  83. $schema = Schema::get();
  84. $schemaUpdater = new SchemaUpdater($schema);
  85. foreach (tableDefs() as $table => $def) {
  86. $schemaUpdater->register($table, $def);
  87. }
  88. $schemaUpdater->checkSchema();
  89. printfnq("DONE.\n");
  90. }
  91. function updateSchemaPlugins()
  92. {
  93. printfnq("Upgrading plugin schema...");
  94. Event::handle('BeforePluginCheckSchema');
  95. Event::handle('CheckSchema');
  96. printfnq("DONE.\n");
  97. }
  98. function fixupUserBadNulls(): void
  99. {
  100. printfnq("Ensuring all users have no empty strings for NULLs...");
  101. foreach (['email', 'incomingemail', 'sms', 'smsemail'] as $col) {
  102. $user = new User();
  103. $user->whereAdd("{$col} = ''");
  104. if ($user->find()) {
  105. while ($user->fetch()) {
  106. $sql = "UPDATE {$user->escapedTableName()} SET {$col} = NULL "
  107. . "WHERE id = {$user->id}";
  108. $user->query($sql);
  109. }
  110. }
  111. }
  112. printfnq("DONE.\n");
  113. }
  114. function fixupNoticeConversation()
  115. {
  116. printfnq("Ensuring all notices have a conversation ID...");
  117. $notice = new Notice();
  118. $notice->whereAdd('conversation is null');
  119. $notice->whereAdd('conversation = 0', 'OR');
  120. $notice->orderBy('id'); // try to get originals before replies
  121. $notice->find();
  122. while ($notice->fetch()) {
  123. try {
  124. $cid = null;
  125. $orig = clone($notice);
  126. if (!empty($notice->reply_to)) {
  127. $reply = Notice::getKV('id', $notice->reply_to);
  128. if ($reply instanceof Notice && !empty($reply->conversation)) {
  129. $notice->conversation = $reply->conversation;
  130. }
  131. unset($reply);
  132. }
  133. // if still empty
  134. if (empty($notice->conversation)) {
  135. $child = new Notice();
  136. $child->reply_to = $notice->getID();
  137. $child->limit(1);
  138. if ($child->find(true) && !empty($child->conversation)) {
  139. $notice->conversation = $child->conversation;
  140. }
  141. unset($child);
  142. }
  143. // if _still_ empty we just create our own conversation
  144. if (empty($notice->conversation)) {
  145. $notice->conversation = $notice->getID();
  146. }
  147. $result = $notice->update($orig);
  148. unset($orig);
  149. } catch (Exception $e) {
  150. print("Error setting conversation: " . $e->getMessage());
  151. }
  152. }
  153. printfnq("DONE.\n");
  154. }
  155. function fixupGroupURI()
  156. {
  157. printfnq("Ensuring all groups have an URI...");
  158. $group = new User_group();
  159. $group->whereAdd('uri IS NULL');
  160. if ($group->find()) {
  161. while ($group->fetch()) {
  162. $orig = User_group::getKV('id', $group->id);
  163. $group->uri = $group->getUri();
  164. $group->update($orig);
  165. }
  166. }
  167. printfnq("DONE.\n");
  168. }
  169. function initConversation()
  170. {
  171. if (common_config('fix', 'upgrade_initConversation') <= 1) {
  172. printfnq(sprintf("Skipping %s, fixed by previous upgrade.\n", __METHOD__));
  173. return;
  174. }
  175. printfnq("Ensuring all conversations have a row in conversation table...");
  176. $notice = new Notice();
  177. $notice->selectAdd();
  178. $notice->selectAdd('DISTINCT conversation');
  179. $notice->joinAdd(['conversation', 'conversation:id'], 'LEFT'); // LEFT to get the null values for conversation.id
  180. $notice->whereAdd('conversation.id IS NULL');
  181. if ($notice->find()) {
  182. printfnq(" fixing {$notice->N} missing conversation entries...");
  183. }
  184. while ($notice->fetch()) {
  185. $id = $notice->conversation;
  186. $uri = common_local_url('conversation', ['id' => $id]);
  187. // @fixme db_dataobject won't save our value for an autoincrement
  188. // so we're bypassing the insert wrappers
  189. $conv = new Conversation();
  190. $sql = "INSERT INTO conversation (id,uri,created) VALUES (%d,'%s','%s')";
  191. $sql = sprintf(
  192. $sql,
  193. $id,
  194. $conv->escape($uri),
  195. $conv->escape(common_sql_now())
  196. );
  197. $conv->query($sql);
  198. }
  199. // This is something we should only have to do once unless introducing new, bad code.
  200. if (DEBUG) {
  201. printfnq(sprintf('Storing in config that we have done %s', __METHOD__));
  202. }
  203. common_config_set('fix', 'upgrade_initConversation', 1);
  204. printfnq("DONE.\n");
  205. }
  206. function fixupConversationURIs()
  207. {
  208. printfnq("Ensuring all conversations have a URI...");
  209. $conv = new Conversation();
  210. $conv->whereAdd('uri IS NULL');
  211. if ($conv->find()) {
  212. $rounds = 0;
  213. while ($conv->fetch()) {
  214. $uri = common_local_url('conversation', ['id' => $conv->id]);
  215. $sql = sprintf(
  216. 'UPDATE conversation SET uri = \'%1$s\' WHERE id = %2$d;',
  217. $conv->escape($uri),
  218. $conv->id
  219. );
  220. $conv->query($sql);
  221. if (($conv->N-++$rounds) % 500 == 0) {
  222. printfnq(sprintf(' %d items left...', $conv->N-$rounds));
  223. }
  224. }
  225. }
  226. printfnq("DONE.\n");
  227. }
  228. function initGroupProfileId()
  229. {
  230. printfnq("Ensuring all User_group entries have a Profile and profile_id...");
  231. $group = new User_group();
  232. $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)');
  233. $group->find();
  234. while ($group->fetch()) {
  235. try {
  236. // We must create a new, incrementally assigned profile_id
  237. $profile = new Profile();
  238. $profile->nickname = $group->nickname;
  239. $profile->fullname = $group->fullname;
  240. $profile->profileurl = $group->mainpage;
  241. $profile->homepage = $group->homepage;
  242. $profile->bio = $group->description;
  243. $profile->location = $group->location;
  244. $profile->created = $group->created;
  245. $profile->modified = $group->modified;
  246. $profile->query('START TRANSACTION');
  247. $id = $profile->insert();
  248. if (empty($id)) {
  249. $profile->query('ROLLBACK');
  250. throw new Exception('Profile insertion failed, profileurl: '.$profile->profileurl);
  251. }
  252. $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}");
  253. $profile->query('COMMIT');
  254. $profile->free();
  255. } catch (Exception $e) {
  256. printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage());
  257. }
  258. }
  259. printfnq("DONE.\n");
  260. }
  261. function initLocalGroup()
  262. {
  263. printfnq("Ensuring all local user groups have a local_group...");
  264. $group = new User_group();
  265. $group->whereAdd('NOT EXISTS (select group_id from local_group where group_id = user_group.id)');
  266. $group->find();
  267. while ($group->fetch()) {
  268. try {
  269. // Hack to check for local groups
  270. if ($group->getUri() == common_local_url('groupbyid', ['id' => $group->id])) {
  271. $lg = new Local_group();
  272. $lg->group_id = $group->id;
  273. $lg->nickname = $group->nickname;
  274. $lg->created = $group->created; // XXX: common_sql_now() ?
  275. $lg->modified = $group->modified;
  276. $lg->insert();
  277. }
  278. } catch (Exception $e) {
  279. printfv("Error initializing local group for {$group->nickname}:" . $e->getMessage());
  280. }
  281. }
  282. printfnq("DONE.\n");
  283. }
  284. function initNoticeReshare()
  285. {
  286. if (common_config('fix', 'upgrade_initNoticeReshare') <= 1) {
  287. printfnq(sprintf("Skipping %s, fixed by previous upgrade.\n", __METHOD__));
  288. return;
  289. }
  290. printfnq("Ensuring all reshares have the correct verb and object-type...");
  291. $notice = new Notice();
  292. $notice->whereAdd('repeat_of is not null');
  293. $notice->whereAdd('(verb <> "' . ActivityVerb::SHARE
  294. . '" OR object_type <> "' . ActivityObject::ACTIVITY . '")');
  295. if ($notice->find()) {
  296. while ($notice->fetch()) {
  297. try {
  298. $orig = Notice::getKV('id', $notice->id);
  299. $notice->verb = ActivityVerb::SHARE;
  300. $notice->object_type = ActivityObject::ACTIVITY;
  301. $notice->update($orig);
  302. } catch (Exception $e) {
  303. printfv("Error updating verb and object_type for {$notice->id}:" . $e->getMessage());
  304. }
  305. }
  306. }
  307. // This is something we should only have to do once unless introducing new, bad code.
  308. if (DEBUG) {
  309. printfnq(sprintf('Storing in config that we have done %s', __METHOD__));
  310. }
  311. common_config_set('fix', 'upgrade_initNoticeReshare', 1);
  312. printfnq("DONE.\n");
  313. }
  314. function initSubscriptionURI()
  315. {
  316. printfnq("Ensuring all subscriptions have a URI...");
  317. $sub = new Subscription();
  318. $sub->whereAdd('uri IS NULL');
  319. if ($sub->find()) {
  320. while ($sub->fetch()) {
  321. try {
  322. $sub->decache();
  323. $sub->query(sprintf(
  324. 'UPDATE subscription '.
  325. "SET uri = '%s' " .
  326. 'WHERE subscriber = %d '.
  327. 'AND subscribed = %d',
  328. $sub->escape(Subscription::newUri($sub->getSubscriber(), $sub->getSubscribed(), $sub->created)),
  329. $sub->subscriber,
  330. $sub->subscribed
  331. ));
  332. } catch (Exception $e) {
  333. common_log(LOG_ERR, "Error updated subscription URI: " . $e->getMessage());
  334. }
  335. }
  336. }
  337. printfnq("DONE.\n");
  338. }
  339. function initGroupMemberURI()
  340. {
  341. printfnq("Ensuring all group memberships have a URI...");
  342. $mem = new Group_member();
  343. $mem->whereAdd('uri IS NULL');
  344. if ($mem->find()) {
  345. while ($mem->fetch()) {
  346. try {
  347. $mem->decache();
  348. $mem->query(sprintf(
  349. 'UPDATE group_member '.
  350. "SET uri = '%s' " .
  351. 'WHERE profile_id = %d ' .
  352. 'AND group_id = %d',
  353. Group_member::newUri(Profile::getByID($mem->profile_id), User_group::getByID($mem->group_id), $mem->created),
  354. $mem->profile_id,
  355. $mem->group_id
  356. ));
  357. } catch (Exception $e) {
  358. common_log(LOG_ERR, "Error updated membership URI: " . $e->getMessage());
  359. }
  360. }
  361. }
  362. printfnq("DONE.\n");
  363. }
  364. function initProfileLists()
  365. {
  366. printfnq("Ensuring all profile tags have a corresponding list...");
  367. $ptag = new Profile_tag();
  368. $ptag->selectAdd();
  369. $ptag->selectAdd('tagger, tag, COUNT(*) AS tagged_count');
  370. $ptag->whereAdd('NOT EXISTS (SELECT tagger, tagged FROM profile_list '.
  371. 'WHERE profile_tag.tagger = profile_list.tagger '.
  372. 'AND profile_tag.tag = profile_list.tag)');
  373. $ptag->groupBy('tagger, tag');
  374. $ptag->orderBy('tagger, tag');
  375. if ($ptag->find()) {
  376. while ($ptag->fetch()) {
  377. $plist = new Profile_list();
  378. $plist->tagger = $ptag->tagger;
  379. $plist->tag = $ptag->tag;
  380. $plist->private = false;
  381. $plist->created = common_sql_now();
  382. $plist->modified = $plist->created;
  383. $plist->mainpage = common_local_url(
  384. 'showprofiletag',
  385. ['tagger' => $plist->getTagger()->nickname,
  386. 'tag' => $plist->tag]
  387. );
  388. ;
  389. $plist->tagged_count = $ptag->tagged_count;
  390. $plist->subscriber_count = 0;
  391. $plist->insert();
  392. $orig = clone($plist);
  393. // After insert since it uses auto-generated ID
  394. $plist->uri = common_local_url(
  395. 'profiletagbyid',
  396. ['id' => $plist->id,
  397. 'tagger_id' => $plist->tagger]
  398. );
  399. $plist->update($orig);
  400. }
  401. }
  402. printfnq("DONE.\n");
  403. }
  404. /*
  405. * Added as we now store interpretd width and height in File table.
  406. */
  407. function fixupFileGeometry()
  408. {
  409. printfnq("Ensuring width and height is set for supported local File objects...");
  410. $file = new File();
  411. $file->whereAdd('filename IS NOT NULL'); // local files
  412. $file->whereAdd('width IS NULL OR width = 0');
  413. if ($file->find()) {
  414. while ($file->fetch()) {
  415. if (DEBUG) {
  416. printfnq(sprintf('Found file without width: %s\n', _ve($file->getFilename())));
  417. }
  418. // Set file geometrical properties if available
  419. try {
  420. $image = ImageFile::fromFileObject($file);
  421. } catch (ServerException $e) {
  422. // We couldn't make out an image from the file.
  423. if (DEBUG) {
  424. printfnq(sprintf('Could not make an image out of the file.\n'));
  425. }
  426. continue;
  427. }
  428. $orig = clone($file);
  429. $file->width = $image->width;
  430. $file->height = $image->height;
  431. if (DEBUG) {
  432. printfnq(sprintf('Setting image file and with to %sx%s.\n', $file->width, $file->height));
  433. }
  434. $file->update($orig);
  435. // FIXME: Do this more automagically inside ImageFile or so.
  436. if ($image->getPath() != $file->getPath()) {
  437. if (DEBUG) {
  438. printfnq(sprintf('Deleting the temporarily stored ImageFile.\n'));
  439. }
  440. $image->unlink();
  441. }
  442. unset($image);
  443. }
  444. }
  445. printfnq("DONE.\n");
  446. }
  447. /*
  448. * File_thumbnail objects for local Files store their own filenames in the database.
  449. */
  450. function deleteLocalFileThumbnailsWithoutFilename()
  451. {
  452. printfnq("Removing all local File_thumbnail entries without filename property...");
  453. $file = new File();
  454. $file->whereAdd('filename IS NOT NULL'); // local files
  455. if ($file->find()) {
  456. // Looping through local File entries
  457. while ($file->fetch()) {
  458. $thumbs = new File_thumbnail();
  459. $thumbs->file_id = $file->id;
  460. $thumbs->whereAdd("filename IS NULL OR filename = ''");
  461. // Checking if there were any File_thumbnail entries without filename
  462. if (!$thumbs->find()) {
  463. continue;
  464. }
  465. // deleting incomplete entry to allow regeneration
  466. while ($thumbs->fetch()) {
  467. $thumbs->delete();
  468. }
  469. }
  470. }
  471. printfnq("DONE.\n");
  472. }
  473. /*
  474. * Delete File_thumbnail entries where the referenced file does not exist.
  475. */
  476. function deleteMissingLocalFileThumbnails()
  477. {
  478. printfnq("Removing all local File_thumbnail entries without existing files...");
  479. $thumbs = new File_thumbnail();
  480. $thumbs->whereAdd("filename IS NOT NULL AND filename <> ''");
  481. // Checking if there were any File_thumbnail entries without filename
  482. if ($thumbs->find()) {
  483. while ($thumbs->fetch()) {
  484. try {
  485. $thumbs->getPath();
  486. } catch (FileNotFoundException $e) {
  487. $thumbs->delete();
  488. }
  489. }
  490. }
  491. printfnq("DONE.\n");
  492. }
  493. /*
  494. * Files are now stored with their hash, so let's generate for previously uploaded files.
  495. */
  496. function setFilehashOnLocalFiles()
  497. {
  498. printfnq('Ensuring all local files have the filehash field set...');
  499. $file = new File();
  500. $file->whereAdd("filename IS NOT NULL AND filename <> ''"); // local files
  501. $file->whereAdd('filehash IS NULL', 'AND'); // without filehash value
  502. if ($file->find()) {
  503. while ($file->fetch()) {
  504. try {
  505. $orig = clone($file);
  506. $file->filehash = hash_file(File::FILEHASH_ALG, $file->getPath());
  507. $file->update($orig);
  508. } catch (FileNotFoundException $e) {
  509. 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";
  510. }
  511. }
  512. }
  513. printfnq("DONE.\n");
  514. }
  515. function fixupFileThumbnailUrlhash()
  516. {
  517. printfnq("Setting urlhash for File_thumbnail entries: ");
  518. switch (common_config('db', 'type')) {
  519. case 'pgsql':
  520. $url_sha256 = 'encode(sha256(CAST("url" AS bytea)), \'hex\')';
  521. break;
  522. case 'mysql':
  523. $url_sha256 = 'sha2(`url`, 256)';
  524. break;
  525. default:
  526. throw new Exception('Unknown DB type selected.');
  527. }
  528. $thumb = new File_thumbnail();
  529. $thumb->query(sprintf(
  530. 'UPDATE %1$s ' .
  531. 'SET urlhash = %2$s ' .
  532. 'WHERE url IS NOT NULL ' . // find all entries with a url value
  533. "AND url <> '' " . // precaution against non-null empty strings
  534. 'AND urlhash IS NULL', // but don't touch those we've already calculated
  535. $thumb->escapedTableName(),
  536. $url_sha256
  537. ));
  538. printfnq("DONE.\n");
  539. }
  540. function migrateProfilePrefs()
  541. {
  542. printfnq("Finding and possibly migrating Profile_prefs entries: ");
  543. $prefs = []; // ['qvitter' => ['cover_photo'=>'profile_banner_url', ...], ...]
  544. Event::handle('GetProfilePrefsMigrations', [&$prefs]);
  545. foreach ($prefs as $namespace=>$mods) {
  546. echo "$namespace... ";
  547. assert(is_array($mods));
  548. $p = new Profile_prefs();
  549. $p->namespace = $namespace;
  550. // find all entries in all modified topics given in this namespace
  551. $p->whereAddIn('topic', array_keys($mods), $p->columnType('topic'));
  552. $p->find();
  553. while ($p->fetch()) {
  554. // for each entry, update 'topic' to the new key value
  555. $orig = clone($p);
  556. $p->topic = $mods[$p->topic];
  557. $p->updateWithKeys($orig);
  558. }
  559. }
  560. printfnq("DONE.\n");
  561. }
  562. main();