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