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