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 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
235 Logger::info('Start', ['item' => $id]);
239 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
240 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
241 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
243 if (DBA::errorNo() != 0) {
244 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
248 while ($item = DBA::fetch($items)) {
249 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
250 $id = $item['uri-id'];
252 if ($rows % 1000 == 0) {
253 DI::config()->set('system', 'post_update_version_1341_id', $id);
258 DI::config()->set('system', 'post_update_version_1341_id', $id);
260 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
262 // When there are less than 1,000 items processed this means that we reached the end
263 // The other entries will then be processed with the regular functionality
265 DI::config()->set('system', 'post_update_version', 1341);
266 Logger::info('Done');
274 * Fill the "tag" table with tags and mentions from the "term" table
276 * @return bool "true" when the job is done
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 private static function update1342()
281 // Was the script completed?
282 if (DI::config()->get('system', 'post_update_version') >= 1342) {
286 if (!DBStructure::existsTable('term')) {
287 DI::config()->set('system', 'post_update_version', 1342);
291 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
293 Logger::info('Start', ['item' => $id]);
297 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
299 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
300 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
301 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
302 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
304 if (DBA::errorNo() != 0) {
305 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
309 while ($term = DBA::fetch($terms)) {
310 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
311 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
312 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
313 if (!DBA::isResult($contact)) {
314 $ssl_url = str_replace('http://', 'https://', $term['url']);
315 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
316 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
319 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
320 $term['type'] = Tag::IMPLICIT_MENTION;
324 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
328 if ($rows % 1000 == 0) {
329 DI::config()->set('system', 'post_update_version_1342_id', $id);
334 DI::config()->set('system', 'post_update_version_1342_id', $id);
336 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
338 // When there are less than 1,000 items processed this means that we reached the end
339 // The other entries will then be processed with the regular functionality
341 DI::config()->set('system', 'post_update_version', 1342);
342 Logger::info('Done');
350 * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
352 * @return bool "true" when the job is done
353 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
355 private static function update1345()
357 // Was the script completed?
358 if (DI::config()->get('system', 'post_update_version') >= 1345) {
362 if (!DBStructure::existsTable('item-delivery-data')) {
363 DI::config()->set('system', 'post_update_version', 1345);
367 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
369 Logger::info('Start', ['item' => $id]);
373 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
374 `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
375 FROM `item-delivery-data`
376 INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
377 WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
379 if (DBA::errorNo() != 0) {
380 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
384 while ($delivery = DBA::fetch($deliveries)) {
385 $id = $delivery['iid'];
386 unset($delivery['iid']);
387 DBA::insert('post-delivery-data', $delivery, Database::INSERT_UPDATE);
390 DBA::close($deliveries);
392 DI::config()->set('system', 'post_update_version_1345_id', $id);
394 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
396 // When there are less than 100 items processed this means that we reached the end
397 // The other entries will then be processed with the regular functionality
399 DI::config()->set('system', 'post_update_version', 1345);
400 Logger::info('Done');
408 * Generates the legacy item.file field string from an item ID.
409 * Includes only file and category terms.
411 * @param int $item_id
415 private static function fileTextFromItemId($item_id)
419 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
420 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
421 foreach ($tags as $tag) {
422 if ($tag['type'] == Category::CATEGORY) {
423 $file_text .= '<' . $tag['term'] . '>';
425 $file_text .= '[' . $tag['term'] . ']';
433 * Fill the "tag" table with tags and mentions from the "term" table
435 * @return bool "true" when the job is done
436 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
438 private static function update1346()
440 // Was the script completed?
441 if (DI::config()->get('system', 'post_update_version') >= 1346) {
445 if (!DBStructure::existsTable('term')) {
446 DI::config()->set('system', 'post_update_version', 1346);
450 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
452 Logger::info('Start', ['item' => $id]);
456 $terms = DBA::select('term', ['oid'],
457 ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
458 ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
460 if (DBA::errorNo() != 0) {
461 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
465 while ($term = DBA::fetch($terms)) {
466 $item = Post::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
467 if (!DBA::isResult($item)) {
471 $file = self::fileTextFromItemId($term['oid']);
473 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
478 if ($rows % 100 == 0) {
479 DI::config()->set('system', 'post_update_version_1346_id', $id);
484 DI::config()->set('system', 'post_update_version_1346_id', $id);
486 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
488 // When there are less than 10 items processed this means that we reached the end
489 // The other entries will then be processed with the regular functionality
491 DI::config()->set('system', 'post_update_version', 1346);
492 Logger::info('Done');
500 * update the "vid" (verb) field in the item table
502 * @return bool "true" when the job is done
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 * @throws \ImagickException
506 private static function update1347()
508 // Was the script completed?
509 if (DI::config()->get("system", "post_update_version") >= 1347) {
513 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
515 Logger::info('Start', ['item' => $id]);
520 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
521 FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
522 LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
523 WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", GRAVITY_ACTIVITY, $id);
525 if (DBA::errorNo() != 0) {
526 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
530 while ($item = DBA::fetch($items)) {
532 $verb = $item['item-verb'];
534 $verb = $item['verb'];
536 if (empty($verb) && is_int($item['activity'])) {
537 $verb = Item::ACTIVITIES[$item['activity']];
543 DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
548 DI::config()->set("system", "post_update_version_1347_id", $id);
550 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
552 if ($start_id == $id) {
553 DI::config()->set("system", "post_update_version", 1347);
554 Logger::info('Done');
562 * update the "gsid" (global server id) field in the contact table
564 * @return bool "true" when the job is done
565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
566 * @throws \ImagickException
568 private static function update1348()
570 // Was the script completed?
571 if (DI::config()->get("system", "post_update_version") >= 1348) {
575 $id = DI::config()->get("system", "post_update_version_1348_id", 0);
577 Logger::info('Start', ['contact' => $id]);
581 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
582 $params = ['order' => ['id'], 'limit' => 10000];
583 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
585 if (DBA::errorNo() != 0) {
586 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
590 while ($contact = DBA::fetch($contacts)) {
591 $id = $contact['id'];
593 DBA::update('contact',
594 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
595 ['id' => $contact['id']]);
599 DBA::close($contacts);
601 DI::config()->set("system", "post_update_version_1348_id", $id);
603 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
605 if ($start_id == $id) {
606 DI::config()->set("system", "post_update_version", 1348);
607 Logger::info('Done');
615 * update the "gsid" (global server id) field in the apcontact table
617 * @return bool "true" when the job is done
618 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
619 * @throws \ImagickException
621 private static function update1349()
623 // Was the script completed?
624 if (DI::config()->get("system", "post_update_version") >= 1349) {
628 $id = DI::config()->get("system", "post_update_version_1349_id", '');
630 Logger::info('Start', ['apcontact' => $id]);
634 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
635 $params = ['order' => ['url'], 'limit' => 10000];
636 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
638 if (DBA::errorNo() != 0) {
639 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
643 while ($apcontact = DBA::fetch($apcontacts)) {
644 $id = $apcontact['url'];
646 DBA::update('apcontact',
647 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
648 ['url' => $apcontact['url']]);
652 DBA::close($apcontacts);
654 DI::config()->set("system", "post_update_version_1349_id", $id);
656 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
658 if ($start_id == $id) {
659 DI::config()->set("system", "post_update_version", 1349);
660 Logger::info('Done');
668 * Remove orphaned photo entries
670 * @return bool "true" when the job is done
671 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
672 * @throws \ImagickException
674 private static function update1383()
676 // Was the script completed?
677 if (DI::config()->get("system", "post_update_version") >= 1383) {
681 Logger::info('Start');
684 $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
686 $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]);
687 while ($photo = DBA::fetch($photos)) {
688 $delete = !in_array($photo['scale'], [4, 5, 6]);
691 // Check if there is a contact entry with that photo
692 $delete = !DBA::exists('contact', ["`id` = ? AND `" . $avatar[$photo['scale']] . "` LIKE ?",
693 $photo['contact-id'], '%' . $photo['resource-id'] . '%']);
697 Photo::delete(['id' => $photo['id']]);
703 DI::config()->set("system", "post_update_version", 1383);
704 Logger::info('Done', ['deleted' => $deleted]);
709 * update the "hash" field in the photo table
711 * @return bool "true" when the job is done
712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
713 * @throws \ImagickException
715 private static function update1384()
717 // Was the script completed?
718 if (DI::config()->get("system", "post_update_version") >= 1384) {
722 $condition = ["`hash` IS NULL"];
723 Logger::info('Start', ['rest' => DBA::count('photo', $condition)]);
726 $photos = DBA::select('photo', [], $condition, ['limit' => 10000]);
728 if (DBA::errorNo() != 0) {
729 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
733 while ($photo = DBA::fetch($photos)) {
734 $img = Photo::getImageForPhoto($photo);
736 $md5 = md5($img->asString());
740 DBA::update('photo', ['hash' => $md5], ['id' => $photo['id']]);
745 Logger::info('Processed', ['rows' => $rows]);
748 DI::config()->set("system", "post_update_version", 1384);
749 Logger::info('Done');