]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
d54c3f2217c726f2c099cc0006dbfb1a593a5a8c
[friendica.git] / src / Database / PostUpdate.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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  */
21
22 namespace Friendica\Database;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Conversation;
29 use Friendica\Model\GServer;
30 use Friendica\Model\Item;
31 use Friendica\Model\ItemURI;
32 use Friendica\Model\Photo;
33 use Friendica\Model\Post;
34 use Friendica\Model\Post\Category;
35 use Friendica\Model\Tag;
36 use Friendica\Model\Verb;
37 use Friendica\Protocol\ActivityPub\Processor;
38 use Friendica\Protocol\ActivityPub\Receiver;
39 use Friendica\Util\JsonLD;
40 use Friendica\Util\Strings;
41
42 /**
43  * These database-intensive post update routines are meant to be executed in the background by the cronjob.
44  *
45  * If there is a need for a intensive migration after a database structure change, update this file
46  * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
47  */
48 class PostUpdate
49 {
50         // Needed for the helper function to read from the legacy term table
51         const OBJECT_TYPE_POST  = 1;
52
53         const VERSION = 1484;
54
55         /**
56          * Calls the post update functions
57          */
58         public static function update()
59         {
60                 if (!self::update1297()) {
61                         return false;
62                 }
63                 if (!self::update1322()) {
64                         return false;
65                 }
66                 if (!self::update1329()) {
67                         return false;
68                 }
69                 if (!self::update1341()) {
70                         return false;
71                 }
72                 if (!self::update1342()) {
73                         return false;
74                 }
75                 if (!self::update1345()) {
76                         return false;
77                 }
78                 if (!self::update1346()) {
79                         return false;
80                 }
81                 if (!self::update1347()) {
82                         return false;
83                 }
84                 if (!self::update1348()) {
85                         return false;
86                 }
87                 if (!self::update1349()) {
88                         return false;
89                 }
90                 if (!self::update1383()) {
91                         return false;
92                 }
93                 if (!self::update1384()) {
94                         return false;
95                 }
96                 if (!self::update1400()) {
97                         return false;
98                 }
99                 if (!self::update1424()) {
100                         return false;
101                 }
102                 if (!self::update1425()) {
103                         return false;
104                 }
105                 if (!self::update1426()) {
106                         return false;
107                 }
108                 if (!self::update1427()) {
109                         return false;
110                 }
111                 if (!self::update1452()) {
112                         return false;
113                 }
114                 if (!self::update1483()) {
115                         return false;
116                 }
117                 if (!self::update1484()) {
118                         return false;
119                 }
120                 return true;
121         }
122
123         /**
124          * Set the delivery queue count to a negative value for all items preceding the feature.
125          *
126          * @return bool "true" when the job is done
127          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128          */
129         private static function update1297()
130         {
131                 // Was the script completed?
132                 if (DI::keyValue()->get('post_update_version') >= 1297) {
133                         return true;
134                 }
135
136                 if (!DBStructure::existsTable('item-delivery-data')) {
137                         DI::keyValue()->set('post_update_version', 1297);
138                         return true;
139                 }
140
141                 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
142                 $max_iid = $max_item_delivery_data['iid'] ?? 0;
143
144                 Logger::info('Start update1297 with max iid: ' . $max_iid);
145
146                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
147
148                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
149
150                 if (DBA::errorNo() != 0) {
151                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
152                         return false;
153                 }
154
155                 Logger::info('Processed rows: ' . DBA::affectedRows());
156
157                 DI::keyValue()->set('post_update_version', 1297);
158
159                 Logger::info('Done');
160
161                 return true;
162         }
163         /**
164          * Remove contact duplicates
165          *
166          * @return bool "true" when the job is done
167          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168          */
169         private static function update1322()
170         {
171                 // Was the script completed?
172                 if (DI::keyValue()->get('post_update_version') >= 1322) {
173                         return true;
174                 }
175
176                 Logger::info('Start');
177
178                 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
179                         WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
180                                 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
181                         AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
182                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
183                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
184
185                 while ($contact = DBA::fetch($contacts)) {
186                         Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
187                         Contact::removeDuplicates($contact['nurl'], $contact['uid']);
188                 }
189
190                 DBA::close($contact);
191                 DI::keyValue()->set('post_update_version', 1322);
192
193                 Logger::info('Done');
194
195                 return true;
196         }
197
198         /**
199          * update user notification data
200          *
201          * @return bool "true" when the job is done
202          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
203          */
204         private static function update1329()
205         {
206                 // Was the script completed?
207                 if (DI::keyValue()->get('post_update_version') >= 1329) {
208                         return true;
209                 }
210
211                 if (!DBStructure::existsTable('item')) {
212                         DI::keyValue()->set('post_update_version', 1329);
213                         return true;
214                 }
215
216                 $id = DI::keyValue()->get('post_update_version_1329_id') ?? 0;
217
218                 Logger::info('Start', ['item' => $id]);
219
220                 $start_id = $id;
221                 $rows = 0;
222                 $condition = ["`id` > ?", $id];
223                 $params = ['order' => ['id'], 'limit' => 10000];
224                 $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params);
225
226                 if (DBA::errorNo() != 0) {
227                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
228                         return false;
229                 }
230
231                 while ($item = DBA::fetch($items)) {
232                         $id = $item['id'];
233
234                         Post\UserNotification::setNotification($item['uri-id'], $item['uid']);
235
236                         ++$rows;
237                 }
238                 DBA::close($items);
239
240                 DI::keyValue()->set('post_update_version_1329_id', $id);
241
242                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
243
244                 if ($start_id == $id) {
245                         DI::keyValue()->set('post_update_version', 1329);
246                         Logger::info('Done');
247                         return true;
248                 }
249
250                 return false;
251         }
252
253         /**
254          * Fill the "tag" table with tags and mentions from the body
255          *
256          * @return bool "true" when the job is done
257          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258          */
259         private static function update1341()
260         {
261                 // Was the script completed?
262                 if (DI::keyValue()->get('post_update_version') >= 1341) {
263                         return true;
264                 }
265
266                 if (!DBStructure::existsTable('item-content')) {
267                         DI::keyValue()->set('post_update_version', 1342);
268                         return true;
269                 }
270
271                 $id = DI::keyValue()->get('post_update_version_1341_id') ?? 0;
272
273                 Logger::info('Start', ['item' => $id]);
274
275                 $rows = 0;
276
277                 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
278                         (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
279                         ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
280
281                 if (DBA::errorNo() != 0) {
282                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
283                         return false;
284                 }
285
286                 while ($item = DBA::fetch($items)) {
287                         Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
288                         $id = $item['uri-id'];
289                         ++$rows;
290                         if ($rows % 1000 == 0) {
291                                 DI::keyValue()->set('post_update_version_1341_id', $id);
292                         }
293                 }
294                 DBA::close($items);
295
296                 DI::keyValue()->set('post_update_version_1341_id', $id);
297
298                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
299
300                 // When there are less than 1,000 items processed this means that we reached the end
301                 // The other entries will then be processed with the regular functionality
302                 if ($rows < 1000) {
303                         DI::keyValue()->set('post_update_version', 1341);
304                         Logger::info('Done');
305                         return true;
306                 }
307
308                 return false;
309         }
310
311         /**
312          * Fill the "tag" table with tags and mentions from the "term" table
313          *
314          * @return bool "true" when the job is done
315          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
316          */
317         private static function update1342()
318         {
319                 // Was the script completed?
320                 if (DI::keyValue()->get('post_update_version') >= 1342) {
321                         return true;
322                 }
323
324                 if (!DBStructure::existsTable('term') || !DBStructure::existsTable('item-content')) {
325                         DI::keyValue()->set('post_update_version', 1342);
326                         return true;
327                 }
328
329                 $id = DI::keyValue()->get('post_update_version_1342_id') ?? 0;
330
331                 Logger::info('Start', ['item' => $id]);
332
333                 $rows = 0;
334
335                 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
336                         FROM `term`
337                         INNER JOIN `item` ON `item`.`id` = `term`.`oid`
338                         INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
339                         WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
340                         Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
341
342                 if (DBA::errorNo() != 0) {
343                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
344                         return false;
345                 }
346
347                 while ($term = DBA::fetch($terms)) {
348                         if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
349                 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
350                 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
351                 if (!DBA::isResult($contact)) {
352                         $ssl_url = str_replace('http://', 'https://', $term['url']);
353                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
354                         $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
355                 }
356
357                 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
358                         $term['type'] = Tag::IMPLICIT_MENTION;
359                 }
360                         }
361
362                         Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url']);
363
364                         $id = $term['tid'];
365                         ++$rows;
366                         if ($rows % 1000 == 0) {
367                                 DI::keyValue()->set('post_update_version_1342_id', $id);
368                         }
369                 }
370                 DBA::close($terms);
371
372                 DI::keyValue()->set('post_update_version_1342_id', $id);
373
374                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
375
376                 // When there are less than 1,000 items processed this means that we reached the end
377                 // The other entries will then be processed with the regular functionality
378                 if ($rows < 1000) {
379                         DI::keyValue()->set('post_update_version', 1342);
380                         Logger::info('Done');
381                         return true;
382                 }
383
384                 return false;
385         }
386
387         /**
388          * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
389          *
390          * @return bool "true" when the job is done
391          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
392          */
393         private static function update1345()
394         {
395                 // Was the script completed?
396                 if (DI::keyValue()->get('post_update_version') >= 1345) {
397                         return true;
398                 }
399
400                 if (!DBStructure::existsTable('item-delivery-data')) {
401                         DI::keyValue()->set('post_update_version', 1345);
402                         return true;
403                 }
404
405                 $id = DI::keyValue()->get('post_update_version_1345_id') ?? 0;
406
407                 Logger::info('Start', ['item' => $id]);
408
409                 $rows = 0;
410
411                 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
412                         `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
413                         FROM `item-delivery-data`
414                         INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
415                         WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
416
417                 if (DBA::errorNo() != 0) {
418                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
419                         return false;
420                 }
421
422                 while ($delivery = DBA::fetch($deliveries)) {
423                         $id = $delivery['iid'];
424                         unset($delivery['iid']);
425                         DBA::insert('post-delivery-data', $delivery, Database::INSERT_UPDATE);
426                         ++$rows;
427                 }
428                 DBA::close($deliveries);
429
430                 DI::keyValue()->set('post_update_version_1345_id', $id);
431
432                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
433
434                 // When there are less than 100 items processed this means that we reached the end
435                 // The other entries will then be processed with the regular functionality
436                 if ($rows < 100) {
437                         DI::keyValue()->set('post_update_version', 1345);
438                         Logger::info('Done');
439                         return true;
440                 }
441
442                 return false;
443         }
444
445         /**
446          * Generates the legacy item.file field string from an item ID.
447          * Includes only file and category terms.
448          *
449          * @param int $item_id
450          * @return string
451          * @throws \Exception
452          */
453         private static function fileTextFromItemId($item_id)
454         {
455                 $file_text = '';
456
457                 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
458                 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
459                 foreach ($tags as $tag) {
460                         if ($tag['type'] == Category::CATEGORY) {
461                                 $file_text .= '<' . $tag['term'] . '>';
462                         } else {
463                                 $file_text .= '[' . $tag['term'] . ']';
464                         }
465                 }
466
467                 return $file_text;
468         }
469
470         /**
471          * Fill the "tag" table with tags and mentions from the "term" table
472          *
473          * @return bool "true" when the job is done
474          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475          */
476         private static function update1346()
477         {
478                 // Was the script completed?
479                 if (DI::keyValue()->get('post_update_version') >= 1346) {
480                         return true;
481                 }
482
483                 if (!DBStructure::existsTable('term')) {
484                         DI::keyValue()->set('post_update_version', 1346);
485                         return true;
486                 }
487
488                 $id = DI::keyValue()->get('post_update_version_1346_id') ?? 0;
489
490                 Logger::info('Start', ['item' => $id]);
491
492                 $rows = 0;
493
494                 $terms = DBA::select('term', ['oid'],
495                         ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
496                         ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
497
498                 if (DBA::errorNo() != 0) {
499                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
500                         return false;
501                 }
502
503                 while ($term = DBA::fetch($terms)) {
504                         $item = Post::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
505                         if (!DBA::isResult($item)) {
506                                 continue;
507                         }
508
509                         $file = self::fileTextFromItemId($term['oid']);
510                         if (!empty($file)) {
511                                 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
512                         }
513
514                         $id = $term['oid'];
515                         ++$rows;
516                         if ($rows % 100 == 0) {
517                                 DI::keyValue()->set('post_update_version_1346_id', $id);
518                         }
519                 }
520                 DBA::close($terms);
521
522                 DI::keyValue()->set('post_update_version_1346_id', $id);
523
524                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
525
526                 // When there are less than 10 items processed this means that we reached the end
527                 // The other entries will then be processed with the regular functionality
528                 if ($rows < 10) {
529                         DI::keyValue()->set('post_update_version', 1346);
530                         Logger::info('Done');
531                         return true;
532                 }
533
534                 return false;
535         }
536
537         /**
538          * update the "vid" (verb) field in the item table
539          *
540          * @return bool "true" when the job is done
541          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
542          * @throws \ImagickException
543          */
544         private static function update1347()
545         {
546                 // Was the script completed?
547                 if (DI::keyValue()->get('post_update_version') >= 1347) {
548                         return true;
549                 }
550
551                 if (!DBStructure::existsTable('item-activity') || !DBStructure::existsTable('item')) {
552                         DI::keyValue()->set('post_update_version', 1347);
553                         return true;
554                 }
555
556                 $id = DI::keyValue()->get('post_update_version_1347_id') ?? 0;
557
558                 Logger::info('Start', ['item' => $id]);
559
560                 $start_id = $id;
561                 $rows = 0;
562
563                 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
564                         FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
565                         LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
566                         WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", Item::GRAVITY_ACTIVITY, $id);
567
568                 if (DBA::errorNo() != 0) {
569                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
570                         return false;
571                 }
572
573                 while ($item = DBA::fetch($items)) {
574                         $id = $item['id'];
575                         $verb = $item['item-verb'];
576                         if (empty($verb)) {
577                                 $verb = $item['verb'];
578                         }
579                         if (empty($verb) && is_int($item['activity'])) {
580                                 $verb = Item::ACTIVITIES[$item['activity']];
581                         }
582                         if (empty($verb)) {
583                                 continue;
584                         }
585
586                         DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
587                         ++$rows;
588                 }
589                 DBA::close($items);
590
591                 DI::keyValue()->set('post_update_version_1347_id', $id);
592
593                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
594
595                 if ($start_id == $id) {
596                         DI::keyValue()->set('post_update_version', 1347);
597                         Logger::info('Done');
598                         return true;
599                 }
600
601                 return false;
602         }
603
604         /**
605          * update the "gsid" (global server id) field in the contact table
606          *
607          * @return bool "true" when the job is done
608          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
609          * @throws \ImagickException
610          */
611         private static function update1348()
612         {
613                 // Was the script completed?
614                 if (DI::keyValue()->get('post_update_version') >= 1348) {
615                         return true;
616                 }
617
618                 $id = DI::keyValue()->get('post_update_version_1348_id') ?? 0;
619
620                 Logger::info('Start', ['contact' => $id]);
621
622                 $start_id = $id;
623                 $rows = 0;
624                 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
625                 $params = ['order' => ['id'], 'limit' => 10000];
626                 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
627
628                 if (DBA::errorNo() != 0) {
629                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
630                         return false;
631                 }
632
633                 while ($contact = DBA::fetch($contacts)) {
634                         $id = $contact['id'];
635
636                         DBA::update('contact',
637                                 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
638                                 ['id' => $contact['id']]);
639
640                         ++$rows;
641                 }
642                 DBA::close($contacts);
643
644                 DI::keyValue()->set('post_update_version_1348_id', $id);
645
646                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
647
648                 if ($start_id == $id) {
649                         DI::keyValue()->set('post_update_version', 1348);
650                         Logger::info('Done');
651                         return true;
652                 }
653
654                 return false;
655         }
656
657         /**
658          * update the "gsid" (global server id) field in the apcontact table
659          *
660          * @return bool "true" when the job is done
661          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662          * @throws \ImagickException
663          */
664         private static function update1349()
665         {
666                 // Was the script completed?
667                 if (DI::keyValue()->get('post_update_version') >= 1349) {
668                         return true;
669                 }
670
671                 $id = DI::keyValue()->get('post_update_version_1349_id') ?? '';
672
673                 Logger::info('Start', ['apcontact' => $id]);
674
675                 $start_id = $id;
676                 $rows = 0;
677                 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
678                 $params = ['order' => ['url'], 'limit' => 10000];
679                 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
680
681                 if (DBA::errorNo() != 0) {
682                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
683                         return false;
684                 }
685
686                 while ($apcontact = DBA::fetch($apcontacts)) {
687                         $id = $apcontact['url'];
688
689                         DBA::update('apcontact',
690                                 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
691                                 ['url' => $apcontact['url']]);
692
693                         ++$rows;
694                 }
695                 DBA::close($apcontacts);
696
697                 DI::keyValue()->set('post_update_version_1349_id', $id);
698
699                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
700
701                 if ($start_id == $id) {
702                         DI::keyValue()->set('post_update_version', 1349);
703                         Logger::info('Done');
704                         return true;
705                 }
706
707                 return false;
708         }
709
710         /**
711          * Remove orphaned photo entries
712          *
713          * @return bool "true" when the job is done
714          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
715          * @throws \ImagickException
716          */
717         private static function update1383()
718         {
719                 // Was the script completed?
720                 if (DI::keyValue()->get('post_update_version') >= 1383) {
721                         return true;
722                 }
723
724                 Logger::info('Start');
725
726                 $deleted = 0;
727                 $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
728
729                 $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]);
730                 while ($photo = DBA::fetch($photos)) {
731                         $delete = !in_array($photo['scale'], [4, 5, 6]);
732
733                         if (!$delete) {
734                                 // Check if there is a contact entry with that photo
735                                 $delete = !DBA::exists('contact', ["`id` = ? AND `" . $avatar[$photo['scale']] . "` LIKE ?",
736                                         $photo['contact-id'], '%' . $photo['resource-id'] . '%']);
737                         }
738
739                         if ($delete) {
740                                 Photo::delete(['id' => $photo['id']]);
741                                 $deleted++;
742                         }
743                 }
744                 DBA::close($photos);
745
746                 DI::keyValue()->set('post_update_version', 1383);
747                 Logger::info('Done', ['deleted' => $deleted]);
748                 return true;
749         }
750
751         /**
752          * update the "hash" field in the photo table
753          *
754          * @return bool "true" when the job is done
755          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
756          * @throws \ImagickException
757          */
758         private static function update1384()
759         {
760                 // Was the script completed?
761                 if (DI::keyValue()->get('post_update_version') >= 1384) {
762                         return true;
763                 }
764
765                 $condition = ["`hash` IS NULL"];
766                 Logger::info('Start', ['rest' => DBA::count('photo', $condition)]);
767
768                 $rows = 0;
769                 $photos = DBA::select('photo', [], $condition, ['limit' => 100]);
770
771                 if (DBA::errorNo() != 0) {
772                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
773                         return false;
774                 }
775
776                 while ($photo = DBA::fetch($photos)) {
777                         $img = Photo::getImageForPhoto($photo);
778                         if (!empty($img)) {
779                                 $md5 = md5($img->asString());
780                         } else {
781                                 $md5 = '';
782                         }
783                         DBA::update('photo', ['hash' => $md5], ['id' => $photo['id']]);
784                         ++$rows;
785                 }
786                 DBA::close($photos);
787
788                 Logger::info('Processed', ['rows' => $rows]);
789
790                 if ($rows <= 100) {
791                         DI::keyValue()->set('post_update_version', 1384);
792                         Logger::info('Done');
793                         return true;
794                 }
795
796                 return false;
797         }
798
799         /**
800          * update the "external-id" field in the post table
801          *
802          * @return bool "true" when the job is done
803          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804          * @throws \ImagickException
805          */
806         private static function update1400()
807         {
808                 // Was the script completed?
809                 if (DI::keyValue()->get('post_update_version') >= 1400) {
810                         return true;
811                 }
812
813                 if (!DBStructure::existsTable('item')) {
814                         DI::keyValue()->set('post_update_version', 1400);
815                         return true;
816                 }
817
818                 $condition = ["`extid` != ? AND EXISTS(SELECT `id` FROM `post-user` WHERE `uri-id` = `item`.`uri-id` AND `uid` = `item`.`uid` AND `external-id` IS NULL)", ''];
819                 Logger::info('Start', ['rest' => DBA::count('item', $condition)]);
820
821                 $rows = 0;
822                 $items = DBA::select('item', ['uri-id', 'uid', 'extid'], $condition, ['order' => ['id'], 'limit' => 10000]);
823
824                 if (DBA::errorNo() != 0) {
825                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
826                         return false;
827                 }
828
829                 while ($item = DBA::fetch($items)) {
830                         Post::update(['external-id' => ItemURI::getIdByURI($item['extid'])], ['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
831                         ++$rows;
832                 }
833                 DBA::close($items);
834
835                 Logger::info('Processed', ['rows' => $rows]);
836
837                 if ($rows <= 100) {
838                         DI::keyValue()->set('post_update_version', 1400);
839                         Logger::info('Done');
840                         return true;
841                 }
842
843                 return false;
844         }
845
846         /**
847          * update the "uri-id" field in the contact table
848          *
849          * @return bool "true" when the job is done
850          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
851          * @throws \ImagickException
852          */
853         private static function update1424()
854         {
855                 // Was the script completed?
856                 if (DI::keyValue()->get('post_update_version') >= 1424) {
857                         return true;
858                 }
859
860                 $condition = ["`uri-id` IS NULL"];
861                 Logger::info('Start', ['rest' => DBA::count('contact', $condition)]);
862
863                 $rows = 0;
864                 $contacts = DBA::select('contact', ['id', 'url'], $condition, ['limit' => 1000]);
865
866                 if (DBA::errorNo() != 0) {
867                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
868                         return false;
869                 }
870
871                 while ($contact = DBA::fetch($contacts)) {
872                         DBA::update('contact', ['uri-id' => ItemURI::getIdByURI($contact['url'])], ['id' => $contact['id']]);
873                         ++$rows;
874                 }
875                 DBA::close($contacts);
876
877                 Logger::info('Processed', ['rows' => $rows]);
878
879                 if ($rows <= 100) {
880                         DI::keyValue()->set('post_update_version', 1424);
881                         Logger::info('Done');
882                         return true;
883                 }
884
885                 return false;
886         }
887
888         /**
889          * update the "uri-id" field in the fcontact table
890          *
891          * @return bool "true" when the job is done
892          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893          * @throws \ImagickException
894          */
895         private static function update1425()
896         {
897                 // Was the script completed?
898                 if (DI::keyValue()->get('post_update_version') >= 1425) {
899                         return true;
900                 }
901
902                 if (!DBStructure::existsTable('fcontact')) {
903                         DI::keyValue()->set('post_update_version', 1425);
904                         return true;
905                 }
906
907                 $condition = ["`uri-id` IS NULL"];
908                 Logger::info('Start', ['rest' => DBA::count('fcontact', $condition)]);
909
910                 $rows = 0;
911                 $fcontacts = DBA::select('fcontact', ['id', 'url', 'guid'], $condition, ['limit' => 1000]);
912
913                 if (DBA::errorNo() != 0) {
914                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
915                         return false;
916                 }
917
918                 while ($fcontact = DBA::fetch($fcontacts)) {
919                         if (!empty($fcontact['guid'])) {
920                                 $uriid = ItemURI::insert(['uri' => $fcontact['url'], 'guid' => $fcontact['guid']]);
921                         } else {
922                                 $uriid = ItemURI::getIdByURI($fcontact['url']);
923                         }
924                         DBA::update('fcontact', ['uri-id' => $uriid], ['id' => $fcontact['id']]);
925                         ++$rows;
926                 }
927                 DBA::close($fcontacts);
928
929                 Logger::info('Processed', ['rows' => $rows]);
930
931                 if ($rows <= 100) {
932                         DI::keyValue()->set('post_update_version', 1425);
933                         Logger::info('Done');
934                         return true;
935                 }
936
937                 return false;
938         }
939
940         /**
941          * update the "uri-id" field in the apcontact table
942          *
943          * @return bool "true" when the job is done
944          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
945          * @throws \ImagickException
946          */
947         private static function update1426()
948         {
949                 // Was the script completed?
950                 if (DI::keyValue()->get('post_update_version') >= 1426) {
951                         return true;
952                 }
953
954                 $condition = ["`uri-id` IS NULL"];
955                 Logger::info('Start', ['rest' => DBA::count('apcontact', $condition)]);
956
957                 $rows = 0;
958                 $apcontacts = DBA::select('apcontact', ['url', 'uuid'], $condition, ['limit' => 1000]);
959
960                 if (DBA::errorNo() != 0) {
961                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
962                         return false;
963                 }
964
965                 while ($apcontact = DBA::fetch($apcontacts)) {
966                         if (!empty($apcontact['uuid'])) {
967                                 $uriid = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
968                         } else {
969                                 $uriid = ItemURI::getIdByURI($apcontact['url']);
970                         }
971                         DBA::update('apcontact', ['uri-id' => $uriid], ['url' => $apcontact['url']]);
972                         ++$rows;
973                 }
974                 DBA::close($apcontacts);
975
976                 Logger::info('Processed', ['rows' => $rows]);
977
978                 if ($rows <= 100) {
979                         DI::keyValue()->set('post_update_version', 1426);
980                         Logger::info('Done');
981                         return true;
982                 }
983
984                 return false;
985         }
986
987         /**
988          * update the "uri-id" field in the event table
989          *
990          * @return bool "true" when the job is done
991          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992          * @throws \ImagickException
993          */
994         private static function update1427()
995         {
996                 // Was the script completed?
997                 if (DI::keyValue()->get('post_update_version') >= 1427) {
998                         return true;
999                 }
1000
1001                 $condition = ["`uri-id` IS NULL"];
1002                 Logger::info('Start', ['rest' => DBA::count('event', $condition)]);
1003
1004                 $rows = 0;
1005                 $events = DBA::select('event', ['id', 'uri', 'guid'], $condition, ['limit' => 1000]);
1006
1007                 if (DBA::errorNo() != 0) {
1008                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
1009                         return false;
1010                 }
1011
1012                 while ($event = DBA::fetch($events)) {
1013                         if (!empty($event['guid'])) {
1014                                 $uriid = ItemURI::insert(['uri' => $event['uri'], 'guid' => $event['guid']]);
1015                         } else {
1016                                 $uriid = ItemURI::getIdByURI($event['uri']);
1017                         }
1018                         DBA::update('event', ['uri-id' => $uriid], ['id' => $event['id']]);
1019                         ++$rows;
1020                 }
1021                 DBA::close($events);
1022
1023                 Logger::info('Processed', ['rows' => $rows]);
1024
1025                 if ($rows <= 100) {
1026                         DI::keyValue()->set('post_update_version', 1427);
1027                         Logger::info('Done');
1028                         return true;
1029                 }
1030
1031                 return false;
1032         }
1033
1034         /**
1035          * Fill the receivers of the post via the raw source
1036          *
1037          * @return bool "true" when the job is done
1038          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1039          * @throws \ImagickException
1040          */
1041         private static function update1452()
1042         {
1043                 // Was the script completed?
1044                 if (DI::keyValue()->get('post_update_version') >= 1452) {
1045                         return true;
1046                 }
1047
1048                 if (!DBStructure::existsTable('conversation')) {
1049                         DI::keyValue()->set('post_update_version', 1452);
1050                         return true;
1051                 }
1052
1053                 $id = DI::keyValue()->get('post_update_version_1452_id') ?? 0;
1054
1055                 Logger::info('Start', ['uri-id' => $id]);
1056
1057                 $rows     = 0;
1058                 $received = '';
1059
1060                 $conversations = DBA::p("SELECT `post-view`.`uri-id`, `conversation`.`source`, `conversation`.`received` FROM `conversation`
1061                         INNER JOIN `post-view` ON `post-view`.`uri` = `conversation`.`item-uri`
1062                         WHERE NOT `source` IS NULL AND `conversation`.`protocol` = ? AND `uri-id` > ? LIMIT ?",
1063                         Conversation::PARCEL_ACTIVITYPUB, $id, 1000);
1064
1065                 if (DBA::errorNo() != 0) {
1066                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
1067                         return false;
1068                 }
1069
1070                 while ($conversation = DBA::fetch($conversations)) {
1071                         $id       = $conversation['uri-id'];
1072                         $received = $conversation['received'];
1073
1074                         $raw = json_decode($conversation['source'], true);
1075                         if (empty($raw)) {
1076                                 continue;
1077                         }
1078                         $activity = JsonLD::compact($raw);
1079
1080                         $urls = Receiver::getReceiverURL($activity);
1081                         Processor::storeReceivers($conversation['uri-id'], $urls);
1082
1083                         if (!empty($activity['as:object'])) {
1084                                 $urls = array_merge($urls, Receiver::getReceiverURL($activity['as:object']));
1085                                 Processor::storeReceivers($conversation['uri-id'], $urls);
1086                         }
1087                         ++$rows;
1088                 }
1089
1090                 DBA::close($conversations);
1091
1092                 DI::keyValue()->set('post_update_version_1452_id', $id);
1093
1094                 Logger::info('Processed', ['rows' => $rows, 'last' => $id, 'last-received' => $received]);
1095
1096                 if ($rows <= 100) {
1097                         DI::keyValue()->set('post_update_version', 1452);
1098                         Logger::info('Done');
1099                         return true;
1100                 }
1101
1102                 return false;
1103         }
1104
1105         /**
1106          * Correct the parent.
1107          * This fixes a bug that was introduced in the development of version 2022.09
1108          *
1109          * @return bool "true" when the job is done
1110          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1111          * @throws \ImagickException
1112          */
1113         private static function update1483()
1114         {
1115                 // Was the script completed?
1116                 if (DI::keyValue()->get('post_update_version') >= 1483) {
1117                         return true;
1118                 }
1119
1120                 Logger::info('Start');
1121
1122                 $posts = DBA::select('post-view', ['uri-id'], ['conversation' => './']);
1123                 while ($post = DBA::fetch($posts)) {
1124                         $parent = Item::getParent($post['uri-id']);
1125                         if ($parent != 0) {
1126                                 DBA::update('post', ['parent-uri-id' => $parent], ['uri-id' => $post['uri-id']]);
1127                                 DBA::update('post-user', ['parent-uri-id' => $parent], ['uri-id' => $post['uri-id']]);
1128                         }
1129                 }
1130                 DBA::close($posts);
1131
1132                 DI::keyValue()->set('post_update_version', 1483);
1133                 Logger::info('Done');
1134                 return true;
1135         }
1136
1137         /**
1138          * Handle duplicate contact entries
1139          *
1140          * @return bool "true" when the job is done
1141          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142          * @throws \ImagickException
1143          */
1144         private static function update1484()
1145         {
1146                 // Was the script completed?
1147                 if (DI::keyValue()->get('post_update_version') >= 1484) {
1148                         return true;
1149                 }
1150
1151                 $id = DI::keyValue()->get('post_update_version_1484_id') ?? 0;
1152
1153                 Logger::info('Start', ['id' => $id]);
1154
1155                 $rows = 0;
1156
1157                 $contacts = DBA::select('contact', ['id', 'uid', 'uri-id', 'url'], ["`id` > ?", $id], ['order' => ['id'], 'limit' => 1000]);
1158
1159                 if (DBA::errorNo() != 0) {
1160                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
1161                         return false;
1162                 }
1163
1164                 while ($contact = DBA::fetch($contacts)) {
1165                         $id = $contact['id'];
1166                         if (is_null($contact['uri-id'])) {
1167                                 $contact['uri-id'] = ItemURI::getIdByURI($contact['url']);
1168                                 DBA::update('contact', ['uri-id' => $contact['uri-id']], ['id' => $contact['id']]);
1169                         }
1170                         Contact::setAccountUser($contact['id'], $contact['uid'], $contact['uri-id'], $contact['url']);
1171                         ++$rows;
1172                 }
1173                 DBA::close($contacts);
1174
1175                 DI::keyValue()->set('post_update_version_1484_id', $id);
1176
1177                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
1178
1179                 if ($rows <= 100) {
1180                         DI::keyValue()->set('post_update_version', 1484);
1181                         Logger::info('Done');
1182                         return true;
1183                 }
1184
1185                 return false;
1186         }
1187 }