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