3 * @file src/Database/PostUpdate.php
5 namespace Friendica\Database;
7 use Friendica\Core\Logger;
8 use Friendica\Core\Protocol;
10 use Friendica\Model\Contact;
11 use Friendica\Model\Item;
12 use Friendica\Model\ItemURI;
13 use Friendica\Model\PermissionSet;
14 use Friendica\Model\UserItem;
17 * These database-intensive post update routines are meant to be executed in the background by the cronjob.
19 * If there is a need for a intensive migration after a database structure change, update this file
20 * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
25 * Calls the post update functions
27 public static function update()
29 if (!self::update1194()) {
32 if (!self::update1206()) {
35 if (!self::update1279()) {
38 if (!self::update1281()) {
41 if (!self::update1297()) {
44 if (!self::update1322()) {
47 if (!self::update1329()) {
55 * Updates the "global" field in the item table
57 * @return bool "true" when the job is done
58 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
60 private static function update1194()
62 // Was the script completed?
63 if (DI::config()->get("system", "post_update_version") >= 1194) {
67 Logger::log("Start", Logger::DEBUG);
69 $end_id = DI::config()->get("system", "post_update_1194_end");
71 $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
73 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
74 $end_id = DI::config()->get("system", "post_update_1194_end");
78 Logger::log("End ID: ".$end_id, Logger::DEBUG);
80 $start_id = DI::config()->get("system", "post_update_1194_start");
82 $query1 = "SELECT `item`.`id` FROM `item` ";
84 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
86 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
87 AND `item`.`visible` AND NOT `item`.`private`
88 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
89 AND `item`.`network` IN ('%s', '%s', '%s', '')
90 AND NOT `item`.`global`";
92 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1",
93 intval($start_id), intval($end_id),
94 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
96 DI::config()->set("system", "post_update_version", 1194);
97 Logger::log("Update is done", Logger::DEBUG);
100 DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
101 $start_id = DI::config()->get("system", "post_update_1194_start");
104 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
106 $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1",
107 intval($start_id), intval($end_id),
108 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
110 $pos_id = $r[0]["id"];
114 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
116 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
117 intval($start_id), intval($pos_id),
118 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
120 Logger::log("Done", Logger::DEBUG);
124 * update the "last-item" field in the "self" contact
126 * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
128 * @return bool "true" when the job is done
129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
131 private static function update1206()
133 // Was the script completed?
134 if (DI::config()->get("system", "post_update_version") >= 1206) {
138 Logger::log("Start", Logger::DEBUG);
139 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
140 (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
142 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
144 if (!DBA::isResult($r)) {
147 foreach ($r as $user) {
148 if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
149 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
153 DI::config()->set("system", "post_update_version", 1206);
154 Logger::log("Done", Logger::DEBUG);
159 * update the item related tables
161 * @return bool "true" when the job is done
162 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
163 * @throws \ImagickException
165 private static function update1279()
167 // Was the script completed?
168 if (DI::config()->get("system", "post_update_version") >= 1279) {
172 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
174 Logger::log("Start from item " . $id, Logger::DEBUG);
176 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
177 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
178 'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
179 'inform', 'postopts', 'icid']);
183 $condition = ["`id` > ?", $id];
184 $params = ['order' => ['id'], 'limit' => 10000];
185 $items = Item::select($fields, $condition, $params);
187 if (DBA::errorNo() != 0) {
188 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
192 while ($item = Item::fetch($items)) {
195 if (empty($item['author-id'])) {
196 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
197 'photo' => $item['author-avatar'], 'network' => $item['network']];
199 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
202 if (empty($item['owner-id'])) {
203 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
204 'photo' => $item['owner-avatar'], 'network' => $item['network']];
206 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
209 if (empty($item['psid'])) {
210 $item['psid'] = PermissionSet::getIdFromACL(
219 $item['allow_cid'] = null;
220 $item['allow_gid'] = null;
221 $item['deny_cid'] = null;
222 $item['deny_gid'] = null;
224 if ($item['post-type'] == 0) {
225 if (!empty($item['type']) && ($item['type'] == 'note')) {
226 $item['post-type'] = Item::PT_PERSONAL_NOTE;
227 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
228 $item['post-type'] = Item::PT_IMAGE;
229 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
230 $item['post-type'] = Item::PT_PAGE;
234 self::createLanguage($item);
236 if (!empty($item['icid']) && !empty($item['language'])) {
237 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
239 unset($item['language']);
241 Item::update($item, ['id' => $id]);
247 DI::config()->set("system", "post_update_version_1279_id", $id);
249 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
251 if ($start_id == $id) {
252 // Set all deprecated fields to "null" if they contain an empty string
253 $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
254 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
255 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
256 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
257 'rendered-hash', 'rendered-html'];
258 foreach ($nullfields as $field) {
259 $fields = [$field => null];
260 $condition = [$field => ''];
261 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
262 // Important: This has to be a "DBA::update", not a "Item::update"
263 DBA::update('item', $fields, $condition);
266 DI::config()->set("system", "post_update_version", 1279);
267 Logger::log("Done", Logger::DEBUG);
274 private static function createLanguage(&$item)
276 if (empty($item['postopts'])) {
280 $opts = explode(',', $item['postopts']);
284 foreach ($opts as $opt) {
285 if (strstr($opt, 'lang=')) {
286 $language = substr($opt, 5);
292 if (empty($language)) {
296 if (!empty($postopts)) {
297 $item['postopts'] = implode(',', $postopts);
299 $item['postopts'] = null;
302 $lang_pairs = explode(':', $language);
306 foreach ($lang_pairs as $pair) {
307 $lang_pair_arr = explode(';', $pair);
308 if (count($lang_pair_arr) == 2) {
309 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
313 $item['language'] = json_encode($lang_arr);
317 * update item-uri data. Prerequisite for the next item structure update.
319 * @return bool "true" when the job is done
320 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
322 private static function update1281()
324 // Was the script completed?
325 if (DI::config()->get("system", "post_update_version") >= 1281) {
329 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
331 Logger::log("Start from item " . $id, Logger::DEBUG);
333 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
337 $condition = ["`id` > ?", $id];
338 $params = ['order' => ['id'], 'limit' => 10000];
339 $items = DBA::select('item', $fields, $condition, $params);
341 if (DBA::errorNo() != 0) {
342 Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
346 while ($item = DBA::fetch($items)) {
349 if (empty($item['uri'])) {
352 } elseif (empty($item['uri-id'])) {
353 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
356 if (empty($item['parent-uri'])) {
357 $item['parent-uri-id'] = $item['uri-id'];
358 } elseif (empty($item['parent-uri-id'])) {
359 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
362 // Very old items don't have this field
363 if (empty($item['thr-parent'])) {
364 $item['thr-parent-id'] = $item['parent-uri-id'];
365 } elseif (empty($item['thr-parent-id'])) {
366 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
370 unset($item['guid']);
372 unset($item['parent-uri']);
373 unset($item['thr-parent']);
375 DBA::update('item', $item, ['id' => $id]);
381 DI::config()->set("system", "post_update_version_1281_id", $id);
383 Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
385 if ($start_id == $id) {
386 Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
387 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");
389 Logger::log("Updating item-uri in item-content", Logger::DEBUG);
390 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");
392 DI::config()->set("system", "post_update_version", 1281);
393 Logger::log("Done", Logger::DEBUG);
401 * Set the delivery queue count to a negative value for all items preceding the feature.
403 * @return bool "true" when the job is done
404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 private static function update1297()
408 // Was the script completed?
409 if (DI::config()->get('system', 'post_update_version') >= 1297) {
413 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
414 $max_iid = $max_item_delivery_data['iid'];
416 Logger::info('Start update1297 with max iid: ' . $max_iid);
418 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
420 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
422 if (DBA::errorNo() != 0) {
423 Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
427 Logger::info('Processed rows: ' . DBA::affectedRows());
429 DI::config()->set('system', 'post_update_version', 1297);
431 Logger::info('Done');
436 * Remove contact duplicates
438 * @return bool "true" when the job is done
439 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
441 private static function update1322()
443 // Was the script completed?
444 if (DI::config()->get('system', 'post_update_version') >= 1322) {
448 Logger::info('Start');
450 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
451 WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
452 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
453 AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
454 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
455 Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
457 while ($contact = DBA::fetch($contacts)) {
458 Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
459 Contact::removeDuplicates($contact['nurl'], $contact['uid']);
462 DBA::close($contact);
463 DI::config()->set('system', 'post_update_version', 1322);
465 Logger::info('Done');
471 * update user-item data with notifications
473 * @return bool "true" when the job is done
474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
476 private static function update1329()
478 // Was the script completed?
479 if (DI::config()->get('system', 'post_update_version') >= 1329) {
483 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
485 Logger::info('Start', ['item' => $id]);
489 $condition = ["`id` > ?", $id];
490 $params = ['order' => ['id'], 'limit' => 10000];
491 $items = DBA::select('item', ['id'], $condition, $params);
493 if (DBA::errorNo() != 0) {
494 Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
498 while ($item = DBA::fetch($items)) {
501 UserItem::setNotification($item['id']);
507 DI::config()->set('system', 'post_update_version_1329_id', $id);
509 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
511 if ($start_id == $id) {
512 DI::config()->set('system', 'post_update_version', 1329);
513 Logger::info('Done');