3 * @copyright Copyright (C) 2020, Friendica
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\Photo;
31 use Friendica\Model\Post;
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;
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()) {
96 * Set the delivery queue count to a negative value for all items preceding the feature.
98 * @return bool "true" when the job is done
99 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 private static function update1297()
103 // Was the script completed?
104 if (DI::config()->get('system', 'post_update_version') >= 1297) {
108 if (!DBStructure::existsTable('item-delivery-data')) {
109 DI::config()->set('system', 'post_update_version', 1297);
113 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
114 $max_iid = $max_item_delivery_data['iid'];
116 Logger::info('Start update1297 with max iid: ' . $max_iid);
118 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
120 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
122 if (DBA::errorNo() != 0) {
123 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
127 Logger::info('Processed rows: ' . DBA::affectedRows());
129 DI::config()->set('system', 'post_update_version', 1297);
131 Logger::info('Done');
136 * Remove contact duplicates
138 * @return bool "true" when the job is done
139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141 private static function update1322()
143 // Was the script completed?
144 if (DI::config()->get('system', 'post_update_version') >= 1322) {
148 Logger::info('Start');
150 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
151 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
152 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
153 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
154 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
155 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
157 while ($contact = DBA::fetch($contacts)) {
158 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
159 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
162 DBA::close($contact);
163 DI::config()->set('system', 'post_update_version', 1322);
165 Logger::info('Done');
171 * update user-item data with notifications
173 * @return bool "true" when the job is done
174 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
176 private static function update1329()
178 // Was the script completed?
179 if (DI::config()->get('system', 'post_update_version') >= 1329) {
183 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
185 Logger::info('Start', ['item' => $id]);
189 $condition = ["`id` > ?", $id];
190 $params = ['order' => ['id'], 'limit' => 10000];
191 $items = DBA::select('item', ['id'], $condition, $params);
193 if (DBA::errorNo() != 0) {
194 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
198 while ($item = DBA::fetch($items)) {
201 UserItem::setNotification($item['id']);
207 DI::config()->set('system', 'post_update_version_1329_id', $id);
209 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
211 if ($start_id == $id) {
212 DI::config()->set('system', 'post_update_version', 1329);
213 Logger::info('Done');
221 * Fill the "tag" table with tags and mentions from the body
223 * @return bool "true" when the job is done
224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
226 private static function update1341()
228 // Was the script completed?
229 if (DI::config()->get('system', 'post_update_version') >= 1341) {
233 if (!DBStructure::existsTable('item-content')) {
234 DI::config()->set('system', 'post_update_version', 1342);
238 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
240 Logger::info('Start', ['item' => $id]);
244 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
245 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
246 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
248 if (DBA::errorNo() != 0) {
249 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
253 while ($item = DBA::fetch($items)) {
254 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
255 $id = $item['uri-id'];
257 if ($rows % 1000 == 0) {
258 DI::config()->set('system', 'post_update_version_1341_id', $id);
263 DI::config()->set('system', 'post_update_version_1341_id', $id);
265 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
267 // When there are less than 1,000 items processed this means that we reached the end
268 // The other entries will then be processed with the regular functionality
270 DI::config()->set('system', 'post_update_version', 1341);
271 Logger::info('Done');
279 * Fill the "tag" table with tags and mentions from the "term" table
281 * @return bool "true" when the job is done
282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
284 private static function update1342()
286 // Was the script completed?
287 if (DI::config()->get('system', 'post_update_version') >= 1342) {
291 if (!DBStructure::existsTable('term') || !DBStructure::existsTable('item-content')) {
292 DI::config()->set('system', 'post_update_version', 1342);
296 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
298 Logger::info('Start', ['item' => $id]);
302 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
304 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
305 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
306 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
307 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
309 if (DBA::errorNo() != 0) {
310 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
314 while ($term = DBA::fetch($terms)) {
315 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
316 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
317 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
318 if (!DBA::isResult($contact)) {
319 $ssl_url = str_replace('http://', 'https://', $term['url']);
320 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
321 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
324 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
325 $term['type'] = Tag::IMPLICIT_MENTION;
329 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
333 if ($rows % 1000 == 0) {
334 DI::config()->set('system', 'post_update_version_1342_id', $id);
339 DI::config()->set('system', 'post_update_version_1342_id', $id);
341 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
343 // When there are less than 1,000 items processed this means that we reached the end
344 // The other entries will then be processed with the regular functionality
346 DI::config()->set('system', 'post_update_version', 1342);
347 Logger::info('Done');
355 * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
357 * @return bool "true" when the job is done
358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360 private static function update1345()
362 // Was the script completed?
363 if (DI::config()->get('system', 'post_update_version') >= 1345) {
367 if (!DBStructure::existsTable('item-delivery-data')) {
368 DI::config()->set('system', 'post_update_version', 1345);
372 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
374 Logger::info('Start', ['item' => $id]);
378 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
379 `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
380 FROM `item-delivery-data`
381 INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
382 WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
384 if (DBA::errorNo() != 0) {
385 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
389 while ($delivery = DBA::fetch($deliveries)) {
390 $id = $delivery['iid'];
391 unset($delivery['iid']);
392 DBA::insert('post-delivery-data', $delivery, Database::INSERT_UPDATE);
395 DBA::close($deliveries);
397 DI::config()->set('system', 'post_update_version_1345_id', $id);
399 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
401 // When there are less than 100 items processed this means that we reached the end
402 // The other entries will then be processed with the regular functionality
404 DI::config()->set('system', 'post_update_version', 1345);
405 Logger::info('Done');
413 * Generates the legacy item.file field string from an item ID.
414 * Includes only file and category terms.
416 * @param int $item_id
420 private static function fileTextFromItemId($item_id)
424 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
425 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
426 foreach ($tags as $tag) {
427 if ($tag['type'] == Category::CATEGORY) {
428 $file_text .= '<' . $tag['term'] . '>';
430 $file_text .= '[' . $tag['term'] . ']';
438 * Fill the "tag" table with tags and mentions from the "term" table
440 * @return bool "true" when the job is done
441 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
443 private static function update1346()
445 // Was the script completed?
446 if (DI::config()->get('system', 'post_update_version') >= 1346) {
450 if (!DBStructure::existsTable('term')) {
451 DI::config()->set('system', 'post_update_version', 1346);
455 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
457 Logger::info('Start', ['item' => $id]);
461 $terms = DBA::select('term', ['oid'],
462 ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
463 ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
465 if (DBA::errorNo() != 0) {
466 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
470 while ($term = DBA::fetch($terms)) {
471 $item = Post::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
472 if (!DBA::isResult($item)) {
476 $file = self::fileTextFromItemId($term['oid']);
478 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
483 if ($rows % 100 == 0) {
484 DI::config()->set('system', 'post_update_version_1346_id', $id);
489 DI::config()->set('system', 'post_update_version_1346_id', $id);
491 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
493 // When there are less than 10 items processed this means that we reached the end
494 // The other entries will then be processed with the regular functionality
496 DI::config()->set('system', 'post_update_version', 1346);
497 Logger::info('Done');
505 * update the "vid" (verb) field in the item table
507 * @return bool "true" when the job is done
508 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
509 * @throws \ImagickException
511 private static function update1347()
513 // Was the script completed?
514 if (DI::config()->get("system", "post_update_version") >= 1347) {
518 if (!DBStructure::existsTable('item-activity')) {
519 DI::config()->set('system', 'post_update_version', 1347);
523 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
525 Logger::info('Start', ['item' => $id]);
530 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
531 FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
532 LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
533 WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", GRAVITY_ACTIVITY, $id);
535 if (DBA::errorNo() != 0) {
536 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
540 while ($item = DBA::fetch($items)) {
542 $verb = $item['item-verb'];
544 $verb = $item['verb'];
546 if (empty($verb) && is_int($item['activity'])) {
547 $verb = Item::ACTIVITIES[$item['activity']];
553 DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
558 DI::config()->set("system", "post_update_version_1347_id", $id);
560 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
562 if ($start_id == $id) {
563 DI::config()->set("system", "post_update_version", 1347);
564 Logger::info('Done');
572 * update the "gsid" (global server id) field in the contact table
574 * @return bool "true" when the job is done
575 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
576 * @throws \ImagickException
578 private static function update1348()
580 // Was the script completed?
581 if (DI::config()->get("system", "post_update_version") >= 1348) {
585 $id = DI::config()->get("system", "post_update_version_1348_id", 0);
587 Logger::info('Start', ['contact' => $id]);
591 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
592 $params = ['order' => ['id'], 'limit' => 10000];
593 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
595 if (DBA::errorNo() != 0) {
596 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
600 while ($contact = DBA::fetch($contacts)) {
601 $id = $contact['id'];
603 DBA::update('contact',
604 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
605 ['id' => $contact['id']]);
609 DBA::close($contacts);
611 DI::config()->set("system", "post_update_version_1348_id", $id);
613 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
615 if ($start_id == $id) {
616 DI::config()->set("system", "post_update_version", 1348);
617 Logger::info('Done');
625 * update the "gsid" (global server id) field in the apcontact table
627 * @return bool "true" when the job is done
628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
629 * @throws \ImagickException
631 private static function update1349()
633 // Was the script completed?
634 if (DI::config()->get("system", "post_update_version") >= 1349) {
638 $id = DI::config()->get("system", "post_update_version_1349_id", '');
640 Logger::info('Start', ['apcontact' => $id]);
644 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
645 $params = ['order' => ['url'], 'limit' => 10000];
646 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
648 if (DBA::errorNo() != 0) {
649 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
653 while ($apcontact = DBA::fetch($apcontacts)) {
654 $id = $apcontact['url'];
656 DBA::update('apcontact',
657 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
658 ['url' => $apcontact['url']]);
662 DBA::close($apcontacts);
664 DI::config()->set("system", "post_update_version_1349_id", $id);
666 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
668 if ($start_id == $id) {
669 DI::config()->set("system", "post_update_version", 1349);
670 Logger::info('Done');
678 * Remove orphaned photo entries
680 * @return bool "true" when the job is done
681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
682 * @throws \ImagickException
684 private static function update1383()
686 // Was the script completed?
687 if (DI::config()->get("system", "post_update_version") >= 1383) {
691 Logger::info('Start');
694 $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
696 $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]);
697 while ($photo = DBA::fetch($photos)) {
698 $delete = !in_array($photo['scale'], [4, 5, 6]);
701 // Check if there is a contact entry with that photo
702 $delete = !DBA::exists('contact', ["`id` = ? AND `" . $avatar[$photo['scale']] . "` LIKE ?",
703 $photo['contact-id'], '%' . $photo['resource-id'] . '%']);
707 Photo::delete(['id' => $photo['id']]);
713 DI::config()->set("system", "post_update_version", 1383);
714 Logger::info('Done', ['deleted' => $deleted]);
719 * update the "hash" field in the photo table
721 * @return bool "true" when the job is done
722 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
723 * @throws \ImagickException
725 private static function update1384()
727 // Was the script completed?
728 if (DI::config()->get("system", "post_update_version") >= 1384) {
732 $condition = ["`hash` IS NULL"];
733 Logger::info('Start', ['rest' => DBA::count('photo', $condition)]);
736 $photos = DBA::select('photo', [], $condition, ['limit' => 10000]);
738 if (DBA::errorNo() != 0) {
739 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
743 while ($photo = DBA::fetch($photos)) {
744 $img = Photo::getImageForPhoto($photo);
746 $md5 = md5($img->asString());
750 DBA::update('photo', ['hash' => $md5], ['id' => $photo['id']]);
755 Logger::info('Processed', ['rows' => $rows]);
758 DI::config()->set("system", "post_update_version", 1384);
759 Logger::info('Done');