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