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