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\UserItem;
34 * These database-intensive post update routines are meant to be executed in the background by the cronjob.
36 * If there is a need for a intensive migration after a database structure change, update this file
37 * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
42 * Calls the post update functions
44 public static function update()
46 if (!self::update1194()) {
49 if (!self::update1206()) {
52 if (!self::update1279()) {
55 if (!self::update1281()) {
58 if (!self::update1297()) {
61 if (!self::update1322()) {
64 if (!self::update1329()) {
72 * Updates the "global" field in the item table
74 * @return bool "true" when the job is done
75 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
77 private static function update1194()
79 // Was the script completed?
80 if (DI::config()->get("system", "post_update_version") >= 1194) {
84 Logger::log("Start", Logger::DEBUG);
86 $end_id = DI::config()->get("system", "post_update_1194_end");
88 $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
90 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
91 $end_id = DI::config()->get("system", "post_update_1194_end");
95 Logger::log("End ID: ".$end_id, Logger::DEBUG);
97 $start_id = DI::config()->get("system", "post_update_1194_start");
99 $query1 = "SELECT `item`.`id` FROM `item` ";
101 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
103 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
104 AND `item`.`visible` AND NOT `item`.`private`
105 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
106 AND `item`.`network` IN ('%s', '%s', '%s', '')
107 AND NOT `item`.`global`";
109 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1",
110 intval($start_id), intval($end_id),
111 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
113 DI::config()->set("system", "post_update_version", 1194);
114 Logger::log("Update is done", Logger::DEBUG);
117 DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
118 $start_id = DI::config()->get("system", "post_update_1194_start");
121 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
123 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1",
124 intval($start_id), intval($end_id),
125 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
127 $pos_id = $r[0]["id"];
131 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
133 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
134 intval($start_id), intval($pos_id),
135 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
137 Logger::log("Done", Logger::DEBUG);
141 * update the "last-item" field in the "self" contact
143 * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
145 * @return bool "true" when the job is done
146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
148 private static function update1206()
150 // Was the script completed?
151 if (DI::config()->get("system", "post_update_version") >= 1206) {
155 Logger::log("Start", Logger::DEBUG);
156 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
157 (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
159 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
161 if (!DBA::isResult($r)) {
164 foreach ($r as $user) {
165 if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
166 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
170 DI::config()->set("system", "post_update_version", 1206);
171 Logger::log("Done", Logger::DEBUG);
176 * update the item related tables
178 * @return bool "true" when the job is done
179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
180 * @throws \ImagickException
182 private static function update1279()
184 // Was the script completed?
185 if (DI::config()->get("system", "post_update_version") >= 1279) {
189 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
191 Logger::log("Start from item " . $id, Logger::DEBUG);
193 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
194 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
195 'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
196 'inform', 'postopts', 'icid']);
200 $condition = ["`id` > ?", $id];
201 $params = ['order' => ['id'], 'limit' => 10000];
202 $items = Item::select($fields, $condition, $params);
204 if (DBA::errorNo() != 0) {
205 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
209 while ($item = Item::fetch($items)) {
212 if (empty($item['author-id'])) {
213 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
214 'photo' => $item['author-avatar'], 'network' => $item['network']];
216 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
219 if (empty($item['owner-id'])) {
220 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
221 'photo' => $item['owner-avatar'], 'network' => $item['network']];
223 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
226 if (empty($item['psid'])) {
227 $item['psid'] = PermissionSet::getIdFromACL(
236 $item['allow_cid'] = null;
237 $item['allow_gid'] = null;
238 $item['deny_cid'] = null;
239 $item['deny_gid'] = null;
241 if ($item['post-type'] == 0) {
242 if (!empty($item['type']) && ($item['type'] == 'note')) {
243 $item['post-type'] = Item::PT_PERSONAL_NOTE;
244 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
245 $item['post-type'] = Item::PT_IMAGE;
246 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
247 $item['post-type'] = Item::PT_PAGE;
251 self::createLanguage($item);
253 if (!empty($item['icid']) && !empty($item['language'])) {
254 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
256 unset($item['language']);
258 Item::update($item, ['id' => $id]);
264 DI::config()->set("system", "post_update_version_1279_id", $id);
266 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
268 if ($start_id == $id) {
269 // Set all deprecated fields to "null" if they contain an empty string
270 $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
271 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
272 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
273 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
274 'rendered-hash', 'rendered-html'];
275 foreach ($nullfields as $field) {
276 $fields = [$field => null];
277 $condition = [$field => ''];
278 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
279 // Important: This has to be a "DBA::update", not a "Item::update"
280 DBA::update('item', $fields, $condition);
283 DI::config()->set("system", "post_update_version", 1279);
284 Logger::log("Done", Logger::DEBUG);
291 private static function createLanguage(&$item)
293 if (empty($item['postopts'])) {
297 $opts = explode(',', $item['postopts']);
301 foreach ($opts as $opt) {
302 if (strstr($opt, 'lang=')) {
303 $language = substr($opt, 5);
309 if (empty($language)) {
313 if (!empty($postopts)) {
314 $item['postopts'] = implode(',', $postopts);
316 $item['postopts'] = null;
319 $lang_pairs = explode(':', $language);
323 foreach ($lang_pairs as $pair) {
324 $lang_pair_arr = explode(';', $pair);
325 if (count($lang_pair_arr) == 2) {
326 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
330 $item['language'] = json_encode($lang_arr);
334 * update item-uri data. Prerequisite for the next item structure update.
336 * @return bool "true" when the job is done
337 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
339 private static function update1281()
341 // Was the script completed?
342 if (DI::config()->get("system", "post_update_version") >= 1281) {
346 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
348 Logger::log("Start from item " . $id, Logger::DEBUG);
350 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
354 $condition = ["`id` > ?", $id];
355 $params = ['order' => ['id'], 'limit' => 10000];
356 $items = DBA::select('item', $fields, $condition, $params);
358 if (DBA::errorNo() != 0) {
359 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
363 while ($item = DBA::fetch($items)) {
366 if (empty($item['uri'])) {
369 } elseif (empty($item['uri-id'])) {
370 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
373 if (empty($item['parent-uri'])) {
374 $item['parent-uri-id'] = $item['uri-id'];
375 } elseif (empty($item['parent-uri-id'])) {
376 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
379 // Very old items don't have this field
380 if (empty($item['thr-parent'])) {
381 $item['thr-parent-id'] = $item['parent-uri-id'];
382 } elseif (empty($item['thr-parent-id'])) {
383 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
387 unset($item['guid']);
389 unset($item['parent-uri']);
390 unset($item['thr-parent']);
392 DBA::update('item', $item, ['id' => $id]);
398 DI::config()->set("system", "post_update_version_1281_id", $id);
400 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
402 if ($start_id == $id) {
403 Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
404 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");
406 Logger::log("Updating item-uri in item-content", Logger::DEBUG);
407 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");
409 DI::config()->set("system", "post_update_version", 1281);
410 Logger::log("Done", Logger::DEBUG);
418 * Set the delivery queue count to a negative value for all items preceding the feature.
420 * @return bool "true" when the job is done
421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
423 private static function update1297()
425 // Was the script completed?
426 if (DI::config()->get('system', 'post_update_version') >= 1297) {
430 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
431 $max_iid = $max_item_delivery_data['iid'];
433 Logger::info('Start update1297 with max iid: ' . $max_iid);
435 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
437 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
439 if (DBA::errorNo() != 0) {
440 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
444 Logger::info('Processed rows: ' . DBA::affectedRows());
446 DI::config()->set('system', 'post_update_version', 1297);
448 Logger::info('Done');
453 * Remove contact duplicates
455 * @return bool "true" when the job is done
456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 private static function update1322()
460 // Was the script completed?
461 if (DI::config()->get('system', 'post_update_version') >= 1322) {
465 Logger::info('Start');
467 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
468 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
469 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
470 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
471 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
472 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
474 while ($contact = DBA::fetch($contacts)) {
475 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
476 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
479 DBA::close($contact);
480 DI::config()->set('system', 'post_update_version', 1322);
482 Logger::info('Done');
488 * update user-item data with notifications
490 * @return bool "true" when the job is done
491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 private static function update1329()
495 // Was the script completed?
496 if (DI::config()->get('system', 'post_update_version') >= 1329) {
500 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
502 Logger::info('Start', ['item' => $id]);
506 $condition = ["`id` > ?", $id];
507 $params = ['order' => ['id'], 'limit' => 10000];
508 $items = DBA::select('item', ['id'], $condition, $params);
510 if (DBA::errorNo() != 0) {
511 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
515 while ($item = DBA::fetch($items)) {
518 UserItem::setNotification($item['id']);
524 DI::config()->set('system', 'post_update_version_1329_id', $id);
526 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
528 if ($start_id == $id) {
529 DI::config()->set('system', 'post_update_version', 1329);
530 Logger::info('Done');