Merge pull request #13872 from friendica/issue-13845
[friendica.git/.git] / update.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
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
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (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 <https://www.gnu.org/licenses/>.
19  *
20  * Automatic post-database structure change updates
21  *
22  * These functions are responsible for doing critical post update changes to the data (not the structure) in the database.
23  *
24  * Database structure changes are done in static/dbstructure.config.php
25  *
26  * For non-critical database migrations, please add a method in the Database\PostUpdate class
27  *
28  * If there is a need for a post update to a structure change, update this file
29  * by adding a new function at the end with the number of the new DB_UPDATE_VERSION.
30  *
31  * The numbered script in this file has to be exactly like the DB_UPDATE_VERSION
32  *
33  * Example:
34  * You are currently on version 4711 and you are preparing changes that demand an update script.
35  *
36  * 1. Create a function "update_4712()" here in the update.php
37  * 2. Apply the needed structural changes in static/dbStructure.php
38  * 3. Set DB_UPDATE_VERSION in static/dbstructure.config.php to 4712.
39  *
40  * If you need to run a script before the database update, name the function "pre_update_4712()"
41  */
42
43 use Friendica\Core\Config\ValueObject\Cache;
44 use Friendica\Core\Logger;
45 use Friendica\Core\Protocol;
46 use Friendica\Core\Storage\Capability\ICanReadFromStorage;
47 use Friendica\Core\Storage\Type\Database as DatabaseStorage;
48 use Friendica\Core\Update;
49 use Friendica\Core\Worker;
50 use Friendica\Database\Database;
51 use Friendica\Database\DBA;
52 use Friendica\Database\DBStructure;
53 use Friendica\DI;
54 use Friendica\Model\Contact;
55 use Friendica\Model\Item;
56 use Friendica\Model\ItemURI;
57 use Friendica\Model\Notification;
58 use Friendica\Model\Photo;
59 use Friendica\Model\Post;
60 use Friendica\Model\Profile;
61 use Friendica\Model\User;
62 use Friendica\Protocol\Activity;
63 use Friendica\Protocol\Delivery;
64 use Friendica\Security\PermissionSet\Repository\PermissionSet;
65 use Friendica\Util\DateTimeFormat;
66
67 // Post-update script of PR 5751
68 function update_1298()
69 {
70         $keys = ['gender', 'marital', 'sexual'];
71         foreach ($keys as $translateKey) {
72                 $allData = DBA::select('profile', ['id', $translateKey]);
73                 $allLangs = DI::l10n()->getAvailableLanguages();
74                 $success = 0;
75                 $fail = 0;
76                 foreach ($allData as $key => $data) {
77                         $toTranslate = $data[$translateKey];
78                         if ($toTranslate != '') {
79                                 foreach ($allLangs as $key => $lang) {
80                                         $a = new \stdClass();
81                                         $a->strings = [];
82
83                                         // First we get the localizations
84                                         if (file_exists('view/lang/$lang/strings.php')) {
85                                                 include 'view/lang/$lang/strings.php';
86                                         }
87                                         if (file_exists('addon/morechoice/lang/$lang/strings.php')) {
88                                                 include 'addon/morechoice/lang/$lang/strings.php';
89                                         }
90
91                                         $localizedStrings = $a->strings;
92                                         unset($a);
93
94                                         $key = array_search($toTranslate, $localizedStrings);
95                                         if ($key !== false) {
96                                                 break;
97                                         }
98
99                                         // defaulting to empty string
100                                         $key = '';
101                                 }
102
103                                 if ($key == '') {
104                                         $fail++;
105                                 } else {
106                                         DBA::update('profile', [$translateKey => $key], ['id' => $data['id']]);
107                                         Logger::notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key,
108                                                 'was' => $data[$translateKey]]);
109
110                                         Contact::updateSelfFromUserID($data['id']);
111                                         Profile::publishUpdate($data['id']);
112                                         $success++;
113                                 }
114                         }
115                 }
116
117                 Logger::notice($translateKey . ' fix completed', ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]);
118         }
119         return Update::SUCCESS;
120 }
121
122 function update_1309()
123 {
124         $queue = DBA::select('queue', ['id', 'cid', 'guid']);
125         while ($entry = DBA::fetch($queue)) {
126                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $entry['cid']]);
127                 if (!DBA::isResult($contact)) {
128                         continue;
129                 }
130
131                 $item = Post::selectFirst(['id', 'gravity'], ['uid' => $contact['uid'], 'guid' => $entry['guid']]);
132                 if (!DBA::isResult($item)) {
133                         continue;
134                 }
135
136                 $deliver_options = ['priority' => Worker::PRIORITY_MEDIUM, 'dont_fork' => true];
137                 Worker::add($deliver_options, 'Delivery', Delivery::POST, $item['id'], $entry['cid']);
138                 Logger::info('Added delivery worker', ['item' => $item['id'], 'contact' => $entry['cid']]);
139                 DBA::delete('queue', ['id' => $entry['id']]);
140         }
141         return Update::SUCCESS;
142 }
143
144 function update_1315()
145 {
146         if (DBStructure::existsTable('item-delivery-data')) {
147                 DBA::delete('item-delivery-data', ['postopts' => '', 'inform' => '', 'queue_count' => 0, 'queue_done' => 0]);
148         }
149         return Update::SUCCESS;
150 }
151
152 function update_1318()
153 {
154         DBA::update('profile', ['marital' => 'In a relation'], ['marital' => 'Unavailable']);
155         DBA::update('profile', ['marital' => 'Single'], ['marital' => 'Available']);
156
157         Worker::add(Worker::PRIORITY_LOW, 'ProfileUpdate');
158         return Update::SUCCESS;
159 }
160
161 function update_1323()
162 {
163         $users = DBA::select('user', ['uid']);
164         while ($user = DBA::fetch($users)) {
165                 if (Contact::updateSelfFromUserID($user['uid'])) {
166                         Profile::publishUpdate($user['uid']);
167                 }
168         }
169         DBA::close($users);
170
171         return Update::SUCCESS;
172 }
173
174 function update_1327()
175 {
176         $contacts = DBA::select('contact', ['uid', 'id', 'blocked', 'readonly'], ["`uid` != ? AND (`blocked` OR `readonly`) AND NOT `pending`", 0]);
177         while ($contact = DBA::fetch($contacts)) {
178                 Contact\User::setBlocked($contact['id'], $contact['uid'], $contact['blocked']);
179                 Contact\User::setIgnored($contact['id'], $contact['uid'], $contact['readonly']);
180         }
181         DBA::close($contacts);
182
183         return Update::SUCCESS;
184 }
185
186 function update_1330()
187 {
188         $currStorage = DI::config()->get('storage', 'class', '');
189
190         // set the name of the storage instead of the classpath as config
191         if (!empty($currStorage)) {
192                 /** @var ICanReadFromStorage $currStorage */
193                 if (!DI::config()->set('storage', 'name', $currStorage::getName())) {
194                         return Update::FAILED;
195                 }
196
197                 // try to delete the class since it isn't needed. This won't work with config files
198                 DI::config()->delete('storage', 'class');
199         }
200
201         // Update attachments and photos
202         if (!DBA::e("UPDATE `photo` SET `photo`.`backend-class` = SUBSTR(`photo`.`backend-class`, 25) WHERE `photo`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'") ||
203             !DBA::e("UPDATE `attach` SET `attach`.`backend-class` = SUBSTR(`attach`.`backend-class`, 25) WHERE `attach`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'")) {
204                 return Update::FAILED;
205         };
206
207         return Update::SUCCESS;
208 }
209
210 function update_1332()
211 {
212         $condition = ["`is-default` IS NOT NULL"];
213         $profiles = DBA::select('profile', [], $condition);
214
215         while ($profile = DBA::fetch($profiles)) {
216                 Profile::migrate($profile);
217         }
218         DBA::close($profiles);
219
220         DBA::update('contact', ['profile-id' => null], ['`profile-id` IS NOT NULL']);
221
222         return Update::SUCCESS;
223 }
224
225 function update_1347()
226 {
227         foreach (Item::ACTIVITIES as $index => $activity) {
228                 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
229         }
230
231         return Update::SUCCESS;
232 }
233
234 function pre_update_1348()
235 {
236         if (!DBA::exists('contact', ['id' => 0])) {
237                 DBA::insert('contact', ['nurl' => '']);
238                 $lastid = DBA::lastInsertId();
239                 if ($lastid != 0) {
240                         DBA::update('contact', ['id' => 0], ['id' => $lastid]);
241                 }
242         }
243
244         // The tables "permissionset" and "tag" could or could not exist during the update.
245         // This depends upon the previous version. Depending upon this situation we have to add
246         // the "0" values before adding the foreign keys - or after would be sufficient.
247
248         update_1348();
249
250         if (DBStructure::existsTable('auth_codes') && DBStructure::existsTable('clients')) {
251                 DBA::e("DELETE FROM `auth_codes` WHERE NOT `client_id` IN (SELECT `client_id` FROM `clients`)");
252         }
253         if (DBStructure::existsTable('tokens') && DBStructure::existsTable('clients')) {
254                 DBA::e("DELETE FROM `tokens` WHERE NOT `client_id` IN (SELECT `client_id` FROM `clients`)");
255         }
256         return Update::SUCCESS;
257 }
258
259 function update_1348()
260 {
261         // Insert a permissionset with id=0
262         // Inserting it without an ID and then changing the value to 0 tricks the auto increment
263         if (!DBA::exists('permissionset', ['id' => 0])) {
264                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
265                 $lastid = DBA::lastInsertId();
266                 if ($lastid != 0) {
267                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
268                 }
269         }
270
271         if (!DBA::exists('tag', ['id' => 0])) {
272                 DBA::insert('tag', ['name' => '']);
273                 $lastid = DBA::lastInsertId();
274                 if ($lastid != 0) {
275                         DBA::update('tag', ['id' => 0], ['id' => $lastid]);
276                 }
277         }
278
279         return Update::SUCCESS;
280 }
281
282 function update_1349()
283 {
284         if (!DBStructure::existsTable('item-activity')) {
285                 return Update::SUCCESS;
286         }
287
288         $correct = true;
289         foreach (Item::ACTIVITIES as $index => $activity) {
290                 if (!DBA::exists('verb', ['id' => $index + 1, 'name' => $activity])) {
291                         $correct = false;
292                 }
293         }
294
295         if (!$correct) {
296                 // The update failed - but it cannot be recovered, since the data doesn't match our expectation
297                 // This means that we can't use this "shortcut" to fill the "vid" field and we have to rely upon
298                 // the postupdate. This is not fatal, but means that it will take some longer time for the system
299                 // to fill all data.
300                 return Update::SUCCESS;
301         }
302
303         if (!DBA::e("UPDATE `item` INNER JOIN `item-activity` ON `item`.`uri-id` = `item-activity`.`uri-id`
304                 SET `vid` = `item-activity`.`activity` + 1 WHERE `gravity` = ? AND (`vid` IS NULL OR `vid` = 0)", Item::GRAVITY_ACTIVITY)) {
305                 return Update::FAILED;
306         }
307
308         return Update::SUCCESS;
309 }
310
311 function update_1351()
312 {
313         if (DBStructure::existsTable('thread') && !DBA::e("UPDATE `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`id` SET `thread`.`uri-id` = `item`.`uri-id`")) {
314                 return Update::FAILED;
315         }
316
317         return Update::SUCCESS;
318 }
319
320 function pre_update_1354()
321 {
322         if (DBStructure::existsColumn('contact', ['ffi_keyword_blacklist'])
323                 && !DBStructure::existsColumn('contact', ['ffi_keyword_denylist'])
324                 && !DBA::e("ALTER TABLE `contact` CHANGE `ffi_keyword_blacklist` `ffi_keyword_denylist` text null")) {
325                 return Update::FAILED;
326         }
327         return Update::SUCCESS;
328 }
329
330 function update_1354()
331 {
332         if (DBStructure::existsColumn('contact', ['ffi_keyword_blacklist'])
333                 && DBStructure::existsColumn('contact', ['ffi_keyword_denylist'])) {
334                 if (!DBA::e("UPDATE `contact` SET `ffi_keyword_denylist` = `ffi_keyword_blacklist`")) {
335                         return Update::FAILED;
336                 }
337
338                 // When the data had been copied then the main task is done.
339                 // Having the old field removed is only beauty but not crucial.
340                 // So we don't care if this was successful or not.
341                 DBA::e("ALTER TABLE `contact` DROP `ffi_keyword_blacklist`");
342         }
343         return Update::SUCCESS;
344 }
345
346 function update_1357()
347 {
348         if (!DBA::e("UPDATE `contact` SET `failed` = true WHERE `success_update` < `failure_update` AND `failed` IS NULL")) {
349                 return Update::FAILED;
350         }
351
352         if (!DBA::e("UPDATE `contact` SET `failed` = false WHERE `success_update` > `failure_update` AND `failed` IS NULL")) {
353                 return Update::FAILED;
354         }
355
356         if (!DBA::e("UPDATE `contact` SET `failed` = false WHERE `updated` > `failure_update` AND `failed` IS NULL")) {
357                 return Update::FAILED;
358         }
359
360         if (!DBA::e("UPDATE `contact` SET `failed` = false WHERE `last-item` > `failure_update` AND `failed` IS NULL")) {
361                 return Update::FAILED;
362         }
363
364         if (!DBA::e("UPDATE `gserver` SET `failed` = true WHERE `last_contact` < `last_failure` AND `failed` IS NULL")) {
365                 return Update::FAILED;
366         }
367
368         if (!DBA::e("UPDATE `gserver` SET `failed` = false WHERE `last_contact` > `last_failure` AND `failed` IS NULL")) {
369                 return Update::FAILED;
370         }
371
372         return Update::SUCCESS;
373 }
374
375 function pre_update_1358()
376 {
377         if (!DBA::e("DELETE FROM `contact-relation` WHERE NOT `relation-cid` IN (SELECT `id` FROM `contact`) OR NOT `cid` IN (SELECT `id` FROM `contact`)")) {
378                 return Update::FAILED;
379         }
380
381         return Update::SUCCESS;
382 }
383
384 function pre_update_1363()
385 {
386         Photo::delete(["`contact-id` != ? AND NOT `contact-id` IN (SELECT `id` FROM `contact`)", 0]);
387         return Update::SUCCESS;
388 }
389
390 function pre_update_1364()
391 {
392         if (!DBA::e("DELETE FROM `2fa_recovery_codes` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
393                 return Update::FAILED;
394         }
395
396         if (!DBA::e("DELETE FROM `2fa_app_specific_password` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
397                 return Update::FAILED;
398         }
399
400         if (!DBA::e("DELETE FROM `attach` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
401                 return Update::FAILED;
402         }
403
404         if (DBStructure::existsTable('clients') && !DBA::e("DELETE FROM `clients` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
405                 return Update::FAILED;
406         }
407
408         if (!DBA::e("DELETE FROM `conv` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
409                 return Update::FAILED;
410         }
411
412         if (!DBA::e("DELETE FROM `fsuggest` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
413                 return Update::FAILED;
414         }
415
416         if (!DBA::e("DELETE FROM `group` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
417                 return Update::FAILED;
418         }
419
420         if (!DBA::e("DELETE FROM `intro` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
421                 return Update::FAILED;
422         }
423
424         if (!DBA::e("DELETE FROM `manage` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
425                 return Update::FAILED;
426         }
427
428         if (!DBA::e("DELETE FROM `manage` WHERE NOT `mid` IN (SELECT `uid` FROM `user`)")) {
429                 return Update::FAILED;
430         }
431
432         if (!DBA::e("DELETE FROM `mail` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
433                 return Update::FAILED;
434         }
435
436         if (!DBA::e("DELETE FROM `mailacct` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
437                 return Update::FAILED;
438         }
439
440         if (!DBA::e("DELETE FROM `notify` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
441                 return Update::FAILED;
442         }
443
444         if (!DBA::e("DELETE FROM `openwebauth-token` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
445                 return Update::FAILED;
446         }
447
448         if (!DBA::e("DELETE FROM `pconfig` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
449                 return Update::FAILED;
450         }
451
452         if (!DBA::e("DELETE FROM `profile` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
453                 return Update::FAILED;
454         }
455
456         if (DBStructure::existsTable('profile_check') && !DBA::e("DELETE FROM `profile_check` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
457                 return Update::FAILED;
458         }
459
460         if (!DBA::e("DELETE FROM `profile_field` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
461                 return Update::FAILED;
462         }
463
464         if (!DBA::e("DELETE FROM `push_subscriber` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
465                 return Update::FAILED;
466         }
467
468         if (!DBA::e("DELETE FROM `register` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
469                 return Update::FAILED;
470         }
471
472         if (!DBA::e("DELETE FROM `search` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
473                 return Update::FAILED;
474         }
475
476         if (DBStructure::existsTable('tokens') && !DBA::e("DELETE FROM `tokens` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
477                 return Update::FAILED;
478         }
479
480         if (!DBA::e("DELETE FROM `user-contact` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
481                 return Update::FAILED;
482         }
483
484         if (DBStructure::existsTable('user-item') && !DBA::e("DELETE FROM `user-item` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
485                 return Update::FAILED;
486         }
487
488         if (!DBA::e("DELETE FROM `notify-threads` WHERE NOT `receiver-uid` IN (SELECT `uid` FROM `user`)")) {
489                 return Update::FAILED;
490         }
491
492         if (!DBA::e("DELETE FROM `event` WHERE NOT `cid` IN (SELECT `id` FROM `contact`)")) {
493                 return Update::FAILED;
494         }
495
496         if (!DBA::e("DELETE FROM `fsuggest` WHERE NOT `cid` IN (SELECT `id` FROM `contact`)")) {
497                 return Update::FAILED;
498         }
499
500         if (!DBA::e("DELETE FROM `group_member` WHERE NOT `contact-id` IN (SELECT `id` FROM `contact`)")) {
501                 return Update::FAILED;
502         }
503
504         if (!DBA::e("DELETE FROM `intro` WHERE NOT `contact-id` IN (SELECT `id` FROM `contact`)")) {
505                 return Update::FAILED;
506         }
507
508         if (DBStructure::existsTable('profile_check') && !DBA::e("DELETE FROM `profile_check` WHERE NOT `cid` IN (SELECT `id` FROM `contact`)")) {
509                 return Update::FAILED;
510         }
511
512         if (!DBA::e("DELETE FROM `user-contact` WHERE NOT `cid` IN (SELECT `id` FROM `contact`)")) {
513                 return Update::FAILED;
514         }
515
516         if (!DBA::e("DELETE FROM `group_member` WHERE NOT `gid` IN (SELECT `id` FROM `group`)")) {
517                 return Update::FAILED;
518         }
519
520         if (!DBA::e("DELETE FROM `gserver-tag` WHERE NOT `gserver-id` IN (SELECT `id` FROM `gserver`)")) {
521                 return Update::FAILED;
522         }
523
524         if (DBStructure::existsTable('user-item') && !DBA::e("DELETE FROM `user-item` WHERE NOT `iid` IN (SELECT `id` FROM `item`)")) {
525                 return Update::FAILED;
526         }
527
528         return Update::SUCCESS;
529 }
530
531 function pre_update_1365()
532 {
533         if (!DBA::e("DELETE FROM `notify-threads` WHERE NOT `notify-id` IN (SELECT `id` FROM `notify`)")) {
534                 return Update::FAILED;
535         }
536
537         if (DBStructure::existsTable('thread') && !DBA::e("DELETE FROM `thread` WHERE NOT `iid` IN (SELECT `id` FROM `item`)")) {
538                 return Update::FAILED;
539         }
540
541         return Update::SUCCESS;
542 }
543
544 function update_1375()
545 {
546         if (!DBA::e("UPDATE `item` SET `thr-parent` = `parent-uri`, `thr-parent-id` = `parent-uri-id` WHERE `thr-parent` = ''")) {
547                 return Update::FAILED;
548         }
549
550         return Update::SUCCESS;
551 }
552
553 function pre_update_1376()
554 {
555         // Insert a user with uid=0
556         DBStructure::checkInitialValues();
557
558         if (!DBA::e("DELETE FROM `item` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
559                 return Update::FAILED;
560         }
561
562         if (!DBA::e("DELETE FROM `event` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
563                 return Update::FAILED;
564         }
565
566         if (DBStructure::existsTable('thread') && !DBA::e("DELETE FROM `thread` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
567                 return Update::FAILED;
568         }
569
570         if (!DBA::e("DELETE FROM `permissionset` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
571                 return Update::FAILED;
572         }
573
574         if (!DBA::e("DELETE FROM `openwebauth-token` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
575                 return Update::FAILED;
576         }
577
578         if (!DBA::e("DELETE FROM `post-category` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
579                 return Update::FAILED;
580         }
581
582         Photo::delete(["NOT `uid` IN (SELECT `uid` FROM `user`)"]);
583
584         if (!DBA::e("DELETE FROM `contact` WHERE NOT `uid` IN (SELECT `uid` FROM `user`)")) {
585                 return Update::FAILED;
586         }
587
588         return Update::SUCCESS;
589 }
590
591 function pre_update_1377()
592 {
593         DBStructure::checkInitialValues();
594
595         if (!DBA::e("DELETE FROM `item` WHERE NOT `author-id` IN (SELECT `id` FROM `contact`)")) {
596                 return Update::FAILED;
597         }
598
599         if (!DBA::e("DELETE FROM `item` WHERE NOT `owner-id` IN (SELECT `id` FROM `contact`)")) {
600                 return Update::FAILED;
601         }
602
603         if (!DBA::e("UPDATE `item` SET `contact-id` = `owner-id` WHERE NOT `contact-id` IN (SELECT `id` FROM `contact`)")) {
604                 return Update::FAILED;
605         }
606
607         if (DBStructure::existsTable('thread') && !DBA::e("DELETE FROM `thread` WHERE NOT `author-id` IN (SELECT `id` FROM `contact`)")) {
608                 return Update::FAILED;
609         }
610
611         if (DBStructure::existsTable('thread') && !DBA::e("DELETE FROM `thread` WHERE NOT `owner-id` IN (SELECT `id` FROM `contact`)")) {
612                 return Update::FAILED;
613         }
614
615         if (DBStructure::existsTable('thread') && !DBA::e("UPDATE `thread` SET `contact-id` = `owner-id` WHERE NOT `contact-id` IN (SELECT `id` FROM `contact`)")) {
616                 return Update::FAILED;
617         }
618
619         if (!DBA::e("UPDATE `notify` SET `uri-id` = NULL WHERE `uri-id` = 0")) {
620                 return Update::FAILED;
621         }
622
623         if (DBStructure::existsTable('diaspora-interaction') && !DBA::e("DELETE FROM `diaspora-interaction` WHERE `uri-id` NOT IN (SELECT `id` FROM `item-uri`)")) {
624                 return Update::FAILED;
625         }
626
627         if (DBStructure::existsTable('item-activity') && !DBA::e("DELETE FROM `item-activity` WHERE `uri-id` NOT IN (SELECT `id` FROM `item-uri`)")) {
628                 return Update::FAILED;
629         }
630
631         if (DBStructure::existsTable('item-content') && !DBA::e("DELETE FROM `item-content` WHERE `uri-id` NOT IN (SELECT `id` FROM `item-uri`)")) {
632                 return Update::FAILED;
633         }
634
635         if (!DBA::e("DELETE FROM `notify` WHERE `uri-id` NOT IN (SELECT `id` FROM `item-uri`)")) {
636                 return Update::FAILED;
637         }
638
639         if (!DBA::e("UPDATE `notify` SET `parent-uri-id` = NULL WHERE `parent-uri-id` = 0")) {
640                 return Update::FAILED;
641         }
642         if (!DBA::e("DELETE FROM `notify` WHERE `parent-uri-id` NOT IN (SELECT `id` FROM `item-uri`)")) {
643                 return Update::FAILED;
644         }
645
646         if (!DBA::e("UPDATE `notify-threads` SET `master-parent-uri-id` = NULL WHERE `master-parent-uri-id` = 0")) {
647                 return Update::FAILED;
648         }
649
650         if (!DBA::e("DELETE FROM `notify-threads` WHERE `master-parent-uri-id` NOT IN (SELECT `id` FROM `item-uri`)")) {
651                 return Update::FAILED;
652         }
653
654         if (!DBA::e("DELETE FROM `notify-threads` WHERE `master-parent-item` NOT IN (SELECT `id` FROM `item`)")) {
655                 return Update::FAILED;
656         }
657
658         return Update::SUCCESS;
659 }
660
661 function update_1380()
662 {
663         if (!DBA::e("UPDATE `notify` INNER JOIN `item` ON `item`.`id` = `notify`.`iid` SET `notify`.`uri-id` = `item`.`uri-id` WHERE `notify`.`uri-id` IS NULL AND `notify`.`otype` IN (?, ?)",
664                 Notification\ObjectType::ITEM, Notification\ObjectType::PERSON)) {
665                 return Update::FAILED;
666         }
667
668         if (!DBA::e("UPDATE `notify` INNER JOIN `item` ON `item`.`id` = `notify`.`parent` SET `notify`.`parent-uri-id` = `item`.`uri-id` WHERE `notify`.`parent-uri-id` IS NULL AND `notify`.`otype` IN (?, ?)",
669                 Notification\ObjectType::ITEM, Notification\ObjectType::PERSON)) {
670                 return Update::FAILED;
671         }
672
673         return Update::SUCCESS;
674 }
675
676 function pre_update_1395()
677 {
678         if (DBStructure::existsTable('post-user') && !DBStructure::existsColumn('post-user', ['id']) && !DBA::e("DROP TABLE `post-user`")) {
679                 return Update::FAILED;
680         }
681         return Update::SUCCESS;
682 }
683
684 function update_1395()
685 {
686         if (!DBA::e("INSERT INTO `post-user`(`id`, `uri-id`, `uid`, `contact-id`, `unseen`, `origin`, `psid`)
687                 SELECT `id`, `uri-id`, `uid`, `contact-id`, `unseen`, `origin`, `psid` FROM `item`
688                 ON DUPLICATE KEY UPDATE `contact-id` = `item`.`contact-id`, `unseen` = `item`.`unseen`, `origin` = `item`.`origin`, `psid` = `item`.`psid`")) {
689                 return Update::FAILED;
690         }
691
692         if (DBStructure::existsTable('user-item') && !DBA::e("INSERT INTO `post-user`(`uri-id`, `uid`, `hidden`, `notification-type`)
693                 SELECT `uri-id`, `user-item`.`uid`, `hidden`,`notification-type` FROM `user-item`
694                         INNER JOIN `item` ON `item`.`id` = `user-item`.`iid`
695                 ON DUPLICATE KEY UPDATE `hidden` = `user-item`.`hidden`, `notification-type` = `user-item`.`notification-type`")) {
696                 return Update::FAILED;
697         }
698         return Update::SUCCESS;
699 }
700
701 function update_1396()
702 {
703         if (!DBStructure::existsTable('item-content')) {
704                 return Update::SUCCESS;
705         }
706
707         if (DBStructure::existsColumn('item-content', ['raw-body'])) {
708                 if (!DBA::e("INSERT IGNORE INTO `post-content`(`uri-id`, `title`, `content-warning`, `body`, `raw-body`,
709                         `location`, `coord`, `language`, `app`, `rendered-hash`, `rendered-html`,
710                         `object-type`, `object`, `target-type`, `target`, `resource-id`, `plink`)
711                         SELECT `item-content`.`uri-id`, `item-content`.`title`, `item-content`.`content-warning`,
712                                 `item-content`.`body`, `item-content`.`raw-body`, `item-content`.`location`, `item-content`.`coord`,
713                                 `item-content`.`language`, `item-content`.`app`, `item-content`.`rendered-hash`,
714                                 `item-content`.`rendered-html`, `item-content`.`object-type`, `item-content`.`object`,
715                                 `item-content`.`target-type`, `item-content`.`target`, `item`.`resource-id`, `item-content`.`plink`
716                                 FROM `item-content` INNER JOIN `item` ON `item`.`uri-id` = `item-content`.`uri-id`")) {
717                         return Update::FAILED;
718                 }
719         } else {
720                 if (!DBA::e("INSERT IGNORE INTO `post-content`(`uri-id`, `title`, `content-warning`, `body`,
721                         `location`, `coord`, `language`, `app`, `rendered-hash`, `rendered-html`,
722                         `object-type`, `object`, `target-type`, `target`, `resource-id`, `plink`)
723                         SELECT `item-content`.`uri-id`, `item-content`.`title`, `item-content`.`content-warning`,
724                                 `item-content`.`body`, `item-content`.`location`, `item-content`.`coord`,
725                                 `item-content`.`language`, `item-content`.`app`, `item-content`.`rendered-hash`,
726                                 `item-content`.`rendered-html`, `item-content`.`object-type`, `item-content`.`object`,
727                                 `item-content`.`target-type`, `item-content`.`target`, `item`.`resource-id`, `item-content`.`plink`
728                                 FROM `item-content` INNER JOIN `item` ON `item`.`uri-id` = `item-content`.`uri-id`")) {
729                         return Update::FAILED;
730                 }
731         }
732         return Update::SUCCESS;
733 }
734
735 function update_1397()
736 {
737         if (!DBA::e("INSERT INTO `post-user-notification`(`uri-id`, `uid`, `notification-type`)
738                 SELECT `uri-id`, `uid`, `notification-type` FROM `post-user` WHERE `notification-type` != 0
739                 ON DUPLICATE KEY UPDATE `uri-id` = `post-user`.`uri-id`, `uid` = `post-user`.`uid`, `notification-type` = `post-user`.`notification-type`")) {
740                 return Update::FAILED;
741         }
742
743         if (!DBStructure::existsTable('user-item')) {
744                 return Update::SUCCESS;
745         }
746
747         if (!DBA::e("INSERT INTO `post-user-notification`(`uri-id`, `uid`, `notification-type`)
748                 SELECT `uri-id`, `user-item`.`uid`, `notification-type` FROM `user-item`
749                         INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` WHERE `notification-type` != 0
750                 ON DUPLICATE KEY UPDATE `notification-type` = `user-item`.`notification-type`")) {
751                 return Update::FAILED;
752         }
753
754         if (!DBStructure::existsTable('thread')) {
755                 return Update::SUCCESS;
756         }
757
758         if (!DBA::e("INSERT IGNORE INTO `post-thread-user`(`uri-id`, `uid`, `pinned`, `starred`, `ignored`, `wall`, `pubmail`, `forum_mode`)
759                 SELECT `thread`.`uri-id`, `thread`.`uid`, `user-item`.`pinned`, `thread`.`starred`,
760                         `thread`.`ignored`, `thread`.`wall`, `thread`.`pubmail`, `thread`.`forum_mode`
761                 FROM `thread` LEFT JOIN `user-item` ON `user-item`.`iid` = `thread`.`iid`")) {
762                 return Update::FAILED;
763         }
764
765         return Update::SUCCESS;
766 }
767
768 function update_1398()
769 {
770         if (!DBStructure::existsTable('thread')) {
771                 return Update::SUCCESS;
772         }
773
774         if (!DBA::e("INSERT IGNORE INTO `post-thread` (`uri-id`, `owner-id`, `author-id`, `network`, `created`, `received`, `changed`, `commented`)
775                 SELECT `uri-id`, `owner-id`, `author-id`, `network`, `created`, `received`, `changed`, `commented` FROM `thread`")) {
776                         return Update::FAILED;
777         }
778
779         if (!DBStructure::existsTable('thread')) {
780                 return Update::SUCCESS;
781         }
782
783         if (!DBA::e("UPDATE `post-thread-user` INNER JOIN `thread` ON `thread`.`uid` = `post-thread-user`.`uid` AND `thread`.`uri-id` = `post-thread-user`.`uri-id`
784                 SET `post-thread-user`.`mention` = `thread`.`mention`")) {
785                         return Update::FAILED;
786         }
787
788         return Update::SUCCESS;
789 }
790
791 function update_1399()
792 {
793         if (!DBA::e("UPDATE `post-thread-user` INNER JOIN `post-user` ON `post-user`.`uid` = `post-thread-user`.`uid` AND `post-user`.`uri-id` = `post-thread-user`.`uri-id`
794                 SET `post-thread-user`.`contact-id` = `post-user`.`contact-id`, `post-thread-user`.`unseen` = `post-user`.`unseen`,
795                 `post-thread-user`.`hidden` = `post-user`.`hidden`, `post-thread-user`.`origin` = `post-user`.`origin`,
796                 `post-thread-user`.`psid` = `post-user`.`psid`, `post-thread-user`.`post-user-id` = `post-user`.`id`")) {
797                         return Update::FAILED;
798         }
799
800         return Update::SUCCESS;
801 }
802
803 function update_1400()
804 {
805         if (!DBA::e("INSERT IGNORE INTO `post` (`uri-id`, `parent-uri-id`, `thr-parent-id`, `owner-id`, `author-id`, `network`,
806                 `created`, `received`, `edited`, `gravity`, `causer-id`, `post-type`, `vid`, `private`, `visible`, `deleted`, `global`)
807                 SELECT `uri-id`, `parent-uri-id`, `thr-parent-id`, `owner-id`, `author-id`, `network`, `created`, `received`, `edited`,
808                         `gravity`, `causer-id`, `post-type`, `vid`, `private`, `visible`, `deleted`, `global` FROM `item`")) {
809                         return Update::FAILED;
810         }
811
812         if (!DBA::e("UPDATE `post-user` INNER JOIN `item` ON `item`.`uri-id` = `post-user`.`uri-id` AND `item`.`uid` = `post-user`.`uid`
813                 INNER JOIN `event` ON `item`.`event-id` = `event`.`id` AND `event`.`id` != 0
814                 SET `post-user`.`event-id` = `item`.`event-id`")) {
815                 return Update::FAILED;
816         }
817
818         if (!DBA::e("UPDATE `post-user` INNER JOIN `item` ON `item`.`uri-id` = `post-user`.`uri-id` AND `item`.`uid` = `post-user`.`uid`
819                 SET `post-user`.`wall` = `item`.`wall`, `post-user`.`parent-uri-id` = `item`.`parent-uri-id`,
820                 `post-user`.`thr-parent-id` = `item`.`thr-parent-id`,
821                 `post-user`.`created` = `item`.`created`, `post-user`.`edited` = `item`.`edited`,
822                 `post-user`.`received` = `item`.`received`, `post-user`.`gravity` = `item`.`gravity`,
823                 `post-user`.`network` = `item`.`network`, `post-user`.`owner-id` = `item`.`owner-id`,
824                 `post-user`.`author-id` = `item`.`author-id`, `post-user`.`causer-id` = `item`.`causer-id`,
825                 `post-user`.`post-type` = `item`.`post-type`, `post-user`.`vid` = `item`.`vid`,
826                 `post-user`.`private` = `item`.`private`, `post-user`.`global` = `item`.`global`,
827                 `post-user`.`visible` = `item`.`visible`, `post-user`.`deleted` = `item`.`deleted`")) {
828                 return Update::FAILED;
829         }
830
831         if (!DBA::e("INSERT IGNORE INTO `post-thread-user` (`uri-id`, `owner-id`, `author-id`, `causer-id`, `network`,
832                 `created`, `received`, `changed`, `commented`, `uid`,  `wall`, `contact-id`, `unseen`, `hidden`, `origin`, `psid`, `post-user-id`)
833                 SELECT `uri-id`, `owner-id`, `author-id`, `causer-id`, `network`, `created`, `received`, `received`, `received`,
834                         `uid`, `wall`, `contact-id`, `unseen`, `hidden`, `origin`, `psid`, `id`
835                 FROM `post-user` WHERE `gravity` = 0 AND NOT EXISTS(SELECT `uri-id` FROM `post-thread-user` WHERE `post-user-id` = `post-user`.id)")) {
836                 return Update::FAILED;
837         }
838
839         if (!DBA::e("UPDATE `post-thread-user` INNER JOIN `post-thread` ON `post-thread-user`.`uri-id` = `post-thread`.`uri-id`
840                 SET `post-thread-user`.`owner-id` = `post-thread`.`owner-id`, `post-thread-user`.`author-id` = `post-thread`.`author-id`,
841                 `post-thread-user`.`causer-id` = `post-thread`.`causer-id`, `post-thread-user`.`network` = `post-thread`.`network`,
842                 `post-thread-user`.`created` = `post-thread`.`created`, `post-thread-user`.`received` = `post-thread`.`received`,
843                 `post-thread-user`.`changed` = `post-thread`.`changed`, `post-thread-user`.`commented` = `post-thread`.`commented`")) {
844                 return Update::FAILED;
845         }
846
847         return Update::SUCCESS;
848 }
849
850 function pre_update_1403()
851 {
852         // Necessary before a primary key change
853         if (DBStructure::existsTable('parsed_url') && !DBA::e("DROP TABLE `parsed_url`")) {
854                 return Update::FAILED;
855         }
856
857         return Update::SUCCESS;
858 }
859
860 function update_1404()
861 {
862         $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], ['command' => ['notifier', 'delivery', 'apdelivery', 'done' => false]]);
863         while ($task = DBA::fetch($tasks)) {
864                 $parameters = json_decode($task['parameter'], true);
865
866                 if (is_array($parameters) && count($parameters) && in_array($parameters[0], [Delivery::MAIL, Delivery::SUGGESTION, Delivery::REMOVAL, Delivery::RELOCATION])) {
867                         continue;
868                 }
869
870                 switch (strtolower($task['command'])) {
871                         case 'notifier':
872                                 if (count($parameters) == 3) {
873                                         continue 2;
874                                 }
875                                 $item = DBA::selectFirst('item', ['uid', 'uri-id'], ['id' => $parameters[1]]);
876                                 if (!DBA::isResult($item)) {
877                                         continue 2;
878                                 }
879
880                                 $parameters[1] = $item['uri-id'];
881                                 $parameters[2] = $item['uid'];
882                                 break;
883                         case 'delivery':
884                                 if (count($parameters) == 4) {
885                                         continue 2;
886                                 }
887                                 $item = DBA::selectFirst('item', ['uid', 'uri-id'], ['id' => $parameters[1]]);
888                                 if (!DBA::isResult($item)) {
889                                         continue 2;
890                                 }
891
892                                 $parameters[1] = $item['uri-id'];
893                                 $parameters[3] = $item['uid'];
894                                 break;
895                         case 'apdelivery':
896                                 if (count($parameters) == 6) {
897                                         continue 2;
898                                 }
899
900                                 if (empty($parameters[4])) {
901                                         $parameters[4] = [];
902                                 }
903
904                                 $item = DBA::selectFirst('item', ['uri-id'], ['id' => $parameters[1]]);
905                                 if (!DBA::isResult($item)) {
906                                         continue 2;
907                                 }
908
909                                 $parameters[5] = $item['uri-id'];
910                                 break;
911                         default:
912                                 continue 2;
913                 }
914                 DBA::update('workerqueue', ['parameter' => json_encode($parameters)], ['id' => $task['id']]);
915
916                 return Update::SUCCESS;
917         }
918 }
919
920 function update_1407()
921 {
922         if (!DBA::e("UPDATE `post` SET `causer-id` = NULL WHERE `causer-id` = 0")) {
923                 return Update::FAILED;
924         }
925         if (!DBA::e("UPDATE `post-user` SET `causer-id` = NULL WHERE `causer-id` = 0")) {
926                 return Update::FAILED;
927         }
928         if (!DBA::e("UPDATE `post-thread` SET `causer-id` = NULL WHERE `causer-id` = 0")) {
929                 return Update::FAILED;
930         }
931         if (!DBA::e("UPDATE `post-thread-user` SET `causer-id` = NULL WHERE `causer-id` = 0")) {
932                 return Update::FAILED;
933         }
934
935         return Update::SUCCESS;
936 }
937
938 function update_1413()
939 {
940         if (!DBA::e("UPDATE `post-user` SET `post-reason` = `post-type` WHERE `post-type` >= 64 and `post-type` <= 75")) {
941                 return Update::FAILED;
942         }
943 }
944
945 function update_1419()
946 {
947         $mails = DBA::select('mail', ['id', 'from-url', 'uri', 'parent-uri', 'guid'], [], ['order' => ['id']]);
948         while ($mail = DBA::fetch($mails)) {
949                 $fields = [];
950                 $fields['author-id'] = Contact::getIdForURL($mail['from-url'], 0, false);
951                 if (empty($fields['author-id'])) {
952                         continue;
953                 }
954
955                 $fields['uri-id']        = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
956                 $fields['parent-uri-id'] = ItemURI::getIdByURI($mail['parent-uri']);
957
958                 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'guid'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
959                 if (!empty($reply)) {
960                         $fields['thr-parent'] = $reply['uri'];
961                         if (!empty($reply['uri-id'])) {
962                                 $fields['thr-parent-id'] = $reply['uri-id'];
963                         } else {
964                                 $fields['thr-parent-id'] = ItemURI::insert(['uri' => $reply['uri'], 'guid' => $reply['guid']]);
965                         }
966                 }
967
968                 DBA::update('mail', $fields, ['id' => $mail['id']]);
969         }
970         return Update::SUCCESS;
971 }
972
973 function update_1429()
974 {
975         if (!DBA::e("UPDATE `contact` SET `uri-id` = null WHERE NOT `uri-id` IS NULL")) {
976                 return Update::FAILED;
977         }
978
979         if (DBStructure::existsTable('fcontact') && !DBA::e("UPDATE `fcontact` SET `uri-id` = null WHERE NOT `uri-id` IS NULL")) {
980                 return Update::FAILED;
981         }
982
983         if (!DBA::e("UPDATE `apcontact` SET `uri-id` = null WHERE NOT `uri-id` IS NULL")) {
984                 return Update::FAILED;
985         }
986
987         DI::keyValue()->set('post_update_version', 1423);
988
989         return Update::SUCCESS;
990 }
991
992 function update_1434()
993 {
994         $name = DI::config()->get('storage', 'name');
995
996         // In case of an empty config, set "Database" as default storage backend
997         if (empty($name)) {
998                 DI::config()->set('storage', 'name', DatabaseStorage::getName());
999         }
1000
1001         // In case of a Using deprecated storage class value, set the right name for it
1002         if (stristr($name, 'Friendica\Model\Storage\\')) {
1003                 DI::config()->set('storage', 'name', substr($name, 24));
1004         }
1005
1006         return Update::SUCCESS;
1007 }
1008
1009 function update_1438()
1010 {
1011         DBA::update('photo', ['photo-type' => Photo::USER_AVATAR], ['profile' => true]);
1012         DBA::update('photo', ['photo-type' => Photo::CONTACT_AVATAR], ["NOT `profile` AND NOT `contact-id` IS NULL AND `contact-id` != ?", 0]);
1013         DBA::update('photo', ['photo-type' => Photo::DEFAULT], ["NOT `profile` AND (`contact-id` IS NULL OR `contact-id` = ?) AND `photo-type` IS NULL AND `album` != ?", 0, Photo::CONTACT_PHOTOS]);
1014 }
1015
1016 function update_1439()
1017 {
1018         if (!DBStructure::existsTable('fcontact')) {
1019                 return Update::SUCCESS;
1020         }
1021
1022         $intros = DBA::select('intro', ['id', 'fid'], ["NOT `fid` IS NULL AND `fid` != ?", 0]);
1023         while ($intro = DBA::fetch($intros)) {
1024                 $fcontact = DBA::selectFirst('fcontact', ['url'], ['id' => $intro['fid']]);
1025                 if (!empty($fcontact['url'])) {
1026                         $id = Contact::getIdForURL($fcontact['url']);
1027                         if (!empty($id)) {
1028                                 DBA::update('intro',['suggest-cid' => $id], ['id' => $intro['id']]);
1029                         }
1030                 }
1031         }
1032         DBA::close($intros);
1033
1034         return Update::SUCCESS;
1035 }
1036
1037 function update_1440()
1038 {
1039         // Fix wrong public permissionset
1040         DBA::p("UPDATE `profile_field` SET `psid` = ? WHERE psid IN (SELECT `id` FROM `permissionset` WHERE `id` != ? AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '')", PermissionSet::PUBLIC, PermissionSet::PUBLIC);
1041         DBA::delete('permissionset', ["`id` != ? AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''", PermissionSet::PUBLIC]);
1042
1043         return Update::SUCCESS;
1044 }
1045
1046 function update_1441()
1047 {
1048         $languages = DI::l10n()->getAvailableLanguages();
1049
1050         $albums = [Photo::PROFILE_PHOTOS];
1051         foreach ($languages as $language) {
1052                 $albums[] = DI::l10n()->withLang($language)->t(Photo::PROFILE_PHOTOS);
1053         }
1054         $albums = array_unique($albums);
1055
1056         Photo::update(['photo-type' => Photo::USER_AVATAR], ['album' => $albums]);
1057
1058         return Update::SUCCESS;
1059 }
1060
1061 function update_1442()
1062 {
1063         // transform blocked intros into ignored intros
1064         DBA::update('intro', ['ignore' => 1, 'blocked' => 0], ['blocked' => 1]);
1065
1066         return Update::SUCCESS;
1067 }
1068
1069 /**
1070  * A bug in Contact\User::updateByContactUpdate prevented any update to the user-contact table since the rows have been
1071  * created in version 1435. This version fixes this bug but the user-contact rows are outdated, we need to regenerate
1072  * them.
1073  */
1074 function update_1444()
1075 {
1076         DBA::e('TRUNCATE TABLE `user-contact`');
1077
1078         $contacts = DBA::select('contact', [], ["`uid` != ?", 0]);
1079         while ($contact = DBA::fetch($contacts)) {
1080                 Contact\User::insertForContactArray($contact);
1081         }
1082
1083         return Update::SUCCESS;
1084 }
1085
1086 function update_1446()
1087 {
1088         $distributed_cache_driver_source = DI::config()->getCache()->getSource('system', 'distributed_cache_driver');
1089         $cache_driver_source = DI::config()->getCache()->getSource('system', 'cache_driver');
1090
1091         // In case the distributed cache driver is the default value, but the current cache driver isn't default,
1092         // we assume that the distributed cache driver should be the same as the current cache driver
1093         if ($distributed_cache_driver_source === Cache::SOURCE_STATIC && $cache_driver_source > Cache::SOURCE_STATIC) {
1094                 DI::config()->set('system', 'distributed_cache_driver', DI::config()->get('system', 'cache_driver'));
1095         }
1096
1097         return Update::SUCCESS;
1098 }
1099
1100 function update_1451()
1101 {
1102         DBA::update('user', ['account-type' => User::ACCOUNT_TYPE_COMMUNITY], ['page-flags' => [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP]]);
1103         DBA::update('contact', ['contact-type' => Contact::TYPE_COMMUNITY], ["`forum` OR `prv`"]);
1104         DBA::update('contact', ['manually-approve' => true], ['prv' => true]);
1105
1106         return Update::SUCCESS;
1107 }
1108
1109 function update_1457()
1110 {
1111         $pinned = DBA::select('post-thread-user', ['uri-id', 'author-id'], ['pinned' => true]);
1112         while ($post = DBA::fetch($pinned)) {
1113                 Post\Collection::add($post['uri-id'], Post\Collection::FEATURED, $post['author-id']);
1114         }
1115         DBA::close($pinned);
1116
1117         return Update::SUCCESS;
1118 }
1119
1120 function update_1480()
1121 {
1122         DBA::update('contact', ['next-update' => DBA::NULL_DATETIME], ['network' => Protocol::FEDERATED]);
1123         DBA::update('post', ['deleted' => false], ["`uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE NOT `deleted`)"]);
1124         return Update::SUCCESS;
1125 }
1126
1127 function update_1481()
1128 {
1129         DBA::e("UPDATE `post-collection` INNER JOIN `post` ON `post`.`uri-id` = `post-collection`.`uri-id` SET `post-collection`.`author-id` = `post`.`author-id` WHERE `post-collection`.`author-id` IS null");
1130         return Update::SUCCESS;
1131 }
1132
1133 function update_1491()
1134 {
1135         DBA::update('contact', ['remote_self' => Contact::MIRROR_OWN_POST], ['remote_self' => Contact::MIRROR_FORWARDED]);
1136         return Update::SUCCESS;
1137 }
1138
1139 function update_1497()
1140 {
1141         DBA::e("UPDATE `user` SET `last-activity` = DATE(`login_date`) WHERE `last-activity` IS NULL");
1142         return Update::SUCCESS;
1143 }
1144
1145 function update_1502()
1146 {
1147         DBA::e("UPDATE `pconfig` SET `cat` = 'calendar' WHERE `k` = 'first_day_of_week'");
1148         return Update::SUCCESS;
1149 }
1150
1151 function update_1505()
1152 {
1153         if (!DBStructure::existsTable('config')) {
1154                 return Update::SUCCESS;
1155         }
1156
1157         $conditions = [
1158                 "((`cat`  = ?) AND ((`k` LIKE ?) OR (`k` = ?) OR (`k` LIKE ?) OR (`k` = ?))) OR " .
1159                 "((`cat` != ?) AND  (`k` LIKE ?)) OR " .
1160                 "((`cat`  = ?) AND  (`k` LIKE ?))",
1161                 "system",
1162                 "post_update_%",
1163                 "worker_last_cleaned",
1164                 "last%",
1165                 "worker_daemon_mode",
1166                 "system",
1167                 "last_%",
1168                 "database",
1169                 "update_%",
1170         ];
1171
1172         $postUpdateEntries = DBA::selectToArray('config', ['cat', 'k', 'v'], $conditions);
1173
1174         foreach ($postUpdateEntries as $postUpdateEntry) {
1175                 if ($postUpdateEntry['cat'] === 'system') {
1176                         DI::keyValue()->set($postUpdateEntry['k'], $postUpdateEntry['v']);
1177                 } else {
1178                         DI::keyValue()->set(sprintf('%s_%s', $postUpdateEntry['cat'], $postUpdateEntry['k']), $postUpdateEntry['v']);
1179                 }
1180         }
1181
1182         return DBA::delete('config', $conditions) ? Update::SUCCESS : Update::FAILED;
1183 }
1184
1185 function update_1508()
1186 {
1187         $config = DBA::selectToArray('config');
1188
1189         $newConfig = DI::config()->beginTransaction();
1190
1191         foreach ($config as $entry) {
1192                 $newConfig->set($entry['cat'], $entry['k'], $entry['v']);
1193         }
1194
1195         $newConfig->commit();
1196
1197         return Update::SUCCESS;
1198 }
1199
1200 function update_1509()
1201 {
1202         $addons = DBA::selectToArray('addon');
1203
1204         $newConfig = DI::config()->beginTransaction();
1205
1206         foreach ($addons as $addon) {
1207                 $newConfig->set('addons', $addon['name'], [
1208                         'last_update' => $addon['timestamp'],
1209                         'admin' => (bool)$addon['plugin_admin'],
1210                 ]);
1211         }
1212
1213         $newConfig->commit();
1214
1215         return Update::SUCCESS;
1216 }
1217
1218 function update_1510()
1219 {
1220         $blocks = DBA::select('pconfig', ['uid', 'v'], ['cat' => 'blockem', 'k' => 'words']);
1221         while ($block = DBA::fetch($blocks)) {
1222                 foreach (explode(',', $block['v']) as $account) {
1223                         $id = Contact::getIdForURL(trim($account), 0, false);
1224                         if (empty($id)) {
1225                                 continue;
1226                         }
1227                         Contact\User::setCollapsed($id, $block['uid'], true);
1228                 }
1229         }
1230         return Update::SUCCESS;
1231 }
1232
1233 function update_1512()
1234 {
1235         DI::keyValue()->set('nodeinfo_total_users', DI::config()->get('nodeinfo', 'total_users'));
1236         DI::keyValue()->set('nodeinfo_active_users_halfyear', DI::config()->get('nodeinfo', 'active_users_halfyear'));
1237         DI::keyValue()->set('nodeinfo_active_users_monthly', DI::config()->get('nodeinfo', 'active_users_monthly'));
1238         DI::keyValue()->set('nodeinfo_active_users_weekly', DI::config()->get('nodeinfo', 'active_users_weekly'));
1239         DI::keyValue()->set('nodeinfo_local_posts', DI::config()->get('nodeinfo', 'local_posts'));
1240         DI::keyValue()->set('nodeinfo_local_comments', DI::config()->get('nodeinfo', 'local_comments'));
1241
1242         DI::config()->delete('nodeinfo', 'total_users');
1243         DI::config()->delete('nodeinfo', 'active_users_halfyear');
1244         DI::config()->delete('nodeinfo', 'active_users_monthly');
1245         DI::config()->delete('nodeinfo', 'active_users_weekly');
1246         DI::config()->delete('nodeinfo', 'local_posts');
1247         DI::config()->delete('nodeinfo', 'local_comments');
1248 }
1249
1250 function update_1513()
1251 {
1252         DI::keyValue()->set('git_friendica_version', DI::config()->get('system', 'git_friendica_version'));
1253         DI::keyValue()->set('twitter_application_name', DI::config()->get('twitter', 'application_name'));
1254
1255         DI::config()->delete('system', 'git_friendica_version');
1256         DI::config()->delete('twitter', 'application_name');
1257 }
1258
1259 function update_1514()
1260 {
1261         if (file_exists(dirname(__FILE__) . '/config/node.config.php')) {
1262
1263                 $transactionalConfig = DI::config()->beginTransaction();
1264                 $oldConfig = include dirname(__FILE__) . '/config/node.config.php';
1265
1266                 if (is_array($oldConfig)) {
1267                         $categories = array_keys($oldConfig);
1268
1269                         foreach ($categories as $category) {
1270                                 if (is_array($oldConfig[$category])) {
1271                                         $keys = array_keys($oldConfig[$category]);
1272
1273                                         foreach ($keys as $key) {
1274                                                 $transactionalConfig->set($category, $key, $oldConfig[$category][$key]);
1275                                         }
1276                                 }
1277                         }
1278                 }
1279
1280                 $transactionalConfig->commit();
1281
1282                 // Rename the node.config.php so it won't get used, but it isn't deleted.
1283                 if (rename(dirname(__FILE__) . '/config/node.config.php', dirname(__FILE__) . '/config/node.config.php.bak')) {
1284                         return Update::SUCCESS;
1285                 } else {
1286                         return Update::FAILED;
1287                 }
1288         }
1289
1290         return Update::SUCCESS;
1291 }
1292
1293 function update_1515()
1294 {
1295         DBA::update('verb', ['name' => Activity::READ], ['name' => 'https://www.w3.org/ns/activitystreams#read']);
1296         DBA::update('verb', ['name' => Activity::VIEW], ['name' => 'https://joinpeertube.org/view']);
1297         return Update::SUCCESS;
1298 }
1299
1300 function update_1516()
1301 {
1302         // Fixes https://github.com/friendica/friendica/issues/12803
1303         // de-serialize multiple serialized values
1304         $configTrans = DI::config()->beginTransaction();
1305         $configArray = DI::config()->getCache()->getDataBySource(Cache::SOURCE_DATA);
1306
1307         foreach ($configArray as $category => $keyValues) {
1308                 if (is_array($keyValues)) {
1309                         foreach ($keyValues as $key => $value) {
1310                                 $configTrans->set($category, $key, $value);
1311                         }
1312                 }
1313         }
1314
1315         $configTrans->commit();
1316
1317         return Update::SUCCESS;
1318 }
1319
1320 function update_1518()
1321 {
1322         $users = DBA::select('user', ['uid']);
1323         while ($user = DBA::fetch($users)) {
1324                 Contact::updateSelfFromUserID($user['uid']);
1325         }
1326         DBA::close($users);
1327
1328         return Update::SUCCESS;
1329 }
1330
1331 function update_1520(): int
1332 {
1333         DBA::update('user', ['parent-uid' => null], ['parent-uid' => 0]);
1334
1335         return Update::SUCCESS;
1336 }
1337
1338 /**
1339  * user-contact.remote_self was wrongly declared as boolean, possibly truncating integer values from contact.remote_self
1340  *
1341  * @return int
1342  * @throws Exception
1343  */
1344 function update_1524(): int
1345 {
1346         $contacts = DBA::select('contact', ['uid', 'uri-id', 'remote_self'], ["`uid` != ?", 0]);
1347         while ($contact = DBA::fetch($contacts)) {
1348                 Contact\User::insertForContactArray($contact);
1349         }
1350
1351         return Update::SUCCESS;
1352 }
1353
1354 function update_1525(): int
1355 {
1356         // Use expected value for user.username
1357         if (!DBA::e('UPDATE `user` u
1358     JOIN `profile` p
1359     ON p.`uid` = u.`uid`
1360     SET u.`username` = p.`name`
1361     WHERE p.`name` != ""')) {
1362                 return Update::FAILED;
1363         }
1364
1365         // Blank out deprecated field profile.name to avoid future confusion
1366         if (!DBA::e('UPDATE `profile` p
1367     SET p.`name` = ""')) {
1368                 return Update::FAILED;
1369         }
1370
1371         // Update users' self-contact name if needed
1372         if (!DBA::e('UPDATE `contact` c
1373     JOIN `user` u
1374     ON u.`uid` = c.`uid` AND c.`self` = 1
1375     SET c.`name` = u.`username`')) {
1376                 return Update::FAILED;
1377         }
1378
1379         return Update::SUCCESS;
1380 }
1381
1382 function update_1531()
1383 {
1384         $threads = Post::selectThread(Item::DELIVER_FIELDLIST, ["`uid` = ? AND `created` > ?", 0, DateTimeFormat::utc('now - ' . DI::config()->get('channel', 'engagement_hours') . ' hour')]);
1385         while ($post = Post::fetch($threads)) {
1386                 $post['gravity'] = Item::GRAVITY_COMMENT;
1387                 Post\Engagement::storeFromItem($post);
1388         }
1389         DBA::close($threads);
1390
1391         return Update::SUCCESS;
1392 }
1393
1394 function update_1535()
1395 {
1396         if (DI::config()->get('system', 'compute_group_counts')) {
1397                 DI::config()->set('system', 'compute_circle_counts', true);
1398         }
1399         DI::config()->delete('system', 'compute_group_counts');
1400         
1401         return Update::SUCCESS;
1402 }
1403
1404 function update_1539()
1405 {
1406         $users = DBA::select('user', ['uid'], ['account-type' => User::ACCOUNT_TYPE_COMMUNITY]);
1407         while ($user = DBA::fetch($users)) {
1408                 User::setCommunityUserSettings($user['uid']);
1409         }
1410         DBA::close($users);
1411
1412         return Update::SUCCESS;
1413 }
1414
1415 function pre_update_1550()
1416 {
1417         if (DBStructure::existsTable('post-engagement') && DBStructure::existsColumn('post-engagement', ['language'])) {
1418                 DBA::e("ALTER TABLE `post-engagement` DROP `language`");
1419         }
1420         if (DBStructure::existsTable('post-searchindex') && DBStructure::existsColumn('post-searchindex', ['network'])) {
1421                 DBA::e("ALTER TABLE `post-searchindex` DROP `network`, DROP `private`");
1422         }
1423         return Update::SUCCESS;
1424 }
1425
1426 function update_1552()
1427 {
1428         DBA::e("UPDATE `post-content` INNER JOIN `post-tag` ON `post-tag`.`uri-id` = `post-content`.`uri-id` INNER JOIN `tag` ON `tag`.`id` = `post-tag`.`tid` SET `sensitive` = ? WHERE `name` = ?", true, 'nsfw');
1429
1430         return Update::SUCCESS;
1431 }