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