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("Running file iterations:\n");
  56. printfnq("* "); fixupFileGeometry();
  57. printfnq("* "); deleteLocalFileThumbnailsWithoutFilename();
  58. printfnq("* "); deleteMissingLocalFileThumbnails();
  59. printfnq("* "); fixupFileThumbnailUrlhash();
  60. printfnq("* "); setFilehashOnLocalFiles();
  61. printfnq("DONE.\n");
  62. } else {
  63. printfnq("Skipping intensive/long-running file iteration functions (enable with -f, should be done at least once!)\n");
  64. }
  65. initGroupProfileId();
  66. initLocalGroup();
  67. initNoticeReshare();
  68. initSubscriptionURI();
  69. initGroupMemberURI();
  70. initProfileLists();
  71. migrateProfilePrefs();
  72. Event::handle('EndUpgrade');
  73. }
  74. }
  75. function tableDefs()
  76. {
  77. $schema = [];
  78. require INSTALLDIR . '/db/core.php';
  79. return $schema;
  80. }
  81. function updateSchemaCore()
  82. {
  83. printfnq("Upgrading core schema...");
  84. $schema = Schema::get();
  85. $schemaUpdater = new SchemaUpdater($schema);
  86. foreach (tableDefs() as $table => $def) {
  87. $schemaUpdater->register($table, $def);
  88. }
  89. $schemaUpdater->checkSchema();
  90. printfnq("DONE.\n");
  91. }
  92. function updateSchemaPlugins()
  93. {
  94. printfnq("Upgrading plugin schema...");
  95. Event::handle('BeforePluginCheckSchema');
  96. Event::handle('CheckSchema');
  97. printfnq("DONE.\n");
  98. }
  99. function fixupUserBadNulls(): void
  100. {
  101. printfnq("Ensuring all users have no empty strings for NULLs...");
  102. foreach (['email', 'incomingemail', 'sms', 'smsemail'] as $col) {
  103. $user = new User();
  104. $user->whereAdd("{$col} = ''");
  105. if ($user->find()) {
  106. while ($user->fetch()) {
  107. $sql = "UPDATE {$user->escapedTableName()} SET {$col} = NULL "
  108. . "WHERE id = {$user->id}";
  109. $user->query($sql);
  110. }
  111. }
  112. }
  113. printfnq("DONE.\n");
  114. }
  115. function fixupNoticeConversation()
  116. {
  117. printfnq("Ensuring all notices have a conversation ID...");
  118. $notice = new Notice();
  119. $notice->whereAdd('conversation is null');
  120. $notice->whereAdd('conversation = 0', 'OR');
  121. $notice->orderBy('id'); // try to get originals before replies
  122. $notice->find();
  123. while ($notice->fetch()) {
  124. try {
  125. $cid = null;
  126. $orig = clone($notice);
  127. if (!empty($notice->reply_to)) {
  128. $reply = Notice::getKV('id', $notice->reply_to);
  129. if ($reply instanceof Notice && !empty($reply->conversation)) {
  130. $notice->conversation = $reply->conversation;
  131. }
  132. unset($reply);
  133. }
  134. // if still empty
  135. if (empty($notice->conversation)) {
  136. $child = new Notice();
  137. $child->reply_to = $notice->getID();
  138. $child->limit(1);
  139. if ($child->find(true) && !empty($child->conversation)) {
  140. $notice->conversation = $child->conversation;
  141. }
  142. unset($child);
  143. }
  144. // if _still_ empty we just create our own conversation
  145. if (empty($notice->conversation)) {
  146. $notice->conversation = $notice->getID();
  147. }
  148. $result = $notice->update($orig);
  149. unset($orig);
  150. } catch (Exception $e) {
  151. print("Error setting conversation: " . $e->getMessage());
  152. }
  153. }
  154. printfnq("DONE.\n");
  155. }
  156. function fixupGroupURI()
  157. {
  158. printfnq("Ensuring all groups have an URI...");
  159. $group = new User_group();
  160. $group->whereAdd('uri IS NULL');
  161. if ($group->find()) {
  162. while ($group->fetch()) {
  163. $orig = User_group::getKV('id', $group->id);
  164. $group->uri = $group->getUri();
  165. $group->update($orig);
  166. }
  167. }
  168. printfnq("DONE.\n");
  169. }
  170. function initConversation()
  171. {
  172. if (common_config('fix', 'upgrade_initConversation') <= 1) {
  173. printfnq(sprintf("Skipping %s, fixed by previous upgrade.\n", __METHOD__));
  174. return;
  175. }
  176. printfnq("Ensuring all conversations have a row in conversation table...");
  177. $notice = new Notice();
  178. $notice->selectAdd();
  179. $notice->selectAdd('DISTINCT conversation');
  180. $notice->joinAdd(['conversation', 'conversation:id'], 'LEFT'); // LEFT to get the null values for conversation.id
  181. $notice->whereAdd('conversation.id IS NULL');
  182. if ($notice->find()) {
  183. printfnq(" fixing {$notice->N} missing conversation entries...");
  184. }
  185. while ($notice->fetch()) {
  186. $id = $notice->conversation;
  187. $uri = common_local_url('conversation', ['id' => $id]);
  188. // @fixme db_dataobject won't save our value for an autoincrement
  189. // so we're bypassing the insert wrappers
  190. $conv = new Conversation();
  191. $sql = "INSERT INTO conversation (id,uri,created) VALUES (%d,'%s','%s')";
  192. $sql = sprintf(
  193. $sql,
  194. $id,
  195. $conv->escape($uri),
  196. $conv->escape(common_sql_now())
  197. );
  198. $conv->query($sql);
  199. }
  200. // This is something we should only have to do once unless introducing new, bad code.
  201. if (DEBUG) {
  202. printfnq(sprintf('Storing in config that we have done %s', __METHOD__));
  203. }
  204. common_config_set('fix', 'upgrade_initConversation', 1);
  205. printfnq("DONE.\n");
  206. }
  207. function fixupConversationURIs()
  208. {
  209. printfnq("Ensuring all conversations have a URI...");
  210. $conv = new Conversation();
  211. $conv->whereAdd('uri IS NULL');
  212. if ($conv->find()) {
  213. $rounds = 0;
  214. while ($conv->fetch()) {
  215. $uri = common_local_url('conversation', ['id' => $conv->id]);
  216. $sql = sprintf(
  217. 'UPDATE conversation SET uri = \'%1$s\' WHERE id = %2$d;',
  218. $conv->escape($uri),
  219. $conv->id
  220. );
  221. $conv->query($sql);
  222. if (($conv->N-++$rounds) % 500 == 0) {
  223. printfnq(sprintf(' %d items left...', $conv->N-$rounds));
  224. }
  225. }
  226. }
  227. printfnq("DONE.\n");
  228. }
  229. function initGroupProfileId()
  230. {
  231. printfnq("Ensuring all User_group entries have a Profile and profile_id...");
  232. $group = new User_group();
  233. $group->whereAdd('NOT EXISTS (SELECT id FROM profile WHERE id = user_group.profile_id)');
  234. $group->find();
  235. while ($group->fetch()) {
  236. try {
  237. // We must create a new, incrementally assigned profile_id
  238. $profile = new Profile();
  239. $profile->nickname = $group->nickname;
  240. $profile->fullname = $group->fullname;
  241. $profile->profileurl = $group->mainpage;
  242. $profile->homepage = $group->homepage;
  243. $profile->bio = $group->description;
  244. $profile->location = $group->location;
  245. $profile->created = $group->created;
  246. $profile->modified = $group->modified;
  247. $profile->query('BEGIN');
  248. $id = $profile->insert();
  249. if (empty($id)) {
  250. $profile->query('ROLLBACK');
  251. throw new Exception('Profile insertion failed, profileurl: '.$profile->profileurl);
  252. }
  253. $group->query("UPDATE user_group SET profile_id={$id} WHERE id={$group->id}");
  254. $profile->query('COMMIT');
  255. $profile->free();
  256. } catch (Exception $e) {
  257. printfv("Error initializing Profile for group {$group->nickname}:" . $e->getMessage());
  258. }
  259. }
  260. printfnq("DONE.\n");
  261. }
  262. function initLocalGroup()
  263. {
  264. printfnq("Ensuring all local user groups have a local_group...");
  265. $group = new User_group();
  266. $group->whereAdd('NOT EXISTS (select group_id from local_group where group_id = user_group.id)');
  267. $group->find();
  268. while ($group->fetch()) {
  269. try {
  270. // Hack to check for local groups
  271. if ($group->getUri() == common_local_url('groupbyid', ['id' => $group->id])) {
  272. $lg = new Local_group();
  273. $lg->group_id = $group->id;
  274. $lg->nickname = $group->nickname;
  275. $lg->created = $group->created; // XXX: common_sql_now() ?
  276. $lg->modified = $group->modified;
  277. $lg->insert();
  278. }
  279. } catch (Exception $e) {
  280. printfv("Error initializing local group for {$group->nickname}:" . $e->getMessage());
  281. }
  282. }
  283. printfnq("DONE.\n");
  284. }
  285. function initNoticeReshare()
  286. {
  287. if (common_config('fix', 'upgrade_initNoticeReshare') <= 1) {
  288. printfnq(sprintf("Skipping %s, fixed by previous upgrade.\n", __METHOD__));
  289. return;
  290. }
  291. printfnq("Ensuring all reshares have the correct verb and object-type...");
  292. $notice = new Notice();
  293. $notice->whereAdd('repeat_of is not null');
  294. $notice->whereAdd('(verb != "'.ActivityVerb::SHARE.'" 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();