]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
9b467c7101d027f11b5eec19c5ecc62f5305f771
[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                 if (!DBStructure::existsTable('term')) {
638                         DI::config()->set('system', 'post_update_version', 1342);
639                         return true;
640                 }
641
642                 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
643
644                 Logger::info('Start', ['item' => $id]);
645
646                 $rows = 0;
647
648                 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
649                         FROM `term`
650                         INNER JOIN `item` ON `item`.`id` = `term`.`oid`
651                         INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
652                         WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
653                         Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
654
655                 if (DBA::errorNo() != 0) {
656                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
657                         return false;
658                 }
659
660                 while ($term = DBA::fetch($terms)) {
661                         if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
662                 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
663                 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
664                 if (!DBA::isResult($contact)) {
665                         $ssl_url = str_replace('http://', 'https://', $term['url']);
666                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
667                         $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
668                 }
669
670                 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
671                         $term['type'] = Tag::IMPLICIT_MENTION;
672                 }
673                         }
674
675                         Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
676
677                         $id = $term['tid'];
678                         ++$rows;
679                         if ($rows % 1000 == 0) {
680                                 DI::config()->set('system', 'post_update_version_1342_id', $id);
681                         }
682                 }
683                 DBA::close($terms);
684
685                 DI::config()->set('system', 'post_update_version_1342_id', $id);
686
687                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
688
689                 // When there are less than 1,000 items processed this means that we reached the end
690                 // The other entries will then be processed with the regular functionality
691                 if ($rows < 1000) {
692                         DI::config()->set('system', 'post_update_version', 1342);
693                         Logger::info('Done');
694                         return true;
695                 }
696
697                 return false;
698         }
699
700         /**
701          * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
702          *
703          * @return bool "true" when the job is done
704          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705          */
706         private static function update1345()
707         {
708                 // Was the script completed?
709                 if (DI::config()->get('system', 'post_update_version') >= 1345) {
710                         return true;
711                 }
712
713                 if (!DBStructure::existsTable('item-delivery-data')) {
714                         DI::config()->set('system', 'post_update_version', 1345);
715                         return true;
716                 }
717
718                 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
719
720                 Logger::info('Start', ['item' => $id]);
721
722                 $rows = 0;
723
724                 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
725                         `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
726                         FROM `item-delivery-data`
727                         INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
728                         WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
729
730                 if (DBA::errorNo() != 0) {
731                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
732                         return false;
733                 }
734
735                 while ($delivery = DBA::fetch($deliveries)) {
736                         $id = $delivery['iid'];
737                         unset($delivery['iid']);
738                         DBA::insert('post-delivery-data', $delivery, true);
739                         ++$rows;
740                 }
741                 DBA::close($deliveries);
742
743                 DI::config()->set('system', 'post_update_version_1345_id', $id);
744
745                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
746
747                 // When there are less than 100 items processed this means that we reached the end
748                 // The other entries will then be processed with the regular functionality
749                 if ($rows < 100) {
750                         DI::config()->set('system', 'post_update_version', 1345);
751                         Logger::info('Done');
752                         return true;
753                 }
754
755                 return false;
756         }
757
758         /**
759          * Generates the legacy item.file field string from an item ID.
760          * Includes only file and category terms.
761          *
762          * @param int $item_id
763          * @return string
764          * @throws \Exception
765          */
766         private static function fileTextFromItemId($item_id)
767         {
768                 $file_text = '';
769
770                 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
771                 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
772                 foreach ($tags as $tag) {
773                         if ($tag['type'] == Category::CATEGORY) {
774                                 $file_text .= '<' . $tag['term'] . '>';
775                         } else {
776                                 $file_text .= '[' . $tag['term'] . ']';
777                         }
778                 }
779
780                 return $file_text;
781         }
782
783         /**
784          * Fill the "tag" table with tags and mentions from the "term" table
785          *
786          * @return bool "true" when the job is done
787          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
788          */
789         private static function update1346()
790         {
791                 // Was the script completed?
792                 if (DI::config()->get('system', 'post_update_version') >= 1346) {
793                         return true;
794                 }
795
796                 if (!DBStructure::existsTable('term')) {
797                         DI::config()->set('system', 'post_update_version', 1346);
798                         return true;
799                 }
800
801                 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
802
803                 Logger::info('Start', ['item' => $id]);
804
805                 $rows = 0;
806
807                 $terms = DBA::select('term', ['oid'],
808                         ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
809                         ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
810
811                 if (DBA::errorNo() != 0) {
812                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
813                         return false;
814                 }
815
816                 while ($term = DBA::fetch($terms)) {
817                         $item = Item::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
818                         if (!DBA::isResult($item)) {
819                                 continue;
820                         }
821
822                         $file = self::fileTextFromItemId($term['oid']);
823                         if (!empty($file)) {
824                                 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
825                         }
826
827                         $id = $term['oid'];
828                         ++$rows;
829                         if ($rows % 100 == 0) {
830                                 DI::config()->set('system', 'post_update_version_1346_id', $id);
831                         }
832                 }
833                 DBA::close($terms);
834
835                 DI::config()->set('system', 'post_update_version_1346_id', $id);
836
837                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
838
839                 // When there are less than 10 items processed this means that we reached the end
840                 // The other entries will then be processed with the regular functionality
841                 if ($rows < 10) {
842                         DI::config()->set('system', 'post_update_version', 1346);
843                         Logger::info('Done');
844                         return true;
845                 }
846
847                 return false;
848         }
849
850         /**
851          * update the "vid" (verb) field in the item table
852          *
853          * @return bool "true" when the job is done
854          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855          * @throws \ImagickException
856          */
857         private static function update1347()
858         {
859                 // Was the script completed?
860                 if (DI::config()->get("system", "post_update_version") >= 1347) {
861                         return true;
862                 }
863
864                 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
865
866                 Logger::info('Start', ['item' => $id]);
867
868                 $start_id = $id;
869                 $rows = 0;
870
871                 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
872                         FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
873                         LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
874                         WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", GRAVITY_ACTIVITY, $id);
875
876                 if (DBA::errorNo() != 0) {
877                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
878                         return false;
879                 }
880
881                 while ($item = DBA::fetch($items)) {
882                         $id = $item['id'];
883                         $verb = $item['item-verb'];
884                         if (empty($verb)) {
885                                 $verb = $item['verb'];
886                         }
887                         if (empty($verb) && is_int($item['activity'])) {
888                                 $verb = Item::ACTIVITIES[$item['activity']];
889                         }
890                         if (empty($verb)) {
891                                 continue;
892                         }
893
894                         DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
895                         ++$rows;
896                 }
897                 DBA::close($items);
898
899                 DI::config()->set("system", "post_update_version_1347_id", $id);
900
901                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
902
903                 if ($start_id == $id) {
904                         DI::config()->set("system", "post_update_version", 1347);
905                         Logger::info('Done');
906                         return true;
907                 }
908
909                 return false;
910         }
911
912         /**
913          * update the "gsid" (global server id) field in the contact table
914          *
915          * @return bool "true" when the job is done
916          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
917          * @throws \ImagickException
918          */
919         private static function update1348()
920         {
921                 // Was the script completed?
922                 if (DI::config()->get("system", "post_update_version") >= 1348) {
923                         return true;
924                 }
925
926                 $id = DI::config()->get("system", "post_update_version_1348_id", 0);
927
928                 Logger::info('Start', ['contact' => $id]);
929
930                 $start_id = $id;
931                 $rows = 0;
932                 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
933                 $params = ['order' => ['id'], 'limit' => 10000];
934                 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
935
936                 if (DBA::errorNo() != 0) {
937                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
938                         return false;
939                 }
940
941                 while ($contact = DBA::fetch($contacts)) {
942                         $id = $contact['id'];
943
944                         DBA::update('contact',
945                                 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
946                                 ['id' => $contact['id']]);
947
948                         ++$rows;
949                 }
950                 DBA::close($contacts);
951
952                 DI::config()->set("system", "post_update_version_1348_id", $id);
953
954                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
955
956                 if ($start_id == $id) {
957                         DI::config()->set("system", "post_update_version", 1348);
958                         Logger::info('Done');
959                         return true;
960                 }
961
962                 return false;
963         }
964
965         /**
966          * update the "gsid" (global server id) field in the apcontact table
967          *
968          * @return bool "true" when the job is done
969          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970          * @throws \ImagickException
971          */
972         private static function update1349()
973         {
974                 // Was the script completed?
975                 if (DI::config()->get("system", "post_update_version") >= 1349) {
976                         return true;
977                 }
978
979                 $id = DI::config()->get("system", "post_update_version_1349_id", '');
980
981                 Logger::info('Start', ['apcontact' => $id]);
982
983                 $start_id = $id;
984                 $rows = 0;
985                 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
986                 $params = ['order' => ['url'], 'limit' => 10000];
987                 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
988
989                 if (DBA::errorNo() != 0) {
990                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
991                         return false;
992                 }
993
994                 while ($apcontact = DBA::fetch($apcontacts)) {
995                         $id = $apcontact['url'];
996
997                         DBA::update('apcontact',
998                                 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
999                                 ['url' => $apcontact['url']]);
1000
1001                         ++$rows;
1002                 }
1003                 DBA::close($apcontacts);
1004
1005                 DI::config()->set("system", "post_update_version_1349_id", $id);
1006
1007                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
1008
1009                 if ($start_id == $id) {
1010                         DI::config()->set("system", "post_update_version", 1349);
1011                         Logger::info('Done');
1012                         return true;
1013                 }
1014
1015                 return false;
1016         }
1017 }