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