]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
Remove unused dependency
[friendica.git] / src / Database / PostUpdate.php
1 <?php
2 /**
3  * @file src/Database/PostUpdate.php
4  */
5 namespace Friendica\Database;
6
7 use Friendica\Core\Logger;
8 use Friendica\Core\Protocol;
9 use Friendica\DI;
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;
15
16 /**
17  * These database-intensive post update routines are meant to be executed in the background by the cronjob.
18  *
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.
21  */
22 class PostUpdate
23 {
24         /**
25          * Calls the post update functions
26          */
27         public static function update()
28         {
29                 if (!self::update1194()) {
30                         return false;
31                 }
32                 if (!self::update1206()) {
33                         return false;
34                 }
35                 if (!self::update1279()) {
36                         return false;
37                 }
38                 if (!self::update1281()) {
39                         return false;
40                 }
41                 if (!self::update1297()) {
42                         return false;
43                 }
44                 if (!self::update1322()) {
45                         return false;
46                 }
47                 if (!self::update1329()) {
48                         return false;
49                 }
50
51                 return true;
52         }
53
54         /**
55          * Updates the "global" field in the item table
56          *
57          * @return bool "true" when the job is done
58          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59          */
60         private static function update1194()
61         {
62                 // Was the script completed?
63                 if (DI::config()->get("system", "post_update_version") >= 1194) {
64                         return true;
65                 }
66
67                 Logger::log("Start", Logger::DEBUG);
68
69                 $end_id = DI::config()->get("system", "post_update_1194_end");
70                 if (!$end_id) {
71                         $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
72                         if ($r) {
73                                 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
74                                 $end_id = DI::config()->get("system", "post_update_1194_end");
75                         }
76                 }
77
78                 Logger::log("End ID: ".$end_id, Logger::DEBUG);
79
80                 $start_id = DI::config()->get("system", "post_update_1194_start");
81
82                 $query1 = "SELECT `item`.`id` FROM `item` ";
83
84                 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
85
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`";
91
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));
95                 if (!$r) {
96                         DI::config()->set("system", "post_update_version", 1194);
97                         Logger::log("Update is done", Logger::DEBUG);
98                         return true;
99                 } else {
100                         DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
101                         $start_id = DI::config()->get("system", "post_update_1194_start");
102                 }
103
104                 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
105
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));
109                 if ($r) {
110                         $pos_id = $r[0]["id"];
111                 } else {
112                         $pos_id = $end_id;
113                 }
114                 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
115
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));
119
120                 Logger::log("Done", Logger::DEBUG);
121         }
122
123         /**
124          * update the "last-item" field in the "self" contact
125          *
126          * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
127          *
128          * @return bool "true" when the job is done
129          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
130          */
131         private static function update1206()
132         {
133                 // Was the script completed?
134                 if (DI::config()->get("system", "post_update_version") >= 1206) {
135                         return true;
136                 }
137
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`
141                         FROM `user`
142                         INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
143
144                 if (!DBA::isResult($r)) {
145                         return false;
146                 }
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']]);
150                         }
151                 }
152
153                 DI::config()->set("system", "post_update_version", 1206);
154                 Logger::log("Done", Logger::DEBUG);
155                 return true;
156         }
157
158         /**
159          * update the item related tables
160          *
161          * @return bool "true" when the job is done
162          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
163          * @throws \ImagickException
164          */
165         private static function update1279()
166         {
167                 // Was the script completed?
168                 if (DI::config()->get("system", "post_update_version") >= 1279) {
169                         return true;
170                 }
171
172                 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
173
174                 Logger::log("Start from item " . $id, Logger::DEBUG);
175
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']);
180
181                 $start_id = $id;
182                 $rows = 0;
183                 $condition = ["`id` > ?", $id];
184                 $params = ['order' => ['id'], 'limit' => 10000];
185                 $items = Item::select($fields, $condition, $params);
186
187                 if (DBA::errorNo() != 0) {
188                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
189                         return false;
190                 }
191
192                 while ($item = Item::fetch($items)) {
193                         $id = $item['id'];
194
195                         if (empty($item['author-id'])) {
196                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
197                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
198
199                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
200                         }
201
202                         if (empty($item['owner-id'])) {
203                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
204                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
205
206                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
207                         }
208
209                         if (empty($item['psid'])) {
210                                 $item['psid'] = PermissionSet::getIdFromACL(
211                                         $item['uid'],
212                                         $item['allow_cid'],
213                                         $item['allow_gid'],
214                                         $item['deny_cid'],
215                                         $item['deny_gid']
216                                 );
217                         }
218
219                         $item['allow_cid'] = null;
220                         $item['allow_gid'] = null;
221                         $item['deny_cid'] = null;
222                         $item['deny_gid'] = null;
223
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;
231                                 }
232                         }
233
234                         self::createLanguage($item);
235
236                         if (!empty($item['icid']) && !empty($item['language'])) {
237                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
238                         }
239                         unset($item['language']);
240
241                         Item::update($item, ['id' => $id]);
242
243                         ++$rows;
244                 }
245                 DBA::close($items);
246
247                 DI::config()->set("system", "post_update_version_1279_id", $id);
248
249                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
250
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);
264                         }
265
266                         DI::config()->set("system", "post_update_version", 1279);
267                         Logger::log("Done", Logger::DEBUG);
268                         return true;
269                 }
270
271                 return false;
272         }
273
274         private static function createLanguage(&$item)
275         {
276                 if (empty($item['postopts'])) {
277                         return;
278                 }
279
280                 $opts = explode(',', $item['postopts']);
281
282                 $postopts = [];
283
284                 foreach ($opts as $opt) {
285                         if (strstr($opt, 'lang=')) {
286                                 $language = substr($opt, 5);
287                         } else {
288                                 $postopts[] = $opt;
289                         }
290                 }
291
292                 if (empty($language)) {
293                         return;
294                 }
295
296                 if (!empty($postopts)) {
297                         $item['postopts'] = implode(',', $postopts);
298                 } else {
299                         $item['postopts'] = null;
300                 }
301
302                 $lang_pairs = explode(':', $language);
303
304                 $lang_arr = [];
305
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];
310                         }
311                 }
312
313                 $item['language'] = json_encode($lang_arr);
314         }
315
316         /**
317          * update item-uri data. Prerequisite for the next item structure update.
318          *
319          * @return bool "true" when the job is done
320          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321          */
322         private static function update1281()
323         {
324                 // Was the script completed?
325                 if (DI::config()->get("system", "post_update_version") >= 1281) {
326                         return true;
327                 }
328
329                 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
330
331                 Logger::log("Start from item " . $id, Logger::DEBUG);
332
333                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
334
335                 $start_id = $id;
336                 $rows = 0;
337                 $condition = ["`id` > ?", $id];
338                 $params = ['order' => ['id'], 'limit' => 10000];
339                 $items = DBA::select('item', $fields, $condition, $params);
340
341                 if (DBA::errorNo() != 0) {
342                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
343                         return false;
344                 }
345
346                 while ($item = DBA::fetch($items)) {
347                         $id = $item['id'];
348
349                         if (empty($item['uri'])) {
350                                 // Should not happen
351                                 continue;
352                         } elseif (empty($item['uri-id'])) {
353                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
354                         }
355
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']);
360                         }
361
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']);
367                         }
368
369                         unset($item['id']);
370                         unset($item['guid']);
371                         unset($item['uri']);
372                         unset($item['parent-uri']);
373                         unset($item['thr-parent']);
374
375                         DBA::update('item', $item, ['id' => $id]);
376
377                         ++$rows;
378                 }
379                 DBA::close($items);
380
381                 DI::config()->set("system", "post_update_version_1281_id", $id);
382
383                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
384
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");
388
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");
391
392                         DI::config()->set("system", "post_update_version", 1281);
393                         Logger::log("Done", Logger::DEBUG);
394                         return true;
395                 }
396
397                 return false;
398         }
399
400         /**
401          * Set the delivery queue count to a negative value for all items preceding the feature.
402          *
403          * @return bool "true" when the job is done
404          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
405          */
406         private static function update1297()
407         {
408                 // Was the script completed?
409                 if (DI::config()->get('system', 'post_update_version') >= 1297) {
410                         return true;
411                 }
412
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'];
415
416                 Logger::info('Start update1297 with max iid: ' . $max_iid);
417
418                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
419
420                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
421
422                 if (DBA::errorNo() != 0) {
423                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
424                         return false;
425                 }
426
427                 Logger::info('Processed rows: ' . DBA::affectedRows());
428
429                 DI::config()->set('system', 'post_update_version', 1297);
430
431                 Logger::info('Done');
432
433                 return true;
434         }
435         /**
436          * Remove contact duplicates
437          *
438          * @return bool "true" when the job is done
439          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
440          */
441         private static function update1322()
442         {
443                 // Was the script completed?
444                 if (DI::config()->get('system', 'post_update_version') >= 1322) {
445                         return true;
446                 }
447
448                 Logger::info('Start');
449
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);
456
457                 while ($contact = DBA::fetch($contacts)) {
458                         Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
459                         Contact::removeDuplicates($contact['nurl'], $contact['uid']);
460                 }
461
462                 DBA::close($contact);
463                 DI::config()->set('system', 'post_update_version', 1322);
464
465                 Logger::info('Done');
466
467                 return true;
468         }
469
470         /**
471          * update user-item data with notifications
472          *
473          * @return bool "true" when the job is done
474          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475          */
476         private static function update1329()
477         {
478                 // Was the script completed?
479                 if (DI::config()->get('system', 'post_update_version') >= 1329) {
480                         return true;
481                 }
482
483                 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
484
485                 Logger::info('Start', ['item' => $id]);
486
487                 $start_id = $id;
488                 $rows = 0;
489                 $condition = ["`id` > ?", $id];
490                 $params = ['order' => ['id'], 'limit' => 10000];
491                 $items = DBA::select('item', ['id'], $condition, $params);
492
493                 if (DBA::errorNo() != 0) {
494                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
495                         return false;
496                 }
497
498                 while ($item = DBA::fetch($items)) {
499                         $id = $item['id'];
500
501                         UserItem::setNotification($item['id']);
502
503                         ++$rows;
504                 }
505                 DBA::close($items);
506
507                 DI::config()->set('system', 'post_update_version_1329_id', $id);
508
509                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
510
511                 if ($start_id == $id) {
512                         DI::config()->set('system', 'post_update_version', 1329);
513                         Logger::info('Done');
514                         return true;
515                 }
516
517                 return false;
518         }
519 }