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