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 if (!DBStructure::existsTable('item')) {
183 DI::config()->set('system', 'post_update_version', 1329);
187 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
189 Logger::info('Start', ['item' => $id]);
193 $condition = ["`id` > ?", $id];
194 $params = ['order' => ['id'], 'limit' => 10000];
195 $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params);
197 if (DBA::errorNo() != 0) {
198 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
202 while ($item = DBA::fetch($items)) {
205 Post\UserNotification::setNotification($item['uri-id'], $item['uid']);
211 DI::config()->set('system', 'post_update_version_1329_id', $id);
213 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
215 if ($start_id == $id) {
216 DI::config()->set('system', 'post_update_version', 1329);
217 Logger::info('Done');
225 * Fill the "tag" table with tags and mentions from the body
227 * @return bool "true" when the job is done
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 private static function update1341()
232 // Was the script completed?
233 if (DI::config()->get('system', 'post_update_version') >= 1341) {
237 if (!DBStructure::existsTable('item-content')) {
238 DI::config()->set('system', 'post_update_version', 1342);
242 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
244 Logger::info('Start', ['item' => $id]);
248 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
249 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
250 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
252 if (DBA::errorNo() != 0) {
253 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
257 while ($item = DBA::fetch($items)) {
258 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
259 $id = $item['uri-id'];
261 if ($rows % 1000 == 0) {
262 DI::config()->set('system', 'post_update_version_1341_id', $id);
267 DI::config()->set('system', 'post_update_version_1341_id', $id);
269 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
271 // When there are less than 1,000 items processed this means that we reached the end
272 // The other entries will then be processed with the regular functionality
274 DI::config()->set('system', 'post_update_version', 1341);
275 Logger::info('Done');
283 * Fill the "tag" table with tags and mentions from the "term" table
285 * @return bool "true" when the job is done
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 private static function update1342()
290 // Was the script completed?
291 if (DI::config()->get('system', 'post_update_version') >= 1342) {
295 if (!DBStructure::existsTable('term') || !DBStructure::existsTable('item-content')) {
296 DI::config()->set('system', 'post_update_version', 1342);
300 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
302 Logger::info('Start', ['item' => $id]);
306 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
308 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
309 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
310 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
311 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
313 if (DBA::errorNo() != 0) {
314 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
318 while ($term = DBA::fetch($terms)) {
319 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
320 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
321 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
322 if (!DBA::isResult($contact)) {
323 $ssl_url = str_replace('http://', 'https://', $term['url']);
324 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
325 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
328 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
329 $term['type'] = Tag::IMPLICIT_MENTION;
333 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
337 if ($rows % 1000 == 0) {
338 DI::config()->set('system', 'post_update_version_1342_id', $id);
343 DI::config()->set('system', 'post_update_version_1342_id', $id);
345 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
347 // When there are less than 1,000 items processed this means that we reached the end
348 // The other entries will then be processed with the regular functionality
350 DI::config()->set('system', 'post_update_version', 1342);
351 Logger::info('Done');
359 * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
361 * @return bool "true" when the job is done
362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364 private static function update1345()
366 // Was the script completed?
367 if (DI::config()->get('system', 'post_update_version') >= 1345) {
371 if (!DBStructure::existsTable('item-delivery-data')) {
372 DI::config()->set('system', 'post_update_version', 1345);
376 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
378 Logger::info('Start', ['item' => $id]);
382 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
383 `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
384 FROM `item-delivery-data`
385 INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
386 WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
388 if (DBA::errorNo() != 0) {
389 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
393 while ($delivery = DBA::fetch($deliveries)) {
394 $id = $delivery['iid'];
395 unset($delivery['iid']);
396 DBA::insert('post-delivery-data', $delivery, Database::INSERT_UPDATE);
399 DBA::close($deliveries);
401 DI::config()->set('system', 'post_update_version_1345_id', $id);
403 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
405 // When there are less than 100 items processed this means that we reached the end
406 // The other entries will then be processed with the regular functionality
408 DI::config()->set('system', 'post_update_version', 1345);
409 Logger::info('Done');
417 * Generates the legacy item.file field string from an item ID.
418 * Includes only file and category terms.
420 * @param int $item_id
424 private static function fileTextFromItemId($item_id)
428 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]];
429 $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition);
430 foreach ($tags as $tag) {
431 if ($tag['type'] == Category::CATEGORY) {
432 $file_text .= '<' . $tag['term'] . '>';
434 $file_text .= '[' . $tag['term'] . ']';
442 * Fill the "tag" table with tags and mentions from the "term" table
444 * @return bool "true" when the job is done
445 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
447 private static function update1346()
449 // Was the script completed?
450 if (DI::config()->get('system', 'post_update_version') >= 1346) {
454 if (!DBStructure::existsTable('term')) {
455 DI::config()->set('system', 'post_update_version', 1346);
459 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
461 Logger::info('Start', ['item' => $id]);
465 $terms = DBA::select('term', ['oid'],
466 ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
467 ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
469 if (DBA::errorNo() != 0) {
470 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
474 while ($term = DBA::fetch($terms)) {
475 $item = Post::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
476 if (!DBA::isResult($item)) {
480 $file = self::fileTextFromItemId($term['oid']);
482 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
487 if ($rows % 100 == 0) {
488 DI::config()->set('system', 'post_update_version_1346_id', $id);
493 DI::config()->set('system', 'post_update_version_1346_id', $id);
495 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
497 // When there are less than 10 items processed this means that we reached the end
498 // The other entries will then be processed with the regular functionality
500 DI::config()->set('system', 'post_update_version', 1346);
501 Logger::info('Done');
509 * update the "vid" (verb) field in the item table
511 * @return bool "true" when the job is done
512 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
513 * @throws \ImagickException
515 private static function update1347()
517 // Was the script completed?
518 if (DI::config()->get("system", "post_update_version") >= 1347) {
522 if (!DBStructure::existsTable('item-activity') || !DBStructure::existsTable('item')) {
523 DI::config()->set('system', 'post_update_version', 1347);
527 $id = DI::config()->get("system", "post_update_version_1347_id", 0);
529 Logger::info('Start', ['item' => $id]);
534 $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity`
535 FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
536 LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id` AND `item`.`gravity` = ?
537 WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", GRAVITY_ACTIVITY, $id);
539 if (DBA::errorNo() != 0) {
540 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
544 while ($item = DBA::fetch($items)) {
546 $verb = $item['item-verb'];
548 $verb = $item['verb'];
550 if (empty($verb) && is_int($item['activity'])) {
551 $verb = Item::ACTIVITIES[$item['activity']];
557 DBA::update('item', ['vid' => Verb::getID($verb)], ['id' => $item['id']]);
562 DI::config()->set("system", "post_update_version_1347_id", $id);
564 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
566 if ($start_id == $id) {
567 DI::config()->set("system", "post_update_version", 1347);
568 Logger::info('Done');
576 * update the "gsid" (global server id) field in the contact table
578 * @return bool "true" when the job is done
579 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
580 * @throws \ImagickException
582 private static function update1348()
584 // Was the script completed?
585 if (DI::config()->get("system", "post_update_version") >= 1348) {
589 $id = DI::config()->get("system", "post_update_version_1348_id", 0);
591 Logger::info('Start', ['contact' => $id]);
595 $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
596 $params = ['order' => ['id'], 'limit' => 10000];
597 $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
599 if (DBA::errorNo() != 0) {
600 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
604 while ($contact = DBA::fetch($contacts)) {
605 $id = $contact['id'];
607 DBA::update('contact',
608 ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
609 ['id' => $contact['id']]);
613 DBA::close($contacts);
615 DI::config()->set("system", "post_update_version_1348_id", $id);
617 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
619 if ($start_id == $id) {
620 DI::config()->set("system", "post_update_version", 1348);
621 Logger::info('Done');
629 * update the "gsid" (global server id) field in the apcontact table
631 * @return bool "true" when the job is done
632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
633 * @throws \ImagickException
635 private static function update1349()
637 // Was the script completed?
638 if (DI::config()->get("system", "post_update_version") >= 1349) {
642 $id = DI::config()->get("system", "post_update_version_1349_id", '');
644 Logger::info('Start', ['apcontact' => $id]);
648 $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id];
649 $params = ['order' => ['url'], 'limit' => 10000];
650 $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
652 if (DBA::errorNo() != 0) {
653 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
657 while ($apcontact = DBA::fetch($apcontacts)) {
658 $id = $apcontact['url'];
660 DBA::update('apcontact',
661 ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
662 ['url' => $apcontact['url']]);
666 DBA::close($apcontacts);
668 DI::config()->set("system", "post_update_version_1349_id", $id);
670 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
672 if ($start_id == $id) {
673 DI::config()->set("system", "post_update_version", 1349);
674 Logger::info('Done');
682 * Remove orphaned photo entries
684 * @return bool "true" when the job is done
685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
686 * @throws \ImagickException
688 private static function update1383()
690 // Was the script completed?
691 if (DI::config()->get("system", "post_update_version") >= 1383) {
695 Logger::info('Start');
698 $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
700 $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]);
701 while ($photo = DBA::fetch($photos)) {
702 $delete = !in_array($photo['scale'], [4, 5, 6]);
705 // Check if there is a contact entry with that photo
706 $delete = !DBA::exists('contact', ["`id` = ? AND `" . $avatar[$photo['scale']] . "` LIKE ?",
707 $photo['contact-id'], '%' . $photo['resource-id'] . '%']);
711 Photo::delete(['id' => $photo['id']]);
717 DI::config()->set("system", "post_update_version", 1383);
718 Logger::info('Done', ['deleted' => $deleted]);
723 * update the "hash" field in the photo table
725 * @return bool "true" when the job is done
726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
727 * @throws \ImagickException
729 private static function update1384()
731 // Was the script completed?
732 if (DI::config()->get("system", "post_update_version") >= 1384) {
736 $condition = ["`hash` IS NULL"];
737 Logger::info('Start', ['rest' => DBA::count('photo', $condition)]);
740 $photos = DBA::select('photo', [], $condition, ['limit' => 10000]);
742 if (DBA::errorNo() != 0) {
743 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
747 while ($photo = DBA::fetch($photos)) {
748 $img = Photo::getImageForPhoto($photo);
750 $md5 = md5($img->asString());
754 DBA::update('photo', ['hash' => $md5], ['id' => $photo['id']]);
759 Logger::info('Processed', ['rows' => $rows]);
762 DI::config()->set("system", "post_update_version", 1384);
763 Logger::info('Done');