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\Verb;
35 use Friendica\Util\Strings;
38 * These database-intensive post update routines are meant to be executed in the background by the cronjob.
40 * If there is a need for a intensive migration after a database structure change, update this file
41 * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
45 // Needed for the helper function to read from the legacy term table
46 const OBJECT_TYPE_POST = 1;
50 * Calls the post update functions
52 public static function update()
54 if (!self::update1297()) {
57 if (!self::update1322()) {
60 if (!self::update1329()) {
63 if (!self::update1341()) {
66 if (!self::update1342()) {
69 if (!self::update1345()) {
72 if (!self::update1346()) {
75 if (!self::update1347()) {
78 if (!self::update1348()) {
81 if (!self::update1349()) {
84 if (!self::update1383()) {
87 if (!self::update1384()) {
95 * Set the delivery queue count to a negative value for all items preceding the feature.
97 * @return bool "true" when the job is done
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 private static function update1297()
102 // Was the script completed?
103 if (DI::config()->get('system', 'post_update_version') >= 1297) {
107 if (!DBStructure::existsTable('item-delivery-data')) {
108 DI::config()->set('system', 'post_update_version', 1297);
112 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
113 $max_iid = $max_item_delivery_data['iid'];
115 Logger::info('Start update1297 with max iid: ' . $max_iid);
117 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
119 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
121 if (DBA::errorNo() != 0) {
122 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
126 Logger::info('Processed rows: ' . DBA::affectedRows());
128 DI::config()->set('system', 'post_update_version', 1297);
130 Logger::info('Done');
135 * Remove contact duplicates
137 * @return bool "true" when the job is done
138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
140 private static function update1322()
142 // Was the script completed?
143 if (DI::config()->get('system', 'post_update_version') >= 1322) {
147 Logger::info('Start');
149 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
150 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
151 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
152 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
153 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
154 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
156 while ($contact = DBA::fetch($contacts)) {
157 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
158 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
161 DBA::close($contact);
162 DI::config()->set('system', 'post_update_version', 1322);
164 Logger::info('Done');
170 * update user notification data
172 * @return bool "true" when the job is done
173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
175 private static function update1329()
177 // Was the script completed?
178 if (DI::config()->get('system', 'post_update_version') >= 1329) {
182 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
184 Logger::info('Start', ['item' => $id]);
188 $condition = ["`id` > ?", $id];
189 $params = ['order' => ['id'], 'limit' => 10000];
190 $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params);
192 if (DBA::errorNo() != 0) {
193 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
197 while ($item = DBA::fetch($items)) {
200 Post\UserNotification::setNotification($item['uri-id'], $item['uid']);
206 DI::config()->set('system', 'post_update_version_1329_id', $id);
208 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
210 if ($start_id == $id) {
211 DI::config()->set('system', 'post_update_version', 1329);
212 Logger::info('Done');
220 * Fill the "tag" table with tags and mentions from the body
222 * @return bool "true" when the job is done
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 private static function update1341()
227 // Was the script completed?
228 if (DI::config()->get('system', 'post_update_version') >= 1341) {
232 if (!DBStructure::existsTable('item-content')) {
233 DI::config()->set('system', 'post_update_version', 1342);
237 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
239 Logger::info('Start', ['item' => $id]);
243 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
244 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
245 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
247 if (DBA::errorNo() != 0) {
248 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
252 while ($item = DBA::fetch($items)) {
253 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
254 $id = $item['uri-id'];
256 if ($rows % 1000 == 0) {
257 DI::config()->set('system', 'post_update_version_1341_id', $id);
262 DI::config()->set('system', 'post_update_version_1341_id', $id);
264 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
266 // When there are less than 1,000 items processed this means that we reached the end
267 // The other entries will then be processed with the regular functionality
269 DI::config()->set('system', 'post_update_version', 1341);
270 Logger::info('Done');
278 * Fill the "tag" table with tags and mentions from the "term" table
280 * @return bool "true" when the job is done
281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
283 private static function update1342()
285 // Was the script completed?
286 if (DI::config()->get('system', 'post_update_version') >= 1342) {
290 if (!DBStructure::existsTable('term') || !DBStructure::existsTable('item-content')) {
291 DI::config()->set('system', 'post_update_version', 1342);
295 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
297 Logger::info('Start', ['item' => $id]);
301 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
303 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
304 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
305 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
306 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
308 if (DBA::errorNo() != 0) {
309 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
313 while ($term = DBA::fetch($terms)) {
314 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
315 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
316 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
317 if (!DBA::isResult($contact)) {
318 $ssl_url = str_replace('http://', 'https://', $term['url']);
319 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
320 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
323 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
324 $term['type'] = Tag::IMPLICIT_MENTION;
328 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
332 if ($rows % 1000 == 0) {
333 DI::config()->set('system', 'post_update_version_1342_id', $id);
338 DI::config()->set('system', 'post_update_version_1342_id', $id);
340 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
342 // When there are less than 1,000 items processed this means that we reached the end
343 // The other entries will then be processed with the regular functionality
345 DI::config()->set('system', 'post_update_version', 1342);
346 Logger::info('Done');
354 * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
356 * @return bool "true" when the job is done
357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
359 private static function update1345()
361 // Was the script completed?
362 if (DI::config()->get('system', 'post_update_version') >= 1345) {
366 if (!DBStructure::existsTable('item-delivery-data')) {
367 DI::config()->set('system', 'post_update_version', 1345);
371 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
373 Logger::info('Start', ['item' => $id]);
377 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
378 `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
379 FROM `item-delivery-data`
380 INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
381 WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
383 if (DBA::errorNo() != 0) {
384 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
388 while ($delivery = DBA::fetch($deliveries)) {
389 $id = $delivery['iid'];
390 unset($delivery['iid']);
391 DBA::insert('post-delivery-data', $delivery, Database::INSERT_UPDATE);
394 DBA::close($deliveries);
396 DI::config()->set('system', 'post_update_version_1345_id', $id);
398 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
400 // When there are less than 100 items processed this means that we reached the end
401 // The other entries will then be processed with the regular functionality
403 DI::config()->set('system', 'post_update_version', 1345);
404 Logger::info('Done');
412 * Generates the legacy item.file field string from an item ID.
413 * Includes only file and category terms.
415 * @param int $item_id
419 private static function fileTextFromItemId($item_id)
423 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
424 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
425 foreach ($tags as $tag) {
426 if ($tag['type'] == Category::CATEGORY) {
427 $file_text .= '<' . $tag['term'] . '>';
429 $file_text .= '[' . $tag['term'] . ']';
437 * Fill the "tag" table with tags and mentions from the "term" table
439 * @return bool "true" when the job is done
440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442 private static function update1346()
444 // Was the script completed?
445 if (DI::config()->get('system', 'post_update_version') >= 1346) {
449 if (!DBStructure::existsTable('term')) {
450 DI::config()->set('system', 'post_update_version', 1346);
454 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
456 Logger::info('Start', ['item' => $id]);
460 $terms = DBA::select('term', ['oid'],
461 ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
462 ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
464 if (DBA::errorNo() != 0) {
465 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
469 while ($term = DBA::fetch($terms)) {
470 $item = Post::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
471 if (!DBA::isResult($item)) {
475 $file = self::fileTextFromItemId($term['oid']);
477 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
482 if ($rows % 100 == 0) {
483 DI::config()->set('system', 'post_update_version_1346_id', $id);
488 DI::config()->set('system', 'post_update_version_1346_id', $id);
490 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
492 // When there are less than 10 items processed this means that we reached the end
493 // The other entries will then be processed with the regular functionality
495 DI::config()->set('system', 'post_update_version', 1346);
496 Logger::info('Done');
504 * update the "vid" (verb) field in the item table
506 * @return bool "true" when the job is done
507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508 * @throws \ImagickException
510 private static function update1347()
512 // Was the script completed?
513 if (DI::config()->get("system", "post_update_version") >= 1347) {
517 if (!DBStructure::existsTable('item-activity')) {
518 DI::config()->set('system', 'post_update_version', 1347);
522 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
524 Logger::info('Start', ['item' => $id]);
529 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
530 FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
531 LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
532 WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", GRAVITY_ACTIVITY, $id);
534 if (DBA::errorNo() != 0) {
535 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
539 while ($item = DBA::fetch($items)) {
541 $verb = $item['item-verb'];
543 $verb = $item['verb'];
545 if (empty($verb) && is_int($item['activity'])) {
546 $verb = Item::ACTIVITIES[$item['activity']];
552 DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
557 DI::config()->set("system", "post_update_version_1347_id", $id);
559 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
561 if ($start_id == $id) {
562 DI::config()->set("system", "post_update_version", 1347);
563 Logger::info('Done');
571 * update the "gsid" (global server id) field in the contact table
573 * @return bool "true" when the job is done
574 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
575 * @throws \ImagickException
577 private static function update1348()
579 // Was the script completed?
580 if (DI::config()->get("system", "post_update_version") >= 1348) {
584 $id = DI::config()->get("system", "post_update_version_1348_id", 0);
586 Logger::info('Start', ['contact' => $id]);
590 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
591 $params = ['order' => ['id'], 'limit' => 10000];
592 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
594 if (DBA::errorNo() != 0) {
595 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
599 while ($contact = DBA::fetch($contacts)) {
600 $id = $contact['id'];
602 DBA::update('contact',
603 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
604 ['id' => $contact['id']]);
608 DBA::close($contacts);
610 DI::config()->set("system", "post_update_version_1348_id", $id);
612 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
614 if ($start_id == $id) {
615 DI::config()->set("system", "post_update_version", 1348);
616 Logger::info('Done');
624 * update the "gsid" (global server id) field in the apcontact table
626 * @return bool "true" when the job is done
627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
628 * @throws \ImagickException
630 private static function update1349()
632 // Was the script completed?
633 if (DI::config()->get("system", "post_update_version") >= 1349) {
637 $id = DI::config()->get("system", "post_update_version_1349_id", '');
639 Logger::info('Start', ['apcontact' => $id]);
643 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
644 $params = ['order' => ['url'], 'limit' => 10000];
645 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
647 if (DBA::errorNo() != 0) {
648 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
652 while ($apcontact = DBA::fetch($apcontacts)) {
653 $id = $apcontact['url'];
655 DBA::update('apcontact',
656 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
657 ['url' => $apcontact['url']]);
661 DBA::close($apcontacts);
663 DI::config()->set("system", "post_update_version_1349_id", $id);
665 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
667 if ($start_id == $id) {
668 DI::config()->set("system", "post_update_version", 1349);
669 Logger::info('Done');
677 * Remove orphaned photo entries
679 * @return bool "true" when the job is done
680 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
681 * @throws \ImagickException
683 private static function update1383()
685 // Was the script completed?
686 if (DI::config()->get("system", "post_update_version") >= 1383) {
690 Logger::info('Start');
693 $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
695 $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]);
696 while ($photo = DBA::fetch($photos)) {
697 $delete = !in_array($photo['scale'], [4, 5, 6]);
700 // Check if there is a contact entry with that photo
701 $delete = !DBA::exists('contact', ["`id` = ? AND `" . $avatar[$photo['scale']] . "` LIKE ?",
702 $photo['contact-id'], '%' . $photo['resource-id'] . '%']);
706 Photo::delete(['id' => $photo['id']]);
712 DI::config()->set("system", "post_update_version", 1383);
713 Logger::info('Done', ['deleted' => $deleted]);
718 * update the "hash" field in the photo table
720 * @return bool "true" when the job is done
721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
722 * @throws \ImagickException
724 private static function update1384()
726 // Was the script completed?
727 if (DI::config()->get("system", "post_update_version") >= 1384) {
731 $condition = ["`hash` IS NULL"];
732 Logger::info('Start', ['rest' => DBA::count('photo', $condition)]);
735 $photos = DBA::select('photo', [], $condition, ['limit' => 10000]);
737 if (DBA::errorNo() != 0) {
738 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
742 while ($photo = DBA::fetch($photos)) {
743 $img = Photo::getImageForPhoto($photo);
745 $md5 = md5($img->asString());
749 DBA::update('photo', ['hash' => $md5], ['id' => $photo['id']]);
754 Logger::info('Processed', ['rows' => $rows]);
757 DI::config()->set("system", "post_update_version", 1384);
758 Logger::info('Done');