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