]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
4 spaces to tab
[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\Core\L10n;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Item;
13 use Friendica\Model\ItemURI;
14 use Friendica\Model\PermissionSet;
15 use Friendica\Database\DBA;
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::update1206()) {
31                         return false;
32                 }
33                 if (!self::update1279()) {
34                         return false;
35                 }
36                 if (!self::update1281()) {
37                         return false;
38                 }
39
40                 return true;
41         }
42
43         /**
44          * @brief Updates the "global" field in the item table
45          *
46          * @return bool "true" when the job is done
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          */
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          */
150         private static function update1279()
151         {
152                 // Was the script completed?
153                 if (Config::get("system", "post_update_version") >= 1279) {
154                         return true;
155                 }
156
157                 $id = Config::get("system", "post_update_version_1279_id", 0);
158
159                 Logger::log("Start from item " . $id, Logger::DEBUG);
160
161                 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
162                         'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
163                         'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
164                         'inform', 'postopts', 'icid']);
165
166                 $start_id = $id;
167                 $rows = 0;
168                 $condition = ["`id` > ?", $id];
169                 $params = ['order' => ['id'], 'limit' => 10000];
170                 $items = Item::select($fields, $condition, $params);
171
172                 if (DBA::errorNo() != 0) {
173                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
174                         return false;
175                 }
176
177                 while ($item = Item::fetch($items)) {
178                         $id = $item['id'];
179
180                         if (empty($item['author-id'])) {
181                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
182                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
183
184                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
185                         }
186
187                         if (empty($item['owner-id'])) {
188                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
189                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
190
191                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
192                         }
193
194                         if (empty($item['psid'])) {
195                                 $item['psid'] = PermissionSet::fetchIDForPost($item);
196                         } else {
197                                 $item['allow_cid'] = null;
198                                 $item['allow_gid'] = null;
199                                 $item['deny_cid'] = null;
200                                 $item['deny_gid'] = null;
201                         }
202
203                         if ($item['post-type'] == 0) {
204                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
205                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
206                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
207                                         $item['post-type'] = Item::PT_IMAGE;
208                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
209                                         $item['post-type'] = Item::PT_PAGE;
210                                 }
211                         }
212
213                         self::createLanguage($item);
214
215                         if (!empty($item['icid']) && !empty($item['language'])) {
216                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
217                         }
218                         unset($item['language']);
219
220                         Item::update($item, ['id' => $id]);
221
222                         ++$rows;
223                 }
224                 DBA::close($items);
225
226                 Config::set("system", "post_update_version_1279_id", $id);
227
228                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
229
230                 if ($start_id == $id) {
231                         // Set all deprecated fields to "null" if they contain an empty string
232                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
233                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
234                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
235                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
236                                 'rendered-hash', 'rendered-html'];
237                         foreach ($nullfields as $field) {
238                                 $fields = [$field => null];
239                                 $condition = [$field => ''];
240                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
241                                 // Important: This has to be a "DBA::update", not a "Item::update"
242                                 DBA::update('item', $fields, $condition);
243                         }
244
245                         Config::set("system", "post_update_version", 1279);
246                         Logger::log("Done", Logger::DEBUG);
247                         return true;
248                 }
249
250                 return false;
251         }
252
253         private static function createLanguage(&$item)
254         {
255                 if (empty($item['postopts'])) {
256                         return;
257                 }
258
259                 $opts = explode(',', $item['postopts']);
260
261                 $postopts = [];
262
263                 foreach ($opts as $opt) {
264                         if (strstr($opt, 'lang=')) {
265                                 $language = substr($opt, 5);
266                         } else {
267                                 $postopts[] = $opt;
268                         }
269                 }
270
271                 if (empty($language)) {
272                         return;
273                 }
274
275                 if (!empty($postopts)) {
276                         $item['postopts'] = implode(',', $postopts);
277                 } else {
278                         $item['postopts'] = null;
279                 }
280
281                 $lang_pairs = explode(':', $language);
282
283                 $lang_arr = [];
284
285                 foreach ($lang_pairs as $pair) {
286                         $lang_pair_arr = explode(';', $pair);
287                         if (count($lang_pair_arr) == 2) {
288                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
289                         }
290                 }
291
292                 $item['language'] = json_encode($lang_arr);
293         }
294
295         /**
296          * @brief update item-uri data. Prerequisite for the next item structure update.
297          *
298          * @return bool "true" when the job is done
299          */
300         private static function update1281()
301         {
302                 // Was the script completed?
303                 if (Config::get("system", "post_update_version") >= 1281) {
304                         return true;
305                 }
306
307                 $id = Config::get("system", "post_update_version_1281_id", 0);
308
309                 Logger::log("Start from item " . $id, Logger::DEBUG);
310
311                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
312
313                 $start_id = $id;
314                 $rows = 0;
315                 $condition = ["`id` > ?", $id];
316                 $params = ['order' => ['id'], 'limit' => 10000];
317                 $items = DBA::select('item', $fields, $condition, $params);
318
319                 if (DBA::errorNo() != 0) {
320                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
321                         return false;
322                 }
323
324                 while ($item = DBA::fetch($items)) {
325                         $id = $item['id'];
326
327                         if (empty($item['uri'])) {
328                                 // Should not happen
329                                 continue;
330                         } elseif (empty($item['uri-id'])) {
331                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
332                         }
333
334                         if (empty($item['parent-uri'])) {
335                                 $item['parent-uri-id'] = $item['uri-id'];
336                         } elseif (empty($item['parent-uri-id'])) {
337                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
338                         }
339
340                         // Very old items don't have this field
341                         if (empty($item['thr-parent'])) {
342                                 $item['thr-parent-id'] = $item['parent-uri-id'];
343                         } elseif (empty($item['thr-parent-id'])) {
344                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
345                         }
346
347                         unset($item['id']);
348                         unset($item['guid']);
349                         unset($item['uri']);
350                         unset($item['parent-uri']);
351                         unset($item['thr-parent']);
352
353                         DBA::update('item', $item, ['id' => $id]);
354
355                         ++$rows;
356                 }
357                 DBA::close($items);
358
359                 Config::set("system", "post_update_version_1281_id", $id);
360
361                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
362
363                 if ($start_id == $id) {
364                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
365                         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");
366
367                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
368                         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");
369
370                         Config::set("system", "post_update_version", 1281);
371                         Logger::log("Done", Logger::DEBUG);
372                         return true;
373                 }
374
375                 return false;
376         }
377
378         // Post-update script of PR 5596
379         function fixGenderStrings() {
380                 $allGenders = DBA::select('contact', ['id', 'gender']);
381                 $allLangs = L10n::getAvailableLanguages();
382                 $success = 0;
383                 $fail = 0;
384                 foreach($allGenders as $key=>$gender) {
385                         foreach($allLangs as $key=>$lang) {
386
387                                 $a = new \stdClass();
388                                 $a->strings = [];
389
390                                 // First we get the the localizations
391                                 if (file_exists("view/lang/$lang/strings.php")) {
392                                         include "view/lang/$lang/strings.php";
393                                 }
394                                 if (file_exists("addon/morechoice/lang/$lang/strings.php")) {
395                                         include "addon/morechoice/lang/$lang/strings.php";
396                                 }
397
398                                 $localizedStrings = $a->strings;
399                                 unset($a);
400
401                                 $key = array_search($gender['gender'], $localizedStrings);
402                                 if($key !== false) {
403                                         break;
404                                 }
405
406                                 // defaulting to empty string
407                                 $key = '';
408                         }
409                         DBA::update('contact', ['gender' => $key], ['id' => $gender['id']]);
410                         logger::log('Updated contact ' . $gender['id'] . ' to gender ' . $key . ' (was: ' . $gender['gender'] . ')');
411
412                         if ($key == '') {
413                                 $fail++;
414                         }
415                         else {
416                                 $success++;
417                         }
418                 }
419                 
420                 Logger::log("Gender fix completed. Success: $success. Fail: $fail");
421         }
422 }