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