3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Database;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
27 use Friendica\Model\Contact;
28 use Friendica\Model\GServer;
29 use Friendica\Model\Item;
30 use Friendica\Model\ItemURI;
31 use Friendica\Model\Photo;
32 use Friendica\Model\Post;
33 use Friendica\Model\Post\Category;
34 use Friendica\Model\Tag;
35 use Friendica\Model\Verb;
36 use Friendica\Util\Strings;
39 * These database-intensive post update routines are meant to be executed in the background by the cronjob.
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.
46 // Needed for the helper function to read from the legacy term table
47 const OBJECT_TYPE_POST = 1;
51 * Calls the post update functions
53 public static function update()
55 if (!self::update1297()) {
58 if (!self::update1322()) {
61 if (!self::update1329()) {
64 if (!self::update1341()) {
67 if (!self::update1342()) {
70 if (!self::update1345()) {
73 if (!self::update1346()) {
76 if (!self::update1347()) {
79 if (!self::update1348()) {
82 if (!self::update1349()) {
85 if (!self::update1383()) {
88 if (!self::update1384()) {
91 if (!self::update1400()) {
98 * Set the delivery queue count to a negative value for all items preceding the feature.
100 * @return bool "true" when the job is done
101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
103 private static function update1297()
105 // Was the script completed?
106 if (DI::config()->get('system', 'post_update_version') >= 1297) {
110 if (!DBStructure::existsTable('item-delivery-data')) {
111 DI::config()->set('system', 'post_update_version', 1297);
115 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
116 $max_iid = $max_item_delivery_data['iid'];
118 Logger::info('Start update1297 with max iid: ' . $max_iid);
120 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
122 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
124 if (DBA::errorNo() != 0) {
125 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
129 Logger::info('Processed rows: ' . DBA::affectedRows());
131 DI::config()->set('system', 'post_update_version', 1297);
133 Logger::info('Done');
138 * Remove contact duplicates
140 * @return bool "true" when the job is done
141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
143 private static function update1322()
145 // Was the script completed?
146 if (DI::config()->get('system', 'post_update_version') >= 1322) {
150 Logger::info('Start');
152 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
153 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
154 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
155 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
156 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
157 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
159 while ($contact = DBA::fetch($contacts)) {
160 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
161 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
164 DBA::close($contact);
165 DI::config()->set('system', 'post_update_version', 1322);
167 Logger::info('Done');
173 * update user notification data
175 * @return bool "true" when the job is done
176 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
178 private static function update1329()
180 // Was the script completed?
181 if (DI::config()->get('system', 'post_update_version') >= 1329) {
185 if (!DBStructure::existsTable('item')) {
186 DI::config()->set('system', 'post_update_version', 1329);
190 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
192 Logger::info('Start', ['item' => $id]);
196 $condition = ["`id` > ?", $id];
197 $params = ['order' => ['id'], 'limit' => 10000];
198 $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params);
200 if (DBA::errorNo() != 0) {
201 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
205 while ($item = DBA::fetch($items)) {
208 Post\UserNotification::setNotification($item['uri-id'], $item['uid']);
214 DI::config()->set('system', 'post_update_version_1329_id', $id);
216 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
218 if ($start_id == $id) {
219 DI::config()->set('system', 'post_update_version', 1329);
220 Logger::info('Done');
228 * Fill the "tag" table with tags and mentions from the body
230 * @return bool "true" when the job is done
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 private static function update1341()
235 // Was the script completed?
236 if (DI::config()->get('system', 'post_update_version') >= 1341) {
240 if (!DBStructure::existsTable('item-content')) {
241 DI::config()->set('system', 'post_update_version', 1342);
245 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
247 Logger::info('Start', ['item' => $id]);
251 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
252 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
253 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
255 if (DBA::errorNo() != 0) {
256 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
260 while ($item = DBA::fetch($items)) {
261 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
262 $id = $item['uri-id'];
264 if ($rows % 1000 == 0) {
265 DI::config()->set('system', 'post_update_version_1341_id', $id);
270 DI::config()->set('system', 'post_update_version_1341_id', $id);
272 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
274 // When there are less than 1,000 items processed this means that we reached the end
275 // The other entries will then be processed with the regular functionality
277 DI::config()->set('system', 'post_update_version', 1341);
278 Logger::info('Done');
286 * Fill the "tag" table with tags and mentions from the "term" table
288 * @return bool "true" when the job is done
289 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 private static function update1342()
293 // Was the script completed?
294 if (DI::config()->get('system', 'post_update_version') >= 1342) {
298 if (!DBStructure::existsTable('term') || !DBStructure::existsTable('item-content')) {
299 DI::config()->set('system', 'post_update_version', 1342);
303 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
305 Logger::info('Start', ['item' => $id]);
309 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
311 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
312 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
313 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
314 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
316 if (DBA::errorNo() != 0) {
317 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
321 while ($term = DBA::fetch($terms)) {
322 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
323 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
324 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
325 if (!DBA::isResult($contact)) {
326 $ssl_url = str_replace('http://', 'https://', $term['url']);
327 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
328 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
331 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
332 $term['type'] = Tag::IMPLICIT_MENTION;
336 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
340 if ($rows % 1000 == 0) {
341 DI::config()->set('system', 'post_update_version_1342_id', $id);
346 DI::config()->set('system', 'post_update_version_1342_id', $id);
348 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
350 // When there are less than 1,000 items processed this means that we reached the end
351 // The other entries will then be processed with the regular functionality
353 DI::config()->set('system', 'post_update_version', 1342);
354 Logger::info('Done');
362 * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
364 * @return bool "true" when the job is done
365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
367 private static function update1345()
369 // Was the script completed?
370 if (DI::config()->get('system', 'post_update_version') >= 1345) {
374 if (!DBStructure::existsTable('item-delivery-data')) {
375 DI::config()->set('system', 'post_update_version', 1345);
379 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
381 Logger::info('Start', ['item' => $id]);
385 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
386 `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
387 FROM `item-delivery-data`
388 INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
389 WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
391 if (DBA::errorNo() != 0) {
392 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
396 while ($delivery = DBA::fetch($deliveries)) {
397 $id = $delivery['iid'];
398 unset($delivery['iid']);
399 DBA::insert('post-delivery-data', $delivery, Database::INSERT_UPDATE);
402 DBA::close($deliveries);
404 DI::config()->set('system', 'post_update_version_1345_id', $id);
406 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
408 // When there are less than 100 items processed this means that we reached the end
409 // The other entries will then be processed with the regular functionality
411 DI::config()->set('system', 'post_update_version', 1345);
412 Logger::info('Done');
420 * Generates the legacy item.file field string from an item ID.
421 * Includes only file and category terms.
423 * @param int $item_id
427 private static function fileTextFromItemId($item_id)
431 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
432 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
433 foreach ($tags as $tag) {
434 if ($tag['type'] == Category::CATEGORY) {
435 $file_text .= '<' . $tag['term'] . '>';
437 $file_text .= '[' . $tag['term'] . ']';
445 * Fill the "tag" table with tags and mentions from the "term" table
447 * @return bool "true" when the job is done
448 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
450 private static function update1346()
452 // Was the script completed?
453 if (DI::config()->get('system', 'post_update_version') >= 1346) {
457 if (!DBStructure::existsTable('term')) {
458 DI::config()->set('system', 'post_update_version', 1346);
462 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
464 Logger::info('Start', ['item' => $id]);
468 $terms = DBA::select('term', ['oid'],
469 ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
470 ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
472 if (DBA::errorNo() != 0) {
473 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
477 while ($term = DBA::fetch($terms)) {
478 $item = Post::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
479 if (!DBA::isResult($item)) {
483 $file = self::fileTextFromItemId($term['oid']);
485 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
490 if ($rows % 100 == 0) {
491 DI::config()->set('system', 'post_update_version_1346_id', $id);
496 DI::config()->set('system', 'post_update_version_1346_id', $id);
498 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
500 // When there are less than 10 items processed this means that we reached the end
501 // The other entries will then be processed with the regular functionality
503 DI::config()->set('system', 'post_update_version', 1346);
504 Logger::info('Done');
512 * update the "vid" (verb) field in the item table
514 * @return bool "true" when the job is done
515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
516 * @throws \ImagickException
518 private static function update1347()
520 // Was the script completed?
521 if (DI::config()->get("system", "post_update_version") >= 1347) {
525 if (!DBStructure::existsTable('item-activity') || !DBStructure::existsTable('item')) {
526 DI::config()->set('system', 'post_update_version', 1347);
530 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
532 Logger::info('Start', ['item' => $id]);
537 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
538 FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
539 LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
540 WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", GRAVITY_ACTIVITY, $id);
542 if (DBA::errorNo() != 0) {
543 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
547 while ($item = DBA::fetch($items)) {
549 $verb = $item['item-verb'];
551 $verb = $item['verb'];
553 if (empty($verb) && is_int($item['activity'])) {
554 $verb = Item::ACTIVITIES[$item['activity']];
560 DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
565 DI::config()->set("system", "post_update_version_1347_id", $id);
567 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
569 if ($start_id == $id) {
570 DI::config()->set("system", "post_update_version", 1347);
571 Logger::info('Done');
579 * update the "gsid" (global server id) field in the contact table
581 * @return bool "true" when the job is done
582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
583 * @throws \ImagickException
585 private static function update1348()
587 // Was the script completed?
588 if (DI::config()->get("system", "post_update_version") >= 1348) {
592 $id = DI::config()->get("system", "post_update_version_1348_id", 0);
594 Logger::info('Start', ['contact' => $id]);
598 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
599 $params = ['order' => ['id'], 'limit' => 10000];
600 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
602 if (DBA::errorNo() != 0) {
603 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
607 while ($contact = DBA::fetch($contacts)) {
608 $id = $contact['id'];
610 DBA::update('contact',
611 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
612 ['id' => $contact['id']]);
616 DBA::close($contacts);
618 DI::config()->set("system", "post_update_version_1348_id", $id);
620 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
622 if ($start_id == $id) {
623 DI::config()->set("system", "post_update_version", 1348);
624 Logger::info('Done');
632 * update the "gsid" (global server id) field in the apcontact table
634 * @return bool "true" when the job is done
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
636 * @throws \ImagickException
638 private static function update1349()
640 // Was the script completed?
641 if (DI::config()->get("system", "post_update_version") >= 1349) {
645 $id = DI::config()->get("system", "post_update_version_1349_id", '');
647 Logger::info('Start', ['apcontact' => $id]);
651 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
652 $params = ['order' => ['url'], 'limit' => 10000];
653 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
655 if (DBA::errorNo() != 0) {
656 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
660 while ($apcontact = DBA::fetch($apcontacts)) {
661 $id = $apcontact['url'];
663 DBA::update('apcontact',
664 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
665 ['url' => $apcontact['url']]);
669 DBA::close($apcontacts);
671 DI::config()->set("system", "post_update_version_1349_id", $id);
673 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
675 if ($start_id == $id) {
676 DI::config()->set("system", "post_update_version", 1349);
677 Logger::info('Done');
685 * Remove orphaned photo entries
687 * @return bool "true" when the job is done
688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
689 * @throws \ImagickException
691 private static function update1383()
693 // Was the script completed?
694 if (DI::config()->get("system", "post_update_version") >= 1383) {
698 Logger::info('Start');
701 $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
703 $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]);
704 while ($photo = DBA::fetch($photos)) {
705 $delete = !in_array($photo['scale'], [4, 5, 6]);
708 // Check if there is a contact entry with that photo
709 $delete = !DBA::exists('contact', ["`id` = ? AND `" . $avatar[$photo['scale']] . "` LIKE ?",
710 $photo['contact-id'], '%' . $photo['resource-id'] . '%']);
714 Photo::delete(['id' => $photo['id']]);
720 DI::config()->set("system", "post_update_version", 1383);
721 Logger::info('Done', ['deleted' => $deleted]);
726 * update the "hash" field in the photo table
728 * @return bool "true" when the job is done
729 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
730 * @throws \ImagickException
732 private static function update1384()
734 // Was the script completed?
735 if (DI::config()->get("system", "post_update_version") >= 1384) {
739 $condition = ["`hash` IS NULL"];
740 Logger::info('Start', ['rest' => DBA::count('photo', $condition)]);
743 $photos = DBA::select('photo', [], $condition, ['limit' => 10000]);
745 if (DBA::errorNo() != 0) {
746 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
750 while ($photo = DBA::fetch($photos)) {
751 $img = Photo::getImageForPhoto($photo);
753 $md5 = md5($img->asString());
757 DBA::update('photo', ['hash' => $md5], ['id' => $photo['id']]);
762 Logger::info('Processed', ['rows' => $rows]);
765 DI::config()->set("system", "post_update_version", 1384);
766 Logger::info('Done');
774 * update the "hash" field in the photo table
776 * @return bool "true" when the job is done
777 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
778 * @throws \ImagickException
780 private static function update1400()
782 // Was the script completed?
783 if (DI::config()->get("system", "post_update_version") >= 1400) {
787 if (!DBStructure::existsTable('item')) {
788 DI::config()->set("system", "post_update_version", 1400);
792 $condition = ["`extid` != ? AND EXISTS(SELECT `id` FROM `post-user` WHERE `uri-id` = `item`.`uri-id` AND `uid` = `item`.`uid` AND `external-id` IS NULL)", ''];
793 Logger::info('Start', ['rest' => DBA::count('item', $condition)]);
796 $items = DBA::select('item', ['uri-id', 'uid', 'extid'], $condition, ['order' => ['id'], 'limit' => 10000]);
798 if (DBA::errorNo() != 0) {
799 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
803 while ($item = DBA::fetch($items)) {
804 Post::update(['external-id' => ItemURI::getIdByURI($item['extid'])], ['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
809 Logger::info('Processed', ['rows' => $rows]);
812 DI::config()->set("system", "post_update_version", 1400);
813 Logger::info('Done');