]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
a5bdcdeadd6c84653c03341d18cdb9533efae9ec
[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\PermissionSet;
14 use Friendica\Database\DBA;
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::update1206()) {
30                         return false;
31                 }
32                 if (!self::update1279()) {
33                         return false;
34                 }
35                 if (!self::update1281()) {
36                         return false;
37                 }
38
39                 return true;
40         }
41
42         /**
43          * @brief Updates the "global" field in the item table
44          *
45          * @return bool "true" when the job is done
46          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
47          */
48         private static function update1194()
49         {
50                 // Was the script completed?
51                 if (Config::get("system", "post_update_version") >= 1194) {
52                         return true;
53                 }
54
55                 Logger::log("Start", Logger::DEBUG);
56
57                 $end_id = Config::get("system", "post_update_1194_end");
58                 if (!$end_id) {
59                         $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
60                         if ($r) {
61                                 Config::set("system", "post_update_1194_end", $r[0]["id"]);
62                                 $end_id = Config::get("system", "post_update_1194_end");
63                         }
64                 }
65
66                 Logger::log("End ID: ".$end_id, Logger::DEBUG);
67
68                 $start_id = Config::get("system", "post_update_1194_start");
69
70                 $query1 = "SELECT `item`.`id` FROM `item` ";
71
72                 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
73
74                 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
75                                 AND `item`.`visible` AND NOT `item`.`private`
76                                 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
77                                 AND `item`.`network` IN ('%s', '%s', '%s', '')
78                                 AND NOT `item`.`global`";
79
80                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1",
81                         intval($start_id), intval($end_id),
82                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
83                 if (!$r) {
84                         Config::set("system", "post_update_version", 1194);
85                         Logger::log("Update is done", Logger::DEBUG);
86                         return true;
87                 } else {
88                         Config::set("system", "post_update_1194_start", $r[0]["id"]);
89                         $start_id = Config::get("system", "post_update_1194_start");
90                 }
91
92                 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
93
94                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1000,1",
95                         intval($start_id), intval($end_id),
96                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
97                 if ($r) {
98                         $pos_id = $r[0]["id"];
99                 } else {
100                         $pos_id = $end_id;
101                 }
102                 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
103
104                 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
105                         intval($start_id), intval($pos_id),
106                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
107
108                 Logger::log("Done", Logger::DEBUG);
109         }
110
111         /**
112          * @brief update the "last-item" field in the "self" contact
113          *
114          * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
115          *
116          * @return bool "true" when the job is done
117          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118          */
119         private static function update1206()
120         {
121                 // Was the script completed?
122                 if (Config::get("system", "post_update_version") >= 1206) {
123                         return true;
124                 }
125
126                 Logger::log("Start", Logger::DEBUG);
127                 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
128                         (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
129                         FROM `user`
130                         INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
131
132                 if (!DBA::isResult($r)) {
133                         return false;
134                 }
135                 foreach ($r as $user) {
136                         if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
137                                 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
138                         }
139                 }
140
141                 Config::set("system", "post_update_version", 1206);
142                 Logger::log("Done", Logger::DEBUG);
143                 return true;
144         }
145
146         /**
147          * @brief update the item related tables
148          *
149          * @return bool "true" when the job is done
150          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
151          * @throws \ImagickException
152          */
153         private static function update1279()
154         {
155                 // Was the script completed?
156                 if (Config::get("system", "post_update_version") >= 1279) {
157                         return true;
158                 }
159
160                 $id = Config::get("system", "post_update_version_1279_id", 0);
161
162                 Logger::log("Start from item " . $id, Logger::DEBUG);
163
164                 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
165                         'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
166                         'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
167                         'inform', 'postopts', 'icid']);
168
169                 $start_id = $id;
170                 $rows = 0;
171                 $condition = ["`id` > ?", $id];
172                 $params = ['order' => ['id'], 'limit' => 10000];
173                 $items = Item::select($fields, $condition, $params);
174
175                 if (DBA::errorNo() != 0) {
176                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
177                         return false;
178                 }
179
180                 while ($item = Item::fetch($items)) {
181                         $id = $item['id'];
182
183                         if (empty($item['author-id'])) {
184                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
185                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
186
187                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
188                         }
189
190                         if (empty($item['owner-id'])) {
191                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
192                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
193
194                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
195                         }
196
197                         if (empty($item['psid'])) {
198                                 $item['psid'] = PermissionSet::fetchIDForPost($item);
199                         } else {
200                                 $item['allow_cid'] = null;
201                                 $item['allow_gid'] = null;
202                                 $item['deny_cid'] = null;
203                                 $item['deny_gid'] = null;
204                         }
205
206                         if ($item['post-type'] == 0) {
207                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
208                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
209                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
210                                         $item['post-type'] = Item::PT_IMAGE;
211                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
212                                         $item['post-type'] = Item::PT_PAGE;
213                                 }
214                         }
215
216                         self::createLanguage($item);
217
218                         if (!empty($item['icid']) && !empty($item['language'])) {
219                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
220                         }
221                         unset($item['language']);
222
223                         Item::update($item, ['id' => $id]);
224
225                         ++$rows;
226                 }
227                 DBA::close($items);
228
229                 Config::set("system", "post_update_version_1279_id", $id);
230
231                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
232
233                 if ($start_id == $id) {
234                         // Set all deprecated fields to "null" if they contain an empty string
235                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
236                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
237                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
238                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
239                                 'rendered-hash', 'rendered-html'];
240                         foreach ($nullfields as $field) {
241                                 $fields = [$field => null];
242                                 $condition = [$field => ''];
243                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
244                                 // Important: This has to be a "DBA::update", not a "Item::update"
245                                 DBA::update('item', $fields, $condition);
246                         }
247
248                         Config::set("system", "post_update_version", 1279);
249                         Logger::log("Done", Logger::DEBUG);
250                         return true;
251                 }
252
253                 return false;
254         }
255
256         private static function createLanguage(&$item)
257         {
258                 if (empty($item['postopts'])) {
259                         return;
260                 }
261
262                 $opts = explode(',', $item['postopts']);
263
264                 $postopts = [];
265
266                 foreach ($opts as $opt) {
267                         if (strstr($opt, 'lang=')) {
268                                 $language = substr($opt, 5);
269                         } else {
270                                 $postopts[] = $opt;
271                         }
272                 }
273
274                 if (empty($language)) {
275                         return;
276                 }
277
278                 if (!empty($postopts)) {
279                         $item['postopts'] = implode(',', $postopts);
280                 } else {
281                         $item['postopts'] = null;
282                 }
283
284                 $lang_pairs = explode(':', $language);
285
286                 $lang_arr = [];
287
288                 foreach ($lang_pairs as $pair) {
289                         $lang_pair_arr = explode(';', $pair);
290                         if (count($lang_pair_arr) == 2) {
291                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
292                         }
293                 }
294
295                 $item['language'] = json_encode($lang_arr);
296         }
297
298         /**
299          * @brief update item-uri data. Prerequisite for the next item structure update.
300          *
301          * @return bool "true" when the job is done
302          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
303          */
304         private static function update1281()
305         {
306                 // Was the script completed?
307                 if (Config::get("system", "post_update_version") >= 1281) {
308                         return true;
309                 }
310
311                 $id = Config::get("system", "post_update_version_1281_id", 0);
312
313                 Logger::log("Start from item " . $id, Logger::DEBUG);
314
315                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
316
317                 $start_id = $id;
318                 $rows = 0;
319                 $condition = ["`id` > ?", $id];
320                 $params = ['order' => ['id'], 'limit' => 10000];
321                 $items = DBA::select('item', $fields, $condition, $params);
322
323                 if (DBA::errorNo() != 0) {
324                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
325                         return false;
326                 }
327
328                 while ($item = DBA::fetch($items)) {
329                         $id = $item['id'];
330
331                         if (empty($item['uri'])) {
332                                 // Should not happen
333                                 continue;
334                         } elseif (empty($item['uri-id'])) {
335                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
336                         }
337
338                         if (empty($item['parent-uri'])) {
339                                 $item['parent-uri-id'] = $item['uri-id'];
340                         } elseif (empty($item['parent-uri-id'])) {
341                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
342                         }
343
344                         // Very old items don't have this field
345                         if (empty($item['thr-parent'])) {
346                                 $item['thr-parent-id'] = $item['parent-uri-id'];
347                         } elseif (empty($item['thr-parent-id'])) {
348                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
349                         }
350
351                         unset($item['id']);
352                         unset($item['guid']);
353                         unset($item['uri']);
354                         unset($item['parent-uri']);
355                         unset($item['thr-parent']);
356
357                         DBA::update('item', $item, ['id' => $id]);
358
359                         ++$rows;
360                 }
361                 DBA::close($items);
362
363                 Config::set("system", "post_update_version_1281_id", $id);
364
365                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
366
367                 if ($start_id == $id) {
368                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
369                         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");
370
371                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
372                         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");
373
374                         Config::set("system", "post_update_version", 1281);
375                         Logger::log("Done", Logger::DEBUG);
376                         return true;
377                 }
378
379                 return false;
380         }
381 }