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()) {
80 * Updates the "global" field in the item table
82 * @return bool "true" when the job is done
83 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
85 private static function update1194()
87 // Was the script completed?
88 if (DI::config()->get("system", "post_update_version") >= 1194) {
92 Logger::log("Start", Logger::DEBUG);
94 $end_id = DI::config()->get("system", "post_update_1194_end");
96 $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
98 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
99 $end_id = DI::config()->get("system", "post_update_1194_end");
103 Logger::log("End ID: ".$end_id, Logger::DEBUG);
105 $start_id = DI::config()->get("system", "post_update_1194_start");
107 $query1 = "SELECT `item`.`id` FROM `item` ";
109 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
111 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
112 AND `item`.`visible` AND NOT `item`.`private`
113 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
114 AND `item`.`network` IN ('%s', '%s', '%s', '')
115 AND NOT `item`.`global`";
117 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1",
118 intval($start_id), intval($end_id),
119 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
121 DI::config()->set("system", "post_update_version", 1194);
122 Logger::log("Update is done", Logger::DEBUG);
125 DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
126 $start_id = DI::config()->get("system", "post_update_1194_start");
129 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
131 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1",
132 intval($start_id), intval($end_id),
133 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
135 $pos_id = $r[0]["id"];
139 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
141 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
142 intval($start_id), intval($pos_id),
143 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
145 Logger::log("Done", Logger::DEBUG);
149 * update the "last-item" field in the "self" contact
151 * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
153 * @return bool "true" when the job is done
154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
156 private static function update1206()
158 // Was the script completed?
159 if (DI::config()->get("system", "post_update_version") >= 1206) {
163 Logger::log("Start", Logger::DEBUG);
164 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
165 (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
167 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
169 if (!DBA::isResult($r)) {
172 foreach ($r as $user) {
173 if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
174 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
178 DI::config()->set("system", "post_update_version", 1206);
179 Logger::log("Done", Logger::DEBUG);
184 * update the item related tables
186 * @return bool "true" when the job is done
187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
188 * @throws \ImagickException
190 private static function update1279()
192 // Was the script completed?
193 if (DI::config()->get("system", "post_update_version") >= 1279) {
197 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
199 Logger::log("Start from item " . $id, Logger::DEBUG);
201 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
202 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
203 'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
204 'inform', 'postopts', 'icid']);
208 $condition = ["`id` > ?", $id];
209 $params = ['order' => ['id'], 'limit' => 10000];
210 $items = Item::select($fields, $condition, $params);
212 if (DBA::errorNo() != 0) {
213 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
217 while ($item = Item::fetch($items)) {
220 if (empty($item['author-id'])) {
221 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
222 'photo' => $item['author-avatar'], 'network' => $item['network']];
224 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
227 if (empty($item['owner-id'])) {
228 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
229 'photo' => $item['owner-avatar'], 'network' => $item['network']];
231 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
234 if (empty($item['psid'])) {
235 $item['psid'] = PermissionSet::getIdFromACL(
244 $item['allow_cid'] = null;
245 $item['allow_gid'] = null;
246 $item['deny_cid'] = null;
247 $item['deny_gid'] = null;
249 if ($item['post-type'] == 0) {
250 if (!empty($item['type']) && ($item['type'] == 'note')) {
251 $item['post-type'] = Item::PT_PERSONAL_NOTE;
252 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
253 $item['post-type'] = Item::PT_IMAGE;
254 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
255 $item['post-type'] = Item::PT_PAGE;
259 self::createLanguage($item);
261 if (!empty($item['icid']) && !empty($item['language'])) {
262 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
264 unset($item['language']);
266 Item::update($item, ['id' => $id]);
272 DI::config()->set("system", "post_update_version_1279_id", $id);
274 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
276 if ($start_id == $id) {
277 // Set all deprecated fields to "null" if they contain an empty string
278 $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
279 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
280 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
281 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
282 'rendered-hash', 'rendered-html'];
283 foreach ($nullfields as $field) {
284 $fields = [$field => null];
285 $condition = [$field => ''];
286 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
287 // Important: This has to be a "DBA::update", not a "Item::update"
288 DBA::update('item', $fields, $condition);
291 DI::config()->set("system", "post_update_version", 1279);
292 Logger::log("Done", Logger::DEBUG);
299 private static function createLanguage(&$item)
301 if (empty($item['postopts'])) {
305 $opts = explode(',', $item['postopts']);
309 foreach ($opts as $opt) {
310 if (strstr($opt, 'lang=')) {
311 $language = substr($opt, 5);
317 if (empty($language)) {
321 if (!empty($postopts)) {
322 $item['postopts'] = implode(',', $postopts);
324 $item['postopts'] = null;
327 $lang_pairs = explode(':', $language);
331 foreach ($lang_pairs as $pair) {
332 $lang_pair_arr = explode(';', $pair);
333 if (count($lang_pair_arr) == 2) {
334 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
338 $item['language'] = json_encode($lang_arr);
342 * update item-uri data. Prerequisite for the next item structure update.
344 * @return bool "true" when the job is done
345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
347 private static function update1281()
349 // Was the script completed?
350 if (DI::config()->get("system", "post_update_version") >= 1281) {
354 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
356 Logger::log("Start from item " . $id, Logger::DEBUG);
358 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
362 $condition = ["`id` > ?", $id];
363 $params = ['order' => ['id'], 'limit' => 10000];
364 $items = DBA::select('item', $fields, $condition, $params);
366 if (DBA::errorNo() != 0) {
367 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
371 while ($item = DBA::fetch($items)) {
374 if (empty($item['uri'])) {
377 } elseif (empty($item['uri-id'])) {
378 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
381 if (empty($item['parent-uri'])) {
382 $item['parent-uri-id'] = $item['uri-id'];
383 } elseif (empty($item['parent-uri-id'])) {
384 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
387 // Very old items don't have this field
388 if (empty($item['thr-parent'])) {
389 $item['thr-parent-id'] = $item['parent-uri-id'];
390 } elseif (empty($item['thr-parent-id'])) {
391 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
395 unset($item['guid']);
397 unset($item['parent-uri']);
398 unset($item['thr-parent']);
400 DBA::update('item', $item, ['id' => $id]);
406 DI::config()->set("system", "post_update_version_1281_id", $id);
408 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
410 if ($start_id == $id) {
411 Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
412 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");
414 Logger::log("Updating item-uri in item-content", Logger::DEBUG);
415 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");
417 DI::config()->set("system", "post_update_version", 1281);
418 Logger::log("Done", Logger::DEBUG);
426 * Set the delivery queue count to a negative value for all items preceding the feature.
428 * @return bool "true" when the job is done
429 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
431 private static function update1297()
433 // Was the script completed?
434 if (DI::config()->get('system', 'post_update_version') >= 1297) {
438 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
439 $max_iid = $max_item_delivery_data['iid'];
441 Logger::info('Start update1297 with max iid: ' . $max_iid);
443 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
445 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
447 if (DBA::errorNo() != 0) {
448 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
452 Logger::info('Processed rows: ' . DBA::affectedRows());
454 DI::config()->set('system', 'post_update_version', 1297);
456 Logger::info('Done');
461 * Remove contact duplicates
463 * @return bool "true" when the job is done
464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
466 private static function update1322()
468 // Was the script completed?
469 if (DI::config()->get('system', 'post_update_version') >= 1322) {
473 Logger::info('Start');
475 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
476 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
477 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
478 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
479 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
480 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
482 while ($contact = DBA::fetch($contacts)) {
483 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
484 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
487 DBA::close($contact);
488 DI::config()->set('system', 'post_update_version', 1322);
490 Logger::info('Done');
496 * update user-item data with notifications
498 * @return bool "true" when the job is done
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 private static function update1329()
503 // Was the script completed?
504 if (DI::config()->get('system', 'post_update_version') >= 1329) {
508 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
510 Logger::info('Start', ['item' => $id]);
514 $condition = ["`id` > ?", $id];
515 $params = ['order' => ['id'], 'limit' => 10000];
516 $items = DBA::select('item', ['id'], $condition, $params);
518 if (DBA::errorNo() != 0) {
519 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
523 while ($item = DBA::fetch($items)) {
526 UserItem::setNotification($item['id']);
532 DI::config()->set('system', 'post_update_version_1329_id', $id);
534 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
536 if ($start_id == $id) {
537 DI::config()->set('system', 'post_update_version', 1329);
538 Logger::info('Done');
546 * Fill the "tag" table with tags and mentions from the body
548 * @return bool "true" when the job is done
549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
551 private static function update1341()
553 // Was the script completed?
554 if (DI::config()->get('system', 'post_update_version') >= 1341) {
558 $id = DI::config()->get('system', 'post_update_version_1341_id', 0);
560 Logger::info('Start', ['item' => $id]);
565 $items = DBA::p("SELECT `uri-id`,`body` FROM `item-content` WHERE
566 (`body` LIKE ? OR `body` LIKE ? OR `body` LIKE ?) AND `uri-id` >= ?
567 ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
569 if (DBA::errorNo() != 0) {
570 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
574 while ($item = DBA::fetch($items)) {
575 Tag::storeFromBody($item['uri-id'], $item['body'], '#!@', false);
576 $id = $item['uri-id'];
578 if ($rows % 1000 == 0) {
579 DI::config()->set('system', 'post_update_version_1341_id', $id);
584 DI::config()->set('system', 'post_update_version_1341_id', $id);
586 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
588 // When there are less than 1,000 items processed this means that we reached the end
589 // The other entries will then be processed with the regular functionality
591 DI::config()->set('system', 'post_update_version', 1341);
592 Logger::info('Done');
600 * Fill the "tag" table with tags and mentions from the "term" table
602 * @return bool "true" when the job is done
603 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
605 private static function update1342()
607 // Was the script completed?
608 if (DI::config()->get('system', 'post_update_version') >= 1342) {
612 $id = DI::config()->get('system', 'post_update_version_1342_id', 0);
614 Logger::info('Start', ['item' => $id]);
619 $terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
621 INNER JOIN `item` ON `item`.`id` = `term`.`oid`
622 INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
623 WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
624 Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id);
626 if (DBA::errorNo() != 0) {
627 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
631 while ($term = DBA::fetch($terms)) {
632 if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) {
633 $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false];
634 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
635 if (!DBA::isResult($contact)) {
636 $ssl_url = str_replace('http://', 'https://', $term['url']);
637 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0];
638 $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]);
641 if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) {
642 $term['type'] = Tag::IMPLICIT_MENTION;
646 Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url'], false);
650 if ($rows % 1000 == 0) {
651 DI::config()->set('system', 'post_update_version_1342_id', $id);
656 DI::config()->set('system', 'post_update_version_1342_id', $id);
658 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
660 // When there are less than 1,000 items processed this means that we reached the end
661 // The other entries will then be processed with the regular functionality
663 DI::config()->set('system', 'post_update_version', 1342);
664 Logger::info('Done');