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\Item;
29 use Friendica\Model\ItemURI;
30 use Friendica\Model\PermissionSet;
31 use Friendica\Model\Tag;
32 use Friendica\Model\UserItem;
33 use Friendica\Util\Strings;
36 * These database-intensive post update routines are meant to be executed in the background by the cronjob.
38 * If there is a need for a intensive migration after a database structure change, update this file
39 * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
44 * Calls the post update functions
46 public static function update()
48 if (!self::update1194()) {
51 if (!self::update1206()) {
54 if (!self::update1279()) {
57 if (!self::update1281()) {
60 if (!self::update1297()) {
63 if (!self::update1322()) {
66 if (!self::update1329()) {
69 if (!self::update1341()) {
72 if (!self::update1342()) {
75 if (!self::update1345()) {
83 * Updates the "global" field in the item table
85 * @return bool "true" when the job is done
86 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
88 private static function update1194()
90 // Was the script completed?
91 if (DI::config()->get("system", "post_update_version") >= 1194) {
95 Logger::log("Start", Logger::DEBUG);
97 $end_id = DI::config()->get("system", "post_update_1194_end");
99 $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
101 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
102 $end_id = DI::config()->get("system", "post_update_1194_end");
106 Logger::log("End ID: ".$end_id, Logger::DEBUG);
108 $start_id = DI::config()->get("system", "post_update_1194_start");
110 $query1 = "SELECT `item`.`id` FROM `item` ";
112 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
114 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
115 AND `item`.`visible` AND NOT `item`.`private`
116 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
117 AND `item`.`network` IN ('%s', '%s', '%s', '')
118 AND NOT `item`.`global`";
120 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1",
121 intval($start_id), intval($end_id),
122 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
124 DI::config()->set("system", "post_update_version", 1194);
125 Logger::log("Update is done", Logger::DEBUG);
128 DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
129 $start_id = DI::config()->get("system", "post_update_1194_start");
132 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
134 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1",
135 intval($start_id), intval($end_id),
136 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
138 $pos_id = $r[0]["id"];
142 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
144 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
145 intval($start_id), intval($pos_id),
146 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
148 Logger::log("Done", Logger::DEBUG);
152 * update the "last-item" field in the "self" contact
154 * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
156 * @return bool "true" when the job is done
157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
159 private static function update1206()
161 // Was the script completed?
162 if (DI::config()->get("system", "post_update_version") >= 1206) {
166 Logger::log("Start", Logger::DEBUG);
167 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
168 (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
170 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
172 if (!DBA::isResult($r)) {
175 foreach ($r as $user) {
176 if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
177 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
181 DI::config()->set("system", "post_update_version", 1206);
182 Logger::log("Done", Logger::DEBUG);
187 * update the item related tables
189 * @return bool "true" when the job is done
190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
191 * @throws \ImagickException
193 private static function update1279()
195 // Was the script completed?
196 if (DI::config()->get("system", "post_update_version") >= 1279) {
200 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
202 Logger::log("Start from item " . $id, Logger::DEBUG);
204 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
205 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
206 'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
207 'inform', 'postopts', 'icid']);
211 $condition = ["`id` > ?", $id];
212 $params = ['order' => ['id'], 'limit' => 10000];
213 $items = Item::select($fields, $condition, $params);
215 if (DBA::errorNo() != 0) {
216 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
220 while ($item = Item::fetch($items)) {
223 if (empty($item['author-id'])) {
224 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
225 'photo' => $item['author-avatar'], 'network' => $item['network']];
227 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
230 if (empty($item['owner-id'])) {
231 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
232 'photo' => $item['owner-avatar'], 'network' => $item['network']];
234 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
237 if (empty($item['psid'])) {
238 $item['psid'] = PermissionSet::getIdFromACL(
247 $item['allow_cid'] = null;
248 $item['allow_gid'] = null;
249 $item['deny_cid'] = null;
250 $item['deny_gid'] = null;
252 if ($item['post-type'] == 0) {
253 if (!empty($item['type']) && ($item['type'] == 'note')) {
254 $item['post-type'] = Item::PT_PERSONAL_NOTE;
255 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
256 $item['post-type'] = Item::PT_IMAGE;
257 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
258 $item['post-type'] = Item::PT_PAGE;
262 self::createLanguage($item);
264 if (!empty($item['icid']) && !empty($item['language'])) {
265 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
267 unset($item['language']);
269 Item::update($item, ['id' => $id]);
275 DI::config()->set("system", "post_update_version_1279_id", $id);
277 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
279 if ($start_id == $id) {
280 // Set all deprecated fields to "null" if they contain an empty string
281 $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
282 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
283 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
284 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
285 'rendered-hash', 'rendered-html'];
286 foreach ($nullfields as $field) {
287 $fields = [$field => null];
288 $condition = [$field => ''];
289 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
290 // Important: This has to be a "DBA::update", not a "Item::update"
291 DBA::update('item', $fields, $condition);
294 DI::config()->set("system", "post_update_version", 1279);
295 Logger::log("Done", Logger::DEBUG);
302 private static function createLanguage(&$item)
304 if (empty($item['postopts'])) {
308 $opts = explode(',', $item['postopts']);
312 foreach ($opts as $opt) {
313 if (strstr($opt, 'lang=')) {
314 $language = substr($opt, 5);
320 if (empty($language)) {
324 if (!empty($postopts)) {
325 $item['postopts'] = implode(',', $postopts);
327 $item['postopts'] = null;
330 $lang_pairs = explode(':', $language);
334 foreach ($lang_pairs as $pair) {
335 $lang_pair_arr = explode(';', $pair);
336 if (count($lang_pair_arr) == 2) {
337 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
341 $item['language'] = json_encode($lang_arr);
345 * update item-uri data. Prerequisite for the next item structure update.
347 * @return bool "true" when the job is done
348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
350 private static function update1281()
352 // Was the script completed?
353 if (DI::config()->get("system", "post_update_version") >= 1281) {
357 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
359 Logger::log("Start from item " . $id, Logger::DEBUG);
361 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
365 $condition = ["`id` > ?", $id];
366 $params = ['order' => ['id'], 'limit' => 10000];
367 $items = DBA::select('item', $fields, $condition, $params);
369 if (DBA::errorNo() != 0) {
370 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
374 while ($item = DBA::fetch($items)) {
377 if (empty($item['uri'])) {
380 } elseif (empty($item['uri-id'])) {
381 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
384 if (empty($item['parent-uri'])) {
385 $item['parent-uri-id'] = $item['uri-id'];
386 } elseif (empty($item['parent-uri-id'])) {
387 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
390 // Very old items don't have this field
391 if (empty($item['thr-parent'])) {
392 $item['thr-parent-id'] = $item['parent-uri-id'];
393 } elseif (empty($item['thr-parent-id'])) {
394 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
398 unset($item['guid']);
400 unset($item['parent-uri']);
401 unset($item['thr-parent']);
403 DBA::update('item', $item, ['id' => $id]);
409 DI::config()->set("system", "post_update_version_1281_id", $id);
411 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
413 if ($start_id == $id) {
414 Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
415 DBA::e("UPDATE `item-activity` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-activity`.`uri` SET `item-activity`.`uri-id` = `item-uri`.`id` WHERE `item-activity`.`uri-id` IS NULL");
417 Logger::log("Updating item-uri in item-content", Logger::DEBUG);
418 DBA::e("UPDATE `item-content` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-content`.`uri` SET `item-content`.`uri-id` = `item-uri`.`id` WHERE `item-content`.`uri-id` IS NULL");
420 DI::config()->set("system", "post_update_version", 1281);
421 Logger::log("Done", Logger::DEBUG);
429 * Set the delivery queue count to a negative value for all items preceding the feature.
431 * @return bool "true" when the job is done
432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 private static function update1297()
436 // Was the script completed?
437 if (DI::config()->get('system', 'post_update_version') >= 1297) {
441 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
442 $max_iid = $max_item_delivery_data['iid'];
444 Logger::info('Start update1297 with max iid: ' . $max_iid);
446 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
448 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
450 if (DBA::errorNo() != 0) {
451 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
455 Logger::info('Processed rows: ' . DBA::affectedRows());
457 DI::config()->set('system', 'post_update_version', 1297);
459 Logger::info('Done');
464 * Remove contact duplicates
466 * @return bool "true" when the job is done
467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
469 private static function update1322()
471 // Was the script completed?
472 if (DI::config()->get('system', 'post_update_version') >= 1322) {
476 Logger::info('Start');
478 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
479 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
480 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
481 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
482 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
483 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
485 while ($contact = DBA::fetch($contacts)) {
486 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
487 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
490 DBA::close($contact);
491 DI::config()->set('system', 'post_update_version', 1322);
493 Logger::info('Done');
499 * update user-item data with notifications
501 * @return bool "true" when the job is done
502 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 private static function update1329()
506 // Was the script completed?
507 if (DI::config()->get('system', 'post_update_version') >= 1329) {
511 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
513 Logger::info('Start', ['item' => $id]);
517 $condition = ["`id` > ?", $id];
518 $params = ['order' => ['id'], 'limit' => 10000];
519 $items = DBA::select('item', ['id'], $condition, $params);
521 if (DBA::errorNo() != 0) {
522 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
526 while ($item = DBA::fetch($items)) {
529 UserItem::setNotification($item['id']);
535 DI::config()->set('system', 'post_update_version_1329_id', $id);
537 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
539 if ($start_id == $id) {
540 DI::config()->set('system', 'post_update_version', 1329);
541 Logger::info('Done');
549 * Fill the "tag" table with tags and mentions from the body
551 * @return bool "true" when the job is done
552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
554 private static function update1341()
556 // Was the script completed?
557 if (DI::config()->get('system', 'post_update_version') >= 1341) {
561 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
563 Logger::info('Start', ['item' => $id]);
567 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
568 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
569 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
571 if (DBA::errorNo() != 0) {
572 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
576 while ($item = DBA::fetch($items)) {
577 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
578 $id = $item['uri-id'];
580 if ($rows % 1000 == 0) {
581 DI::config()->set('system', 'post_update_version_1341_id', $id);
586 DI::config()->set('system', 'post_update_version_1341_id', $id);
588 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
590 // When there are less than 1,000 items processed this means that we reached the end
591 // The other entries will then be processed with the regular functionality
593 DI::config()->set('system', 'post_update_version', 1341);
594 Logger::info('Done');
602 * Fill the "tag" table with tags and mentions from the "term" table
604 * @return bool "true" when the job is done
605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
607 private static function update1342()
609 // Was the script completed?
610 if (DI::config()->get('system', 'post_update_version') >= 1342) {
614 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
616 Logger::info('Start', ['item' => $id]);
620 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
622 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
623 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
624 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
625 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
627 if (DBA::errorNo() != 0) {
628 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
632 while ($term = DBA::fetch($terms)) {
633 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
634 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
635 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
636 if (!DBA::isResult($contact)) {
637 $ssl_url = str_replace('http://', 'https://', $term['url']);
638 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
639 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
642 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
643 $term['type'] = Tag::IMPLICIT_MENTION;
647 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
651 if ($rows % 1000 == 0) {
652 DI::config()->set('system', 'post_update_version_1342_id', $id);
657 DI::config()->set('system', 'post_update_version_1342_id', $id);
659 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
661 // When there are less than 1,000 items processed this means that we reached the end
662 // The other entries will then be processed with the regular functionality
664 DI::config()->set('system', 'post_update_version', 1342);
665 Logger::info('Done');
673 * Fill the "post-delivery-data" table with data from the "item-delivery-data" table
675 * @return bool "true" when the job is done
676 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 private static function update1345()
680 // Was the script completed?
681 if (DI::config()->get('system', 'post_update_version') >= 1345) {
685 $id = DI::config()->get('system', 'post_update_version_1345_id', 0);
687 Logger::info('Start', ['item' => $id]);
691 $deliveries = DBA::p("SELECT `uri-id`, `iid`, `item-delivery-data`.`postopts`, `item-delivery-data`.`inform`,
692 `queue_count`, `queue_done`, `activitypub`, `dfrn`, `diaspora`, `ostatus`, `legacy_dfrn`, `queue_failed`
693 FROM `item-delivery-data`
694 INNER JOIN `item` ON `item`.`id` = `item-delivery-data`.`iid`
695 WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
697 if (DBA::errorNo() != 0) {
698 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
702 while ($delivery = DBA::fetch($deliveries)) {
703 $id = $delivery['iid'];
704 unset($delivery['iid']);
705 DBA::insert('post-delivery-data', $delivery);
708 DBA::close($deliveries);
710 DI::config()->set('system', 'post_update_version_1345_id', $id);
712 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
714 // When there are less than 100 items processed this means that we reached the end
715 // The other entries will then be processed with the regular functionality
717 DI::config()->set('system', 'post_update_version', 1345);
718 Logger::info('Done');