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\Post\Category;
32 use Friendica\Model\Tag;
33 use Friendica\Model\Term;
34 use Friendica\Model\UserItem;
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.
46 * Calls the post update functions
48 public static function update()
50 if (!self::update1194()) {
53 if (!self::update1206()) {
56 if (!self::update1279()) {
59 if (!self::update1281()) {
62 if (!self::update1297()) {
65 if (!self::update1322()) {
68 if (!self::update1329()) {
71 if (!self::update1341()) {
74 if (!self::update1342()) {
77 if (!self::update1346()) {
85 * Updates the "global" field in the item table
87 * @return bool "true" when the job is done
88 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
90 private static function update1194()
92 // Was the script completed?
93 if (DI::config()->get("system", "post_update_version") >= 1194) {
97 Logger::log("Start", Logger::DEBUG);
99 $end_id = DI::config()->get("system", "post_update_1194_end");
101 $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
103 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
104 $end_id = DI::config()->get("system", "post_update_1194_end");
108 Logger::log("End ID: ".$end_id, Logger::DEBUG);
110 $start_id = DI::config()->get("system", "post_update_1194_start");
112 $query1 = "SELECT `item`.`id` FROM `item` ";
114 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
116 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
117 AND `item`.`visible` AND NOT `item`.`private`
118 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
119 AND `item`.`network` IN ('%s', '%s', '%s', '')
120 AND NOT `item`.`global`";
122 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1",
123 intval($start_id), intval($end_id),
124 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
126 DI::config()->set("system", "post_update_version", 1194);
127 Logger::log("Update is done", Logger::DEBUG);
130 DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
131 $start_id = DI::config()->get("system", "post_update_1194_start");
134 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
136 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1",
137 intval($start_id), intval($end_id),
138 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
140 $pos_id = $r[0]["id"];
144 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
146 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
147 intval($start_id), intval($pos_id),
148 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
150 Logger::log("Done", Logger::DEBUG);
154 * update the "last-item" field in the "self" contact
156 * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
158 * @return bool "true" when the job is done
159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
161 private static function update1206()
163 // Was the script completed?
164 if (DI::config()->get("system", "post_update_version") >= 1206) {
168 Logger::log("Start", Logger::DEBUG);
169 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
170 (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
172 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
174 if (!DBA::isResult($r)) {
177 foreach ($r as $user) {
178 if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
179 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
183 DI::config()->set("system", "post_update_version", 1206);
184 Logger::log("Done", Logger::DEBUG);
189 * update the item related tables
191 * @return bool "true" when the job is done
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 * @throws \ImagickException
195 private static function update1279()
197 // Was the script completed?
198 if (DI::config()->get("system", "post_update_version") >= 1279) {
202 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
204 Logger::log("Start from item " . $id, Logger::DEBUG);
206 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
207 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
208 'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
209 'inform', 'postopts', 'icid']);
213 $condition = ["`id` > ?", $id];
214 $params = ['order' => ['id'], 'limit' => 10000];
215 $items = Item::select($fields, $condition, $params);
217 if (DBA::errorNo() != 0) {
218 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
222 while ($item = Item::fetch($items)) {
225 if (empty($item['author-id'])) {
226 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
227 'photo' => $item['author-avatar'], 'network' => $item['network']];
229 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
232 if (empty($item['owner-id'])) {
233 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
234 'photo' => $item['owner-avatar'], 'network' => $item['network']];
236 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
239 if (empty($item['psid'])) {
240 $item['psid'] = PermissionSet::getIdFromACL(
249 $item['allow_cid'] = null;
250 $item['allow_gid'] = null;
251 $item['deny_cid'] = null;
252 $item['deny_gid'] = null;
254 if ($item['post-type'] == 0) {
255 if (!empty($item['type']) && ($item['type'] == 'note')) {
256 $item['post-type'] = Item::PT_PERSONAL_NOTE;
257 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
258 $item['post-type'] = Item::PT_IMAGE;
259 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
260 $item['post-type'] = Item::PT_PAGE;
264 self::createLanguage($item);
266 if (!empty($item['icid']) && !empty($item['language'])) {
267 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
269 unset($item['language']);
271 Item::update($item, ['id' => $id]);
277 DI::config()->set("system", "post_update_version_1279_id", $id);
279 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
281 if ($start_id == $id) {
282 // Set all deprecated fields to "null" if they contain an empty string
283 $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
284 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
285 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
286 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
287 'rendered-hash', 'rendered-html'];
288 foreach ($nullfields as $field) {
289 $fields = [$field => null];
290 $condition = [$field => ''];
291 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
292 // Important: This has to be a "DBA::update", not a "Item::update"
293 DBA::update('item', $fields, $condition);
296 DI::config()->set("system", "post_update_version", 1279);
297 Logger::log("Done", Logger::DEBUG);
304 private static function createLanguage(&$item)
306 if (empty($item['postopts'])) {
310 $opts = explode(',', $item['postopts']);
314 foreach ($opts as $opt) {
315 if (strstr($opt, 'lang=')) {
316 $language = substr($opt, 5);
322 if (empty($language)) {
326 if (!empty($postopts)) {
327 $item['postopts'] = implode(',', $postopts);
329 $item['postopts'] = null;
332 $lang_pairs = explode(':', $language);
336 foreach ($lang_pairs as $pair) {
337 $lang_pair_arr = explode(';', $pair);
338 if (count($lang_pair_arr) == 2) {
339 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
343 $item['language'] = json_encode($lang_arr);
347 * update item-uri data. Prerequisite for the next item structure update.
349 * @return bool "true" when the job is done
350 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
352 private static function update1281()
354 // Was the script completed?
355 if (DI::config()->get("system", "post_update_version") >= 1281) {
359 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
361 Logger::log("Start from item " . $id, Logger::DEBUG);
363 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
367 $condition = ["`id` > ?", $id];
368 $params = ['order' => ['id'], 'limit' => 10000];
369 $items = DBA::select('item', $fields, $condition, $params);
371 if (DBA::errorNo() != 0) {
372 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
376 while ($item = DBA::fetch($items)) {
379 if (empty($item['uri'])) {
382 } elseif (empty($item['uri-id'])) {
383 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
386 if (empty($item['parent-uri'])) {
387 $item['parent-uri-id'] = $item['uri-id'];
388 } elseif (empty($item['parent-uri-id'])) {
389 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
392 // Very old items don't have this field
393 if (empty($item['thr-parent'])) {
394 $item['thr-parent-id'] = $item['parent-uri-id'];
395 } elseif (empty($item['thr-parent-id'])) {
396 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
400 unset($item['guid']);
402 unset($item['parent-uri']);
403 unset($item['thr-parent']);
405 DBA::update('item', $item, ['id' => $id]);
411 DI::config()->set("system", "post_update_version_1281_id", $id);
413 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
415 if ($start_id == $id) {
416 Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
417 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");
419 Logger::log("Updating item-uri in item-content", Logger::DEBUG);
420 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");
422 DI::config()->set("system", "post_update_version", 1281);
423 Logger::log("Done", Logger::DEBUG);
431 * Set the delivery queue count to a negative value for all items preceding the feature.
433 * @return bool "true" when the job is done
434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
436 private static function update1297()
438 // Was the script completed?
439 if (DI::config()->get('system', 'post_update_version') >= 1297) {
443 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
444 $max_iid = $max_item_delivery_data['iid'];
446 Logger::info('Start update1297 with max iid: ' . $max_iid);
448 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
450 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
452 if (DBA::errorNo() != 0) {
453 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
457 Logger::info('Processed rows: ' . DBA::affectedRows());
459 DI::config()->set('system', 'post_update_version', 1297);
461 Logger::info('Done');
466 * Remove contact duplicates
468 * @return bool "true" when the job is done
469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
471 private static function update1322()
473 // Was the script completed?
474 if (DI::config()->get('system', 'post_update_version') >= 1322) {
478 Logger::info('Start');
480 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
481 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
482 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
483 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
484 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
485 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
487 while ($contact = DBA::fetch($contacts)) {
488 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
489 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
492 DBA::close($contact);
493 DI::config()->set('system', 'post_update_version', 1322);
495 Logger::info('Done');
501 * update user-item data with notifications
503 * @return bool "true" when the job is done
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 private static function update1329()
508 // Was the script completed?
509 if (DI::config()->get('system', 'post_update_version') >= 1329) {
513 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
515 Logger::info('Start', ['item' => $id]);
519 $condition = ["`id` > ?", $id];
520 $params = ['order' => ['id'], 'limit' => 10000];
521 $items = DBA::select('item', ['id'], $condition, $params);
523 if (DBA::errorNo() != 0) {
524 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
528 while ($item = DBA::fetch($items)) {
531 UserItem::setNotification($item['id']);
537 DI::config()->set('system', 'post_update_version_1329_id', $id);
539 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
541 if ($start_id == $id) {
542 DI::config()->set('system', 'post_update_version', 1329);
543 Logger::info('Done');
551 * Fill the "tag" table with tags and mentions from the body
553 * @return bool "true" when the job is done
554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556 private static function update1341()
558 // Was the script completed?
559 if (DI::config()->get('system', 'post_update_version') >= 1341) {
563 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
565 Logger::info('Start', ['item' => $id]);
570 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
571 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
572 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
574 if (DBA::errorNo() != 0) {
575 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
579 while ($item = DBA::fetch($items)) {
580 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
581 $id = $item['uri-id'];
583 if ($rows % 1000 == 0) {
584 DI::config()->set('system', 'post_update_version_1341_id', $id);
589 DI::config()->set('system', 'post_update_version_1341_id', $id);
591 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
593 // When there are less than 1,000 items processed this means that we reached the end
594 // The other entries will then be processed with the regular functionality
596 DI::config()->set('system', 'post_update_version', 1341);
597 Logger::info('Done');
605 * Fill the "tag" table with tags and mentions from the "term" table
607 * @return bool "true" when the job is done
608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
610 private static function update1342()
612 // Was the script completed?
613 if (DI::config()->get('system', 'post_update_version') >= 1342) {
617 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
619 Logger::info('Start', ['item' => $id]);
624 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
626 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
627 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
628 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
629 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
631 if (DBA::errorNo() != 0) {
632 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
636 while ($term = DBA::fetch($terms)) {
637 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
638 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
639 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
640 if (!DBA::isResult($contact)) {
641 $ssl_url = str_replace('http://', 'https://', $term['url']);
642 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
643 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
646 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
647 $term['type'] = Tag::IMPLICIT_MENTION;
651 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
655 if ($rows % 1000 == 0) {
656 DI::config()->set('system', 'post_update_version_1342_id', $id);
661 DI::config()->set('system', 'post_update_version_1342_id', $id);
663 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
665 // When there are less than 1,000 items processed this means that we reached the end
666 // The other entries will then be processed with the regular functionality
668 DI::config()->set('system', 'post_update_version', 1342);
669 Logger::info('Done');
677 * Fill the "tag" table with tags and mentions from the "term" table
679 * @return bool "true" when the job is done
680 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
682 private static function update1346()
684 // Was the script completed?
685 if (DI::config()->get('system', 'post_update_version') >= 1346) {
689 $id = DI::config()->get('system', 'post_update_version_1346_id', 0);
691 Logger::info('Start', ['item' => $id]);
695 $terms = DBA::select('term', ['oid'],
696 ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
697 ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]);
699 if (DBA::errorNo() != 0) {
700 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
704 while ($term = DBA::fetch($terms)) {
705 $item = Item::selectFirst(['uri-id', 'uid'], ['id' => $term['oid']]);
706 if (!DBA::isResult($item)) {
710 $file = Term::fileTextFromItemId($term['oid']);
712 Category::storeTextByURIId($item['uri-id'], $item['uid'], $file);
717 if ($rows % 100 == 0) {
718 DI::config()->set('system', 'post_update_version_1346_id', $id);
723 DI::config()->set('system', 'post_update_version_1346_id', $id);
725 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
727 // When there are less than 10 items processed this means that we reached the end
728 // The other entries will then be processed with the regular functionality
730 DI::config()->set('system', 'post_update_version', 1346);
731 Logger::info('Done');