]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
Merge pull request #8677 from MrPetovan/bug/8672-frio-contact-double-wrapping
[friendica.git] / src / Database / PostUpdate.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Item;
29 use Friendica\Model\ItemURI;
30 use Friendica\Model\PermissionSet;
31 use Friendica\Model\Post\Category;
32 use Friendica\Model\Tag;
33 use Friendica\Model\UserItem;
34 use Friendica\Model\Verb;
35 use Friendica\Util\Strings;
36
37 /**
38  * These database-intensive post update routines are meant to be executed in the background by the cronjob.
39  *
40  * If there is a need for a intensive migration after a database structure change, update this file
41  * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
42  */
43 class PostUpdate
44 {
45         // Needed for the helper function to read from the legacy term table
46         const OBJECT_TYPE_POST  = 1;
47
48         /**
49          * Calls the post update functions
50          */
51         public static function update()
52         {
53                 if (!self::update1194()) {
54                         return false;
55                 }
56                 if (!self::update1206()) {
57                         return false;
58                 }
59                 if (!self::update1279()) {
60                         return false;
61                 }
62                 if (!self::update1281()) {
63                         return false;
64                 }
65                 if (!self::update1297()) {
66                         return false;
67                 }
68                 if (!self::update1322()) {
69                         return false;
70                 }
71                 if (!self::update1329()) {
72                         return false;
73                 }
74                 if (!self::update1341()) {
75                         return false;
76                 }
77                 if (!self::update1342()) {
78                         return false;
79                 }
80                 if (!self::update1345()) {
81                         return false;
82                 }
83                 if (!self::update1346()) {
84                         return false;
85                 }
86                 if (!self::update1347()) {
87                         return false;
88                 }
89
90                 return true;
91         }
92
93         /**
94          * Updates the "global" field in the item table
95          *
96          * @return bool "true" when the job is done
97          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
98          */
99         private static function update1194()
100         {
101                 // Was the script completed?
102                 if (DI::config()->get("system", "post_update_version") >= 1194) {
103                         return true;
104                 }
105
106                 Logger::log("Start", Logger::DEBUG);
107
108                 $end_id = DI::config()->get("system", "post_update_1194_end");
109                 if (!$end_id) {
110                         $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
111                         if ($r) {
112                                 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
113                                 $end_id = DI::config()->get("system", "post_update_1194_end");
114                         }
115                 }
116
117                 Logger::log("End ID: ".$end_id, Logger::DEBUG);
118
119                 $start_id = DI::config()->get("system", "post_update_1194_start");
120
121                 $query1 = "SELECT `item`.`id` FROM `item` ";
122
123                 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
124
125                 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
126                                 AND `item`.`visible` AND NOT `item`.`private`
127                                 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
128                                 AND `item`.`network` IN ('%s', '%s', '%s', '')
129                                 AND NOT `item`.`global`";
130
131                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1",
132                         intval($start_id), intval($end_id),
133                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
134                 if (!$r) {
135                         DI::config()->set("system", "post_update_version", 1194);
136                         Logger::log("Update is done", Logger::DEBUG);
137                         return true;
138                 } else {
139                         DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
140                         $start_id = DI::config()->get("system", "post_update_1194_start");
141                 }
142
143                 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
144
145                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1000,1",
146                         intval($start_id), intval($end_id),
147                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
148                 if ($r) {
149                         $pos_id = $r[0]["id"];
150                 } else {
151                         $pos_id = $end_id;
152                 }
153                 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
154
155                 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
156                         intval($start_id), intval($pos_id),
157                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
158
159                 Logger::log("Done", Logger::DEBUG);
160         }
161
162         /**
163          * update the "last-item" field in the "self" contact
164          *
165          * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
166          *
167          * @return bool "true" when the job is done
168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169          */
170         private static function update1206()
171         {
172                 // Was the script completed?
173                 if (DI::config()->get("system", "post_update_version") >= 1206) {
174                         return true;
175                 }
176
177                 Logger::log("Start", Logger::DEBUG);
178                 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
179                         (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
180                         FROM `user`
181                         INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
182
183                 if (!DBA::isResult($r)) {
184                         return false;
185                 }
186                 foreach ($r as $user) {
187                         if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
188                                 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
189                         }
190                 }
191
192                 DI::config()->set("system", "post_update_version", 1206);
193                 Logger::log("Done", Logger::DEBUG);
194                 return true;
195         }
196
197         /**
198          * update the item related tables
199          *
200          * @return bool "true" when the job is done
201          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
202          * @throws \ImagickException
203          */
204         private static function update1279()
205         {
206                 // Was the script completed?
207                 if (DI::config()->get("system", "post_update_version") >= 1279) {
208                         return true;
209                 }
210
211                 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
212
213                 Logger::log("Start from item " . $id, Logger::DEBUG);
214
215                 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
216                         'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
217                         'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
218                         'inform', 'postopts', 'icid']);
219
220                 $start_id = $id;
221                 $rows = 0;
222                 $condition = ["`id` > ?", $id];
223                 $params = ['order' => ['id'], 'limit' => 10000];
224                 $items = Item::select($fields, $condition, $params);
225
226                 if (DBA::errorNo() != 0) {
227                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
228                         return false;
229                 }
230
231                 while ($item = Item::fetch($items)) {
232                         $id = $item['id'];
233
234                         if (empty($item['author-id'])) {
235                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
236                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
237
238                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
239                         }
240
241                         if (empty($item['owner-id'])) {
242                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
243                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
244
245                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
246                         }
247
248                         if (empty($item['psid'])) {
249                                 $item['psid'] = PermissionSet::getIdFromACL(
250                                         $item['uid'],
251                                         $item['allow_cid'],
252                                         $item['allow_gid'],
253                                         $item['deny_cid'],
254                                         $item['deny_gid']
255                                 );
256                         }
257
258                         $item['allow_cid'] = null;
259                         $item['allow_gid'] = null;
260                         $item['deny_cid'] = null;
261                         $item['deny_gid'] = null;
262
263                         if ($item['post-type'] == 0) {
264                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
265                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
266                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
267                                         $item['post-type'] = Item::PT_IMAGE;
268                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
269                                         $item['post-type'] = Item::PT_PAGE;
270                                 }
271                         }
272
273                         self::createLanguage($item);
274
275                         if (!empty($item['icid']) && !empty($item['language'])) {
276                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
277                         }
278                         unset($item['language']);
279
280                         Item::update($item, ['id' => $id]);
281
282                         ++$rows;
283                 }
284                 DBA::close($items);
285
286                 DI::config()->set("system", "post_update_version_1279_id", $id);
287
288                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
289
290                 if ($start_id == $id) {
291                         // Set all deprecated fields to "null" if they contain an empty string
292                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
293                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
294                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
295                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
296                                 'rendered-hash', 'rendered-html'];
297                         foreach ($nullfields as $field) {
298                                 $fields = [$field => null];
299                                 $condition = [$field => ''];
300                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
301                                 // Important: This has to be a "DBA::update", not a "Item::update"
302                                 DBA::update('item', $fields, $condition);
303                         }
304
305                         DI::config()->set("system", "post_update_version", 1279);
306                         Logger::log("Done", Logger::DEBUG);
307                         return true;
308                 }
309
310                 return false;
311         }
312
313         private static function createLanguage(&$item)
314         {
315                 if (empty($item['postopts'])) {
316                         return;
317                 }
318
319                 $opts = explode(',', $item['postopts']);
320
321                 $postopts = [];
322
323                 foreach ($opts as $opt) {
324                         if (strstr($opt, 'lang=')) {
325                                 $language = substr($opt, 5);
326                         } else {
327                                 $postopts[] = $opt;
328                         }
329                 }
330
331                 if (empty($language)) {
332                         return;
333                 }
334
335                 if (!empty($postopts)) {
336                         $item['postopts'] = implode(',', $postopts);
337                 } else {
338                         $item['postopts'] = null;
339                 }
340
341                 $lang_pairs = explode(':', $language);
342
343                 $lang_arr = [];
344
345                 foreach ($lang_pairs as $pair) {
346                         $lang_pair_arr = explode(';', $pair);
347                         if (count($lang_pair_arr) == 2) {
348                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
349                         }
350                 }
351
352                 $item['language'] = json_encode($lang_arr);
353         }
354
355         /**
356          * update item-uri data. Prerequisite for the next item structure update.
357          *
358          * @return bool "true" when the job is done
359          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360          */
361         private static function update1281()
362         {
363                 // Was the script completed?
364                 if (DI::config()->get("system", "post_update_version") >= 1281) {
365                         return true;
366                 }
367
368                 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
369
370                 Logger::log("Start from item " . $id, Logger::DEBUG);
371
372                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
373
374                 $start_id = $id;
375                 $rows = 0;
376                 $condition = ["`id` > ?", $id];
377                 $params = ['order' => ['id'], 'limit' => 10000];
378                 $items = DBA::select('item', $fields, $condition, $params);
379
380                 if (DBA::errorNo() != 0) {
381                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
382                         return false;
383                 }
384
385                 while ($item = DBA::fetch($items)) {
386                         $id = $item['id'];
387
388                         if (empty($item['uri'])) {
389                                 // Should not happen
390                                 continue;
391                         } elseif (empty($item['uri-id'])) {
392                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
393                         }
394
395                         if (empty($item['parent-uri'])) {
396                                 $item['parent-uri-id'] = $item['uri-id'];
397                         } elseif (empty($item['parent-uri-id'])) {
398                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
399                         }
400
401                         // Very old items don't have this field
402                         if (empty($item['thr-parent'])) {
403                                 $item['thr-parent-id'] = $item['parent-uri-id'];
404                         } elseif (empty($item['thr-parent-id'])) {
405                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
406                         }
407
408                         unset($item['id']);
409                         unset($item['guid']);
410                         unset($item['uri']);
411                         unset($item['parent-uri']);
412                         unset($item['thr-parent']);
413
414                         DBA::update('item', $item, ['id' => $id]);
415
416                         ++$rows;
417                 }
418                 DBA::close($items);
419
420                 DI::config()->set("system", "post_update_version_1281_id", $id);
421
422                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
423
424                 if ($start_id == $id) {
425                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
426                         DBA::e("UPDATE `item-activity` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-activity`.`uri` SET `item-activity`.`uri-id` = `item-uri`.`id` WHERE `item-activity`.`uri-id` IS NULL");
427
428                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
429                         DBA::e("UPDATE `item-content` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-content`.`uri` SET `item-content`.`uri-id` = `item-uri`.`id` WHERE `item-content`.`uri-id` IS NULL");
430
431                         DI::config()->set("system", "post_update_version", 1281);
432                         Logger::log("Done", Logger::DEBUG);
433                         return true;
434                 }
435
436                 return false;
437         }
438
439         /**
440          * Set the delivery queue count to a negative value for all items preceding the feature.
441          *
442          * @return bool "true" when the job is done
443          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
444          */
445         private static function update1297()
446         {
447                 // Was the script completed?
448                 if (DI::config()->get('system', 'post_update_version') >= 1297) {
449                         return true;
450                 }
451
452                 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
453                 $max_iid = $max_item_delivery_data['iid'];
454
455                 Logger::info('Start update1297 with max iid: ' . $max_iid);
456
457                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
458
459                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
460
461                 if (DBA::errorNo() != 0) {
462                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
463                         return false;
464                 }
465
466                 Logger::info('Processed rows: ' . DBA::affectedRows());
467
468                 DI::config()->set('system', 'post_update_version', 1297);
469
470                 Logger::info('Done');
471
472                 return true;
473         }
474         /**
475          * Remove contact duplicates
476          *
477          * @return bool "true" when the job is done
478          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
479          */
480         private static function update1322()
481         {
482                 // Was the script completed?
483                 if (DI::config()->get('system', 'post_update_version') >= 1322) {
484                         return true;
485                 }
486
487                 Logger::info('Start');
488
489                 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
490                         WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
491                                 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
492                         AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
493                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
494                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
495
496                 while ($contact = DBA::fetch($contacts)) {
497                         Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
498                         Contact::removeDuplicates($contact['nurl'], $contact['uid']);
499                 }
500
501                 DBA::close($contact);
502                 DI::config()->set('system', 'post_update_version', 1322);
503
504                 Logger::info('Done');
505
506                 return true;
507         }
508
509         /**
510          * update user-item data with notifications
511          *
512          * @return bool "true" when the job is done
513          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
514          */
515         private static function update1329()
516         {
517                 // Was the script completed?
518                 if (DI::config()->get('system', 'post_update_version') >= 1329) {
519                         return true;
520                 }
521
522                 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
523
524                 Logger::info('Start', ['item' => $id]);
525
526                 $start_id = $id;
527                 $rows = 0;
528                 $condition = ["`id` > ?", $id];
529                 $params = ['order' => ['id'], 'limit' => 10000];
530                 $items = DBA::select('item', ['id'], $condition, $params);
531
532                 if (DBA::errorNo() != 0) {
533                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
534                         return false;
535                 }
536
537                 while ($item = DBA::fetch($items)) {
538                         $id = $item['id'];
539
540                         UserItem::setNotification($item['id']);
541
542                         ++$rows;
543                 }
544                 DBA::close($items);
545
546                 DI::config()->set('system', 'post_update_version_1329_id', $id);
547
548                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
549
550                 if ($start_id == $id) {
551                         DI::config()->set('system', 'post_update_version', 1329);
552                         Logger::info('Done');
553                         return true;
554                 }
555
556                 return false;
557         }
558
559         /**
560          * Fill the "tag" table with tags and mentions from the body
561          *
562          * @return bool "true" when the job is done
563          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
564          */
565         private static function update1341()
566         {
567                 // Was the script completed?
568                 if (DI::config()->get('system', 'post_update_version') >= 1341) {
569                         return true;
570                 }
571
572                 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
573
574                 Logger::info('Start', ['item' => $id]);
575
576                 $rows = 0;
577
578                 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
579                         (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
580                         ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
581
582                 if (DBA::errorNo() != 0) {
583                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
584                         return false;
585                 }
586
587                 while ($item = DBA::fetch($items)) {
588                         Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
589                         $id = $item['uri-id'];
590                         ++$rows;
591                         if ($rows % 1000 == 0) {
592                                 DI::config()->set('system', 'post_update_version_1341_id', $id);
593                         }
594                 }
595                 DBA::close($items);
596
597                 DI::config()->set('system', 'post_update_version_1341_id', $id);
598
599                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
600
601                 // When there are less than 1,000 items processed this means that we reached the end
602                 // The other entries will then be processed with the regular functionality
603                 if ($rows < 1000) {
604                         DI::config()->set('system', 'post_update_version', 1341);
605                         Logger::info('Done');
606                         return true;
607                 }
608
609                 return false;
610         }
611
612         /**
613          * Fill the "tag" table with tags and mentions from the "term" table
614          *
615          * @return bool "true" when the job is done
616          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
617          */
618         private static function update1342()
619         {
620                 // Was the script completed?
621                 if (DI::config()->get('system', 'post_update_version') >= 1342) {
622                         return true;
623                 }
624
625                 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
626
627                 Logger::info('Start', ['item' => $id]);
628
629                 $rows = 0;
630
631                 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
632                         FROM `term`
633                         INNER JOIN `item` ON `item`.`id` = `term`.`oid`
634                         INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
635                         WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
636                         Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
637
638                 if (DBA::errorNo() != 0) {
639                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
640                         return false;
641                 }
642
643                 while ($term = DBA::fetch($terms)) {
644                         if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
645                 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
646                 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
647                 if (!DBA::isResult($contact)) {
648                         $ssl_url = str_replace('http://', 'https://', $term['url']);
649                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
650                         $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
651                 }
652
653                 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
654                         $term['type'] = Tag::IMPLICIT_MENTION;
655                 }
656                         }
657
658                         Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
659
660                         $id = $term['tid'];
661                         ++$rows;
662                         if ($rows % 1000 == 0) {
663                                 DI::config()->set('system', 'post_update_version_1342_id', $id);
664                         }
665                 }
666                 DBA::close($terms);
667
668                 DI::config()->set('system', 'post_update_version_1342_id', $id);
669
670                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
671
672                 // When there are less than 1,000 items processed this means that we reached the end
673                 // The other entries will then be processed with the regular functionality
674                 if ($rows < 1000) {
675                         DI::config()->set('system', 'post_update_version', 1342);
676                         Logger::info('Done');
677                         return true;
678                 }
679
680                 return false;
681         }
682
683         /**
684          * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
685          *
686          * @return bool "true" when the job is done
687          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
688          */
689         private static function update1345()
690         {
691                 // Was the script completed?
692                 if (DI::config()->get('system', 'post_update_version') >= 1345) {
693                         return true;
694                 }
695
696                 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
697
698                 Logger::info('Start', ['item' => $id]);
699
700                 $rows = 0;
701
702                 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
703                         `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
704                         FROM `item-delivery-data`
705                         INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
706                         WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
707
708                 if (DBA::errorNo() != 0) {
709                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
710                         return false;
711                 }
712
713                 while ($delivery = DBA::fetch($deliveries)) {
714                         $id = $delivery['iid'];
715                         unset($delivery['iid']);
716                         DBA::insert('post-delivery-data', $delivery, true);
717                         ++$rows;
718                 }
719                 DBA::close($deliveries);
720
721                 DI::config()->set('system', 'post_update_version_1345_id', $id);
722
723                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
724
725                 // When there are less than 100 items processed this means that we reached the end
726                 // The other entries will then be processed with the regular functionality
727                 if ($rows < 100) {
728                         DI::config()->set('system', 'post_update_version', 1345);
729                         Logger::info('Done');
730                         return true;
731                 }
732
733                 return false;
734         }
735
736         /**
737          * Generates the legacy item.file field string from an item ID.
738          * Includes only file and category terms.
739          *
740          * @param int $item_id
741          * @return string
742          * @throws \Exception
743          */
744         private static function fileTextFromItemId($item_id)
745         {
746                 $file_text = '';
747
748                 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
749                 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
750                 foreach ($tags as $tag) {
751                         if ($tag['type'] == Category::CATEGORY) {
752                                 $file_text .= '<' . $tag['term'] . '>';
753                         } else {
754                                 $file_text .= '[' . $tag['term'] . ']';
755                         }
756                 }
757
758                 return $file_text;
759         }
760
761         /**
762          * Fill the "tag" table with tags and mentions from the "term" table
763          *
764          * @return bool "true" when the job is done
765          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766          */
767         private static function update1346()
768         {
769                 // Was the script completed?
770                 if (DI::config()->get('system', 'post_update_version') >= 1346) {
771                         return true;
772                 }
773
774                 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
775
776                 Logger::info('Start', ['item' => $id]);
777
778                 $rows = 0;
779
780                 $terms = DBA::select('term', ['oid'],
781                         ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
782                         ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
783
784                 if (DBA::errorNo() != 0) {
785                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
786                         return false;
787                 }
788
789                 while ($term = DBA::fetch($terms)) {
790                         $item = Item::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
791                         if (!DBA::isResult($item)) {
792                                 continue;
793                         }
794
795                         $file = self::fileTextFromItemId($term['oid']);
796                         if (!empty($file)) {
797                                 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
798                         }
799
800                         $id = $term['oid'];
801                         ++$rows;
802                         if ($rows % 100 == 0) {
803                                 DI::config()->set('system', 'post_update_version_1346_id', $id);
804                         }
805                 }
806                 DBA::close($terms);
807
808                 DI::config()->set('system', 'post_update_version_1346_id', $id);
809
810                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
811
812                 // When there are less than 10 items processed this means that we reached the end
813                 // The other entries will then be processed with the regular functionality
814                 if ($rows < 10) {
815                         DI::config()->set('system', 'post_update_version', 1346);
816                         Logger::info('Done');
817                         return true;
818                 }
819
820                 return false;
821         }
822
823         /**
824          * update the "vid" (verb) field in the item table 
825          *
826          * @return bool "true" when the job is done
827          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828          * @throws \ImagickException
829          */
830         private static function update1347()
831         {
832                 // Was the script completed?
833                 if (DI::config()->get("system", "post_update_version") >= 1347) {
834                         return true;
835                 }
836
837                 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
838
839                 Logger::info('Start', ['item' => $id]);
840
841                 $start_id = $id;
842                 $rows = 0;
843                 $condition = ["`id` > ? AND `vid` IS NULL", $id];
844                 $params = ['order' => ['id'], 'limit' => 10000];
845                 $items = Item::select(['id', 'verb'], $condition, $params);
846
847                 if (DBA::errorNo() != 0) {
848                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
849                         return false;
850                 }
851
852                 while ($item = Item::fetch($items)) {
853                         $id = $item['id'];
854
855                         DBA::update('item', ['vid' => Verb::getID($item['verb'])], ['id' => $item['id']]);
856
857                         ++$rows;
858                 }
859                 DBA::close($items);
860
861                 DI::config()->set("system", "post_update_version_1347_id", $id);
862
863                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
864
865                 if ($start_id == $id) {
866                         DI::config()->set("system", "post_update_version", 1347);
867                         Logger::info('Done');
868                         return true;
869                 }
870
871                 return false;
872         }
873 }