]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
94d00853abc650b086dd67297c4fbe408978123c
[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\UserItem;
14 use Friendica\Model\PermissionSet;
15
16 /**
17  * Post update functions
18  */
19 class PostUpdate
20 {
21         /**
22          * Calls the post update functions
23          */
24         public static function update()
25         {
26                 if (!self::update1194()) {
27                         return false;
28                 }
29                 if (!self::update1206()) {
30                         return false;
31                 }
32                 if (!self::update1279()) {
33                         return false;
34                 }
35                 if (!self::update1281()) {
36                         return false;
37                 }
38                 if (!self::update1297()) {
39                         return false;
40                 }
41                 if (!self::update1322()) {
42                         return false;
43                 }
44                 if (!self::update1329()) {
45                         return false;
46                 }
47
48                 return true;
49         }
50
51         /**
52          * Updates the "global" field in the item table
53          *
54          * @return bool "true" when the job is done
55          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56          */
57         private static function update1194()
58         {
59                 // Was the script completed?
60                 if (DI::config()->get("system", "post_update_version") >= 1194) {
61                         return true;
62                 }
63
64                 Logger::log("Start", Logger::DEBUG);
65
66                 $end_id = DI::config()->get("system", "post_update_1194_end");
67                 if (!$end_id) {
68                         $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
69                         if ($r) {
70                                 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
71                                 $end_id = DI::config()->get("system", "post_update_1194_end");
72                         }
73                 }
74
75                 Logger::log("End ID: ".$end_id, Logger::DEBUG);
76
77                 $start_id = DI::config()->get("system", "post_update_1194_start");
78
79                 $query1 = "SELECT `item`.`id` FROM `item` ";
80
81                 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
82
83                 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
84                                 AND `item`.`visible` AND NOT `item`.`private`
85                                 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
86                                 AND `item`.`network` IN ('%s', '%s', '%s', '')
87                                 AND NOT `item`.`global`";
88
89                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1",
90                         intval($start_id), intval($end_id),
91                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
92                 if (!$r) {
93                         DI::config()->set("system", "post_update_version", 1194);
94                         Logger::log("Update is done", Logger::DEBUG);
95                         return true;
96                 } else {
97                         DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
98                         $start_id = DI::config()->get("system", "post_update_1194_start");
99                 }
100
101                 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
102
103                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1000,1",
104                         intval($start_id), intval($end_id),
105                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
106                 if ($r) {
107                         $pos_id = $r[0]["id"];
108                 } else {
109                         $pos_id = $end_id;
110                 }
111                 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
112
113                 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
114                         intval($start_id), intval($pos_id),
115                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
116
117                 Logger::log("Done", Logger::DEBUG);
118         }
119
120         /**
121          * update the "last-item" field in the "self" contact
122          *
123          * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
124          *
125          * @return bool "true" when the job is done
126          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
127          */
128         private static function update1206()
129         {
130                 // Was the script completed?
131                 if (DI::config()->get("system", "post_update_version") >= 1206) {
132                         return true;
133                 }
134
135                 Logger::log("Start", Logger::DEBUG);
136                 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
137                         (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
138                         FROM `user`
139                         INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
140
141                 if (!DBA::isResult($r)) {
142                         return false;
143                 }
144                 foreach ($r as $user) {
145                         if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
146                                 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
147                         }
148                 }
149
150                 DI::config()->set("system", "post_update_version", 1206);
151                 Logger::log("Done", Logger::DEBUG);
152                 return true;
153         }
154
155         /**
156          * update the item related tables
157          *
158          * @return bool "true" when the job is done
159          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
160          * @throws \ImagickException
161          */
162         private static function update1279()
163         {
164                 // Was the script completed?
165                 if (DI::config()->get("system", "post_update_version") >= 1279) {
166                         return true;
167                 }
168
169                 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
170
171                 Logger::log("Start from item " . $id, Logger::DEBUG);
172
173                 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
174                         'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
175                         'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
176                         'inform', 'postopts', 'icid']);
177
178                 $start_id = $id;
179                 $rows = 0;
180                 $condition = ["`id` > ?", $id];
181                 $params = ['order' => ['id'], 'limit' => 10000];
182                 $items = Item::select($fields, $condition, $params);
183
184                 if (DBA::errorNo() != 0) {
185                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
186                         return false;
187                 }
188
189                 while ($item = Item::fetch($items)) {
190                         $id = $item['id'];
191
192                         if (empty($item['author-id'])) {
193                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
194                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
195
196                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
197                         }
198
199                         if (empty($item['owner-id'])) {
200                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
201                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
202
203                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
204                         }
205
206                         if (empty($item['psid'])) {
207                                 $item['psid'] = PermissionSet::getIdFromACL(
208                                         $item['uid'],
209                                         $item['allow_cid'],
210                                         $item['allow_gid'],
211                                         $item['deny_cid'],
212                                         $item['deny_gid']
213                                 );
214                         }
215
216                         $item['allow_cid'] = null;
217                         $item['allow_gid'] = null;
218                         $item['deny_cid'] = null;
219                         $item['deny_gid'] = null;
220
221                         if ($item['post-type'] == 0) {
222                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
223                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
224                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
225                                         $item['post-type'] = Item::PT_IMAGE;
226                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
227                                         $item['post-type'] = Item::PT_PAGE;
228                                 }
229                         }
230
231                         self::createLanguage($item);
232
233                         if (!empty($item['icid']) && !empty($item['language'])) {
234                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
235                         }
236                         unset($item['language']);
237
238                         Item::update($item, ['id' => $id]);
239
240                         ++$rows;
241                 }
242                 DBA::close($items);
243
244                 DI::config()->set("system", "post_update_version_1279_id", $id);
245
246                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
247
248                 if ($start_id == $id) {
249                         // Set all deprecated fields to "null" if they contain an empty string
250                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
251                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
252                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
253                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
254                                 'rendered-hash', 'rendered-html'];
255                         foreach ($nullfields as $field) {
256                                 $fields = [$field => null];
257                                 $condition = [$field => ''];
258                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
259                                 // Important: This has to be a "DBA::update", not a "Item::update"
260                                 DBA::update('item', $fields, $condition);
261                         }
262
263                         DI::config()->set("system", "post_update_version", 1279);
264                         Logger::log("Done", Logger::DEBUG);
265                         return true;
266                 }
267
268                 return false;
269         }
270
271         private static function createLanguage(&$item)
272         {
273                 if (empty($item['postopts'])) {
274                         return;
275                 }
276
277                 $opts = explode(',', $item['postopts']);
278
279                 $postopts = [];
280
281                 foreach ($opts as $opt) {
282                         if (strstr($opt, 'lang=')) {
283                                 $language = substr($opt, 5);
284                         } else {
285                                 $postopts[] = $opt;
286                         }
287                 }
288
289                 if (empty($language)) {
290                         return;
291                 }
292
293                 if (!empty($postopts)) {
294                         $item['postopts'] = implode(',', $postopts);
295                 } else {
296                         $item['postopts'] = null;
297                 }
298
299                 $lang_pairs = explode(':', $language);
300
301                 $lang_arr = [];
302
303                 foreach ($lang_pairs as $pair) {
304                         $lang_pair_arr = explode(';', $pair);
305                         if (count($lang_pair_arr) == 2) {
306                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
307                         }
308                 }
309
310                 $item['language'] = json_encode($lang_arr);
311         }
312
313         /**
314          * update item-uri data. Prerequisite for the next item structure update.
315          *
316          * @return bool "true" when the job is done
317          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318          */
319         private static function update1281()
320         {
321                 // Was the script completed?
322                 if (DI::config()->get("system", "post_update_version") >= 1281) {
323                         return true;
324                 }
325
326                 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
327
328                 Logger::log("Start from item " . $id, Logger::DEBUG);
329
330                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
331
332                 $start_id = $id;
333                 $rows = 0;
334                 $condition = ["`id` > ?", $id];
335                 $params = ['order' => ['id'], 'limit' => 10000];
336                 $items = DBA::select('item', $fields, $condition, $params);
337
338                 if (DBA::errorNo() != 0) {
339                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
340                         return false;
341                 }
342
343                 while ($item = DBA::fetch($items)) {
344                         $id = $item['id'];
345
346                         if (empty($item['uri'])) {
347                                 // Should not happen
348                                 continue;
349                         } elseif (empty($item['uri-id'])) {
350                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
351                         }
352
353                         if (empty($item['parent-uri'])) {
354                                 $item['parent-uri-id'] = $item['uri-id'];
355                         } elseif (empty($item['parent-uri-id'])) {
356                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
357                         }
358
359                         // Very old items don't have this field
360                         if (empty($item['thr-parent'])) {
361                                 $item['thr-parent-id'] = $item['parent-uri-id'];
362                         } elseif (empty($item['thr-parent-id'])) {
363                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
364                         }
365
366                         unset($item['id']);
367                         unset($item['guid']);
368                         unset($item['uri']);
369                         unset($item['parent-uri']);
370                         unset($item['thr-parent']);
371
372                         DBA::update('item', $item, ['id' => $id]);
373
374                         ++$rows;
375                 }
376                 DBA::close($items);
377
378                 DI::config()->set("system", "post_update_version_1281_id", $id);
379
380                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
381
382                 if ($start_id == $id) {
383                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
384                         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");
385
386                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
387                         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");
388
389                         DI::config()->set("system", "post_update_version", 1281);
390                         Logger::log("Done", Logger::DEBUG);
391                         return true;
392                 }
393
394                 return false;
395         }
396
397         /**
398          * Set the delivery queue count to a negative value for all items preceding the feature.
399          *
400          * @return bool "true" when the job is done
401          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
402          */
403         private static function update1297()
404         {
405                 // Was the script completed?
406                 if (DI::config()->get('system', 'post_update_version') >= 1297) {
407                         return true;
408                 }
409
410                 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
411                 $max_iid = $max_item_delivery_data['iid'];
412
413                 Logger::info('Start update1297 with max iid: ' . $max_iid);
414
415                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
416
417                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
418
419                 if (DBA::errorNo() != 0) {
420                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
421                         return false;
422                 }
423
424                 Logger::info('Processed rows: ' . DBA::affectedRows());
425
426                 DI::config()->set('system', 'post_update_version', 1297);
427
428                 Logger::info('Done');
429
430                 return true;
431         }
432         /**
433          * Remove contact duplicates
434          *
435          * @return bool "true" when the job is done
436          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
437          */
438         private static function update1322()
439         {
440                 // Was the script completed?
441                 if (DI::config()->get('system', 'post_update_version') >= 1322) {
442                         return true;
443                 }
444
445                 Logger::info('Start');
446
447                 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
448                         WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
449                                 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
450                         AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
451                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
452                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
453
454                 while ($contact = DBA::fetch($contacts)) {
455                         Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
456                         Contact::removeDuplicates($contact['nurl'], $contact['uid']);
457                 }
458
459                 DBA::close($contact);
460                 DI::config()->set('system', 'post_update_version', 1322);
461
462                 Logger::info('Done');
463
464                 return true;
465         }
466
467         /**
468          * update user-item data with notifications
469          *
470          * @return bool "true" when the job is done
471          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472          */
473         private static function update1329()
474         {
475                 // Was the script completed?
476                 if (DI::config()->get('system', 'post_update_version') >= 1329) {
477                         return true;
478                 }
479
480                 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
481
482                 Logger::info('Start', ['item' => $id]);
483
484                 $start_id = $id;
485                 $rows = 0;
486                 $condition = ["`id` > ?", $id];
487                 $params = ['order' => ['id'], 'limit' => 10000];
488                 $items = DBA::select('item', ['id'], $condition, $params);
489
490                 if (DBA::errorNo() != 0) {
491                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
492                         return false;
493                 }
494
495                 while ($item = DBA::fetch($items)) {
496                         $id = $item['id'];
497
498                         UserItem::setNotification($item['id']);
499
500                         ++$rows;
501                 }
502                 DBA::close($items);
503
504                 DI::config()->set('system', 'post_update_version_1329_id', $id);
505
506                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
507
508                 if ($start_id == $id) {
509                         DI::config()->set('system', 'post_update_version', 1329);
510                         Logger::info('Done');
511                         return true;
512                 }
513
514                 return false;
515         }
516 }