]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
50e7dbcc92303b01006aa594b149f9a0d10245ad
[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\Config;
8 use Friendica\Core\Logger;
9 use Friendica\Core\Protocol;
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 (Config::get("system", "post_update_version") >= 1194) {
61                         return true;
62                 }
63
64                 Logger::log("Start", Logger::DEBUG);
65
66                 $end_id = 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                                 Config::set("system", "post_update_1194_end", $r[0]["id"]);
71                                 $end_id = Config::get("system", "post_update_1194_end");
72                         }
73                 }
74
75                 Logger::log("End ID: ".$end_id, Logger::DEBUG);
76
77                 $start_id = 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                         Config::set("system", "post_update_version", 1194);
94                         Logger::log("Update is done", Logger::DEBUG);
95                         return true;
96                 } else {
97                         Config::set("system", "post_update_1194_start", $r[0]["id"]);
98                         $start_id = 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 (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                 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 (Config::get("system", "post_update_version") >= 1279) {
166                         return true;
167                 }
168
169                 $id = 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::fetchIDForPost($item);
208                         } else {
209                                 $item['allow_cid'] = null;
210                                 $item['allow_gid'] = null;
211                                 $item['deny_cid'] = null;
212                                 $item['deny_gid'] = null;
213                         }
214
215                         if ($item['post-type'] == 0) {
216                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
217                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
218                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
219                                         $item['post-type'] = Item::PT_IMAGE;
220                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
221                                         $item['post-type'] = Item::PT_PAGE;
222                                 }
223                         }
224
225                         self::createLanguage($item);
226
227                         if (!empty($item['icid']) && !empty($item['language'])) {
228                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
229                         }
230                         unset($item['language']);
231
232                         Item::update($item, ['id' => $id]);
233
234                         ++$rows;
235                 }
236                 DBA::close($items);
237
238                 Config::set("system", "post_update_version_1279_id", $id);
239
240                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
241
242                 if ($start_id == $id) {
243                         // Set all deprecated fields to "null" if they contain an empty string
244                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
245                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
246                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
247                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
248                                 'rendered-hash', 'rendered-html'];
249                         foreach ($nullfields as $field) {
250                                 $fields = [$field => null];
251                                 $condition = [$field => ''];
252                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
253                                 // Important: This has to be a "DBA::update", not a "Item::update"
254                                 DBA::update('item', $fields, $condition);
255                         }
256
257                         Config::set("system", "post_update_version", 1279);
258                         Logger::log("Done", Logger::DEBUG);
259                         return true;
260                 }
261
262                 return false;
263         }
264
265         private static function createLanguage(&$item)
266         {
267                 if (empty($item['postopts'])) {
268                         return;
269                 }
270
271                 $opts = explode(',', $item['postopts']);
272
273                 $postopts = [];
274
275                 foreach ($opts as $opt) {
276                         if (strstr($opt, 'lang=')) {
277                                 $language = substr($opt, 5);
278                         } else {
279                                 $postopts[] = $opt;
280                         }
281                 }
282
283                 if (empty($language)) {
284                         return;
285                 }
286
287                 if (!empty($postopts)) {
288                         $item['postopts'] = implode(',', $postopts);
289                 } else {
290                         $item['postopts'] = null;
291                 }
292
293                 $lang_pairs = explode(':', $language);
294
295                 $lang_arr = [];
296
297                 foreach ($lang_pairs as $pair) {
298                         $lang_pair_arr = explode(';', $pair);
299                         if (count($lang_pair_arr) == 2) {
300                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
301                         }
302                 }
303
304                 $item['language'] = json_encode($lang_arr);
305         }
306
307         /**
308          * update item-uri data. Prerequisite for the next item structure update.
309          *
310          * @return bool "true" when the job is done
311          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
312          */
313         private static function update1281()
314         {
315                 // Was the script completed?
316                 if (Config::get("system", "post_update_version") >= 1281) {
317                         return true;
318                 }
319
320                 $id = Config::get("system", "post_update_version_1281_id", 0);
321
322                 Logger::log("Start from item " . $id, Logger::DEBUG);
323
324                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
325
326                 $start_id = $id;
327                 $rows = 0;
328                 $condition = ["`id` > ?", $id];
329                 $params = ['order' => ['id'], 'limit' => 10000];
330                 $items = DBA::select('item', $fields, $condition, $params);
331
332                 if (DBA::errorNo() != 0) {
333                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
334                         return false;
335                 }
336
337                 while ($item = DBA::fetch($items)) {
338                         $id = $item['id'];
339
340                         if (empty($item['uri'])) {
341                                 // Should not happen
342                                 continue;
343                         } elseif (empty($item['uri-id'])) {
344                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
345                         }
346
347                         if (empty($item['parent-uri'])) {
348                                 $item['parent-uri-id'] = $item['uri-id'];
349                         } elseif (empty($item['parent-uri-id'])) {
350                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
351                         }
352
353                         // Very old items don't have this field
354                         if (empty($item['thr-parent'])) {
355                                 $item['thr-parent-id'] = $item['parent-uri-id'];
356                         } elseif (empty($item['thr-parent-id'])) {
357                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
358                         }
359
360                         unset($item['id']);
361                         unset($item['guid']);
362                         unset($item['uri']);
363                         unset($item['parent-uri']);
364                         unset($item['thr-parent']);
365
366                         DBA::update('item', $item, ['id' => $id]);
367
368                         ++$rows;
369                 }
370                 DBA::close($items);
371
372                 Config::set("system", "post_update_version_1281_id", $id);
373
374                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
375
376                 if ($start_id == $id) {
377                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
378                         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");
379
380                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
381                         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");
382
383                         Config::set("system", "post_update_version", 1281);
384                         Logger::log("Done", Logger::DEBUG);
385                         return true;
386                 }
387
388                 return false;
389         }
390
391         /**
392          * Set the delivery queue count to a negative value for all items preceding the feature.
393          *
394          * @return bool "true" when the job is done
395          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
396          */
397         private static function update1297()
398         {
399                 // Was the script completed?
400                 if (Config::get('system', 'post_update_version') >= 1297) {
401                         return true;
402                 }
403
404                 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
405                 $max_iid = $max_item_delivery_data['iid'];
406
407                 Logger::info('Start update1297 with max iid: ' . $max_iid);
408
409                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
410
411                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
412
413                 if (DBA::errorNo() != 0) {
414                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
415                         return false;
416                 }
417
418                 Logger::info('Processed rows: ' . DBA::affectedRows());
419
420                 Config::set('system', 'post_update_version', 1297);
421
422                 Logger::info('Done');
423
424                 return true;
425         }
426         /**
427          * Remove contact duplicates
428          *
429          * @return bool "true" when the job is done
430          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
431          */
432         private static function update1322()
433         {
434                 // Was the script completed?
435                 if (Config::get('system', 'post_update_version') >= 1322) {
436                         return true;
437                 }
438
439                 Logger::info('Start');
440
441                 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
442                         WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
443                                 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
444                         AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
445                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
446                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
447
448                 while ($contact = DBA::fetch($contacts)) {
449                         Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
450                         Contact::removeDuplicates($contact['nurl'], $contact['uid']);
451                 }
452
453                 DBA::close($contact);
454                 Config::set('system', 'post_update_version', 1322);
455
456                 Logger::info('Done');
457
458                 return true;
459         }
460
461         /**
462          * update user-item data with notifications
463          *
464          * @return bool "true" when the job is done
465          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
466          */
467         private static function update1329()
468         {
469                 // Was the script completed?
470                 if (Config::get('system', 'post_update_version') >= 1329) {
471                         return true;
472                 }
473
474                 $id = Config::get('system', 'post_update_version_1329_id', 0);
475
476                 Logger::info('Start', ['item' => $id]);
477
478                 $start_id = $id;
479                 $rows = 0;
480                 $condition = ["`id` > ?", $id];
481                 $params = ['order' => ['id'], 'limit' => 10000];
482                 $items = DBA::select('item', ['id'], $condition, $params);
483
484                 if (DBA::errorNo() != 0) {
485                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
486                         return false;
487                 }
488
489                 while ($item = DBA::fetch($items)) {
490                         $id = $item['id'];
491
492                         UserItem::setNotification($item['id']);
493
494                         ++$rows;
495                 }
496                 DBA::close($items);
497
498                 Config::set('system', 'post_update_version_1329_id', $id);
499
500                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
501
502                 if ($start_id == $id) {
503                         Config::set('system', 'post_update_version', 1329);
504                         Logger::info('Done');
505                         return true;
506                 }
507
508                 return false;
509         }
510 }