]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
Use direct logic
[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                 if (!self::update1297()) {
38                         return false;
39                 }
40
41                 return true;
42         }
43
44         /**
45          * @brief Updates the "global" field in the item table
46          *
47          * @return bool "true" when the job is done
48          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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::log("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::log("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(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
85                 if (!$r) {
86                         Config::set("system", "post_update_version", 1194);
87                         Logger::log("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::log("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(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
99                 if ($r) {
100                         $pos_id = $r[0]["id"];
101                 } else {
102                         $pos_id = $end_id;
103                 }
104                 Logger::log("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(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
109
110                 Logger::log("Done", Logger::DEBUG);
111         }
112
113         /**
114          * @brief update the "last-item" field in the "self" contact
115          *
116          * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
117          *
118          * @return bool "true" when the job is done
119          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120          */
121         private static function update1206()
122         {
123                 // Was the script completed?
124                 if (Config::get("system", "post_update_version") >= 1206) {
125                         return true;
126                 }
127
128                 Logger::log("Start", Logger::DEBUG);
129                 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
130                         (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
131                         FROM `user`
132                         INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
133
134                 if (!DBA::isResult($r)) {
135                         return false;
136                 }
137                 foreach ($r as $user) {
138                         if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
139                                 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
140                         }
141                 }
142
143                 Config::set("system", "post_update_version", 1206);
144                 Logger::log("Done", Logger::DEBUG);
145                 return true;
146         }
147
148         /**
149          * @brief update the item related tables
150          *
151          * @return bool "true" when the job is done
152          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153          * @throws \ImagickException
154          */
155         private static function update1279()
156         {
157                 // Was the script completed?
158                 if (Config::get("system", "post_update_version") >= 1279) {
159                         return true;
160                 }
161
162                 $id = Config::get("system", "post_update_version_1279_id", 0);
163
164                 Logger::log("Start from item " . $id, Logger::DEBUG);
165
166                 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
167                         'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
168                         'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
169                         'inform', 'postopts', 'icid']);
170
171                 $start_id = $id;
172                 $rows = 0;
173                 $condition = ["`id` > ?", $id];
174                 $params = ['order' => ['id'], 'limit' => 10000];
175                 $items = Item::select($fields, $condition, $params);
176
177                 if (DBA::errorNo() != 0) {
178                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
179                         return false;
180                 }
181
182                 while ($item = Item::fetch($items)) {
183                         $id = $item['id'];
184
185                         if (empty($item['author-id'])) {
186                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
187                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
188
189                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
190                         }
191
192                         if (empty($item['owner-id'])) {
193                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
194                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
195
196                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
197                         }
198
199                         if (empty($item['psid'])) {
200                                 $item['psid'] = PermissionSet::fetchIDForPost($item);
201                         } else {
202                                 $item['allow_cid'] = null;
203                                 $item['allow_gid'] = null;
204                                 $item['deny_cid'] = null;
205                                 $item['deny_gid'] = null;
206                         }
207
208                         if ($item['post-type'] == 0) {
209                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
210                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
211                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
212                                         $item['post-type'] = Item::PT_IMAGE;
213                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
214                                         $item['post-type'] = Item::PT_PAGE;
215                                 }
216                         }
217
218                         self::createLanguage($item);
219
220                         if (!empty($item['icid']) && !empty($item['language'])) {
221                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
222                         }
223                         unset($item['language']);
224
225                         Item::update($item, ['id' => $id]);
226
227                         ++$rows;
228                 }
229                 DBA::close($items);
230
231                 Config::set("system", "post_update_version_1279_id", $id);
232
233                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
234
235                 if ($start_id == $id) {
236                         // Set all deprecated fields to "null" if they contain an empty string
237                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
238                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
239                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
240                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
241                                 'rendered-hash', 'rendered-html'];
242                         foreach ($nullfields as $field) {
243                                 $fields = [$field => null];
244                                 $condition = [$field => ''];
245                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
246                                 // Important: This has to be a "DBA::update", not a "Item::update"
247                                 DBA::update('item', $fields, $condition);
248                         }
249
250                         Config::set("system", "post_update_version", 1279);
251                         Logger::log("Done", Logger::DEBUG);
252                         return true;
253                 }
254
255                 return false;
256         }
257
258         private static function createLanguage(&$item)
259         {
260                 if (empty($item['postopts'])) {
261                         return;
262                 }
263
264                 $opts = explode(',', $item['postopts']);
265
266                 $postopts = [];
267
268                 foreach ($opts as $opt) {
269                         if (strstr($opt, 'lang=')) {
270                                 $language = substr($opt, 5);
271                         } else {
272                                 $postopts[] = $opt;
273                         }
274                 }
275
276                 if (empty($language)) {
277                         return;
278                 }
279
280                 if (!empty($postopts)) {
281                         $item['postopts'] = implode(',', $postopts);
282                 } else {
283                         $item['postopts'] = null;
284                 }
285
286                 $lang_pairs = explode(':', $language);
287
288                 $lang_arr = [];
289
290                 foreach ($lang_pairs as $pair) {
291                         $lang_pair_arr = explode(';', $pair);
292                         if (count($lang_pair_arr) == 2) {
293                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
294                         }
295                 }
296
297                 $item['language'] = json_encode($lang_arr);
298         }
299
300         /**
301          * @brief update item-uri data. Prerequisite for the next item structure update.
302          *
303          * @return bool "true" when the job is done
304          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305          */
306         private static function update1281()
307         {
308                 // Was the script completed?
309                 if (Config::get("system", "post_update_version") >= 1281) {
310                         return true;
311                 }
312
313                 $id = Config::get("system", "post_update_version_1281_id", 0);
314
315                 Logger::log("Start from item " . $id, Logger::DEBUG);
316
317                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
318
319                 $start_id = $id;
320                 $rows = 0;
321                 $condition = ["`id` > ?", $id];
322                 $params = ['order' => ['id'], 'limit' => 10000];
323                 $items = DBA::select('item', $fields, $condition, $params);
324
325                 if (DBA::errorNo() != 0) {
326                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
327                         return false;
328                 }
329
330                 while ($item = DBA::fetch($items)) {
331                         $id = $item['id'];
332
333                         if (empty($item['uri'])) {
334                                 // Should not happen
335                                 continue;
336                         } elseif (empty($item['uri-id'])) {
337                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
338                         }
339
340                         if (empty($item['parent-uri'])) {
341                                 $item['parent-uri-id'] = $item['uri-id'];
342                         } elseif (empty($item['parent-uri-id'])) {
343                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
344                         }
345
346                         // Very old items don't have this field
347                         if (empty($item['thr-parent'])) {
348                                 $item['thr-parent-id'] = $item['parent-uri-id'];
349                         } elseif (empty($item['thr-parent-id'])) {
350                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
351                         }
352
353                         unset($item['id']);
354                         unset($item['guid']);
355                         unset($item['uri']);
356                         unset($item['parent-uri']);
357                         unset($item['thr-parent']);
358
359                         DBA::update('item', $item, ['id' => $id]);
360
361                         ++$rows;
362                 }
363                 DBA::close($items);
364
365                 Config::set("system", "post_update_version_1281_id", $id);
366
367                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
368
369                 if ($start_id == $id) {
370                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
371                         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");
372
373                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
374                         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");
375
376                         Config::set("system", "post_update_version", 1281);
377                         Logger::log("Done", Logger::DEBUG);
378                         return true;
379                 }
380
381                 return false;
382         }
383
384         /**
385          * Set the delivery queue count to a negative value for all items preceding the feature.
386          *
387          * @return bool "true" when the job is done
388          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389          */
390         private static function update1297()
391         {
392                 // Was the script completed?
393                 if (Config::get('system', 'post_update_version') >= 1297) {
394                         return true;
395                 }
396
397                 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
398                 $max_iid = $max_item_delivery_data['iid'];
399
400                 Logger::info('Start update1297 with max iid: ' . $max_iid);
401
402                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
403
404                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
405
406                 if (DBA::errorNo() != 0) {
407                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
408                         return false;
409                 }
410
411                 Logger::info('Processed rows: ' . DBA::affectedRows());
412
413                 Config::set('system', 'post_update_version', 1297);
414
415                 Logger::info('Done');
416
417                 return true;
418         }
419 }