Merge pull request #8099 from annando/statistics
[friendica.git/.git] / update.php
1 <?php
2
3 use Friendica\Core\Addon;
4 use Friendica\Core\Config;
5 use Friendica\Core\L10n;
6 use Friendica\Core\Logger;
7 use Friendica\Core\PConfig;
8 use Friendica\Core\Update;
9 use Friendica\Core\Worker;
10 use Friendica\Database\DBA;
11 use Friendica\Model\Contact;
12 use Friendica\Model\GContact;
13 use Friendica\Model\Item;
14 use Friendica\Model\User;
15 use Friendica\Model\Storage;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Worker\Delivery;
18
19 /**
20  *
21  * update.php - automatic system update
22  *
23  * This function is responsible for doing post update changes to the data
24  * (not the structure) in the database.
25  *
26  * Database structure changes are done in static/dbstructure.config.php
27  *
28  * If there is a need for a post process to a structure change, update this file
29  * by adding a new function at the end with the number of the new DB_UPDATE_VERSION.
30  *
31  * The numbered script in this file has to be exactly like the DB_UPDATE_VERSION
32  *
33  * Example:
34  * You are currently on version 4711 and you are preparing changes that demand an update script.
35  *
36  * 1. Create a function "update_4712()" here in the update.php
37  * 2. Apply the needed structural changes in static/dbStructure.php
38  * 3. Set DB_UPDATE_VERSION in static/dbstructure.config.php to 4712.
39  *
40  * If you need to run a script before the database update, name the function "pre_update_4712()"
41  */
42
43 function update_1178()
44 {
45         require_once 'mod/profiles.php';
46
47         $profiles = q("SELECT `uid`, `about`, `locality`, `pub_keywords`, `gender` FROM `profile` WHERE `is-default`");
48
49         foreach ($profiles as $profile) {
50                 if ($profile["about"].$profile["locality"].$profile["pub_keywords"].$profile["gender"] == "") {
51                         continue;
52                 }
53
54                 $profile["pub_keywords"] = profile_clean_keywords($profile["pub_keywords"]);
55
56                 $r = q("UPDATE `contact` SET `about` = '%s', `location` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `self` AND `uid` = %d",
57                         DBA::escape($profile["about"]),
58                         DBA::escape($profile["locality"]),
59                         DBA::escape($profile["pub_keywords"]),
60                         DBA::escape($profile["gender"]),
61                         intval($profile["uid"])
62                 );
63         }
64 }
65
66 function update_1179()
67 {
68         if (Config::get('system', 'no_community_page')) {
69                 Config::set('system', 'community_page_style', CP_NO_COMMUNITY_PAGE);
70         }
71
72         // Update the central item storage with uid=0
73         Worker::add(PRIORITY_LOW, "threadupdate");
74
75         return Update::SUCCESS;
76 }
77
78 function update_1181()
79 {
80
81         // Fill the new fields in the term table.
82         Worker::add(PRIORITY_LOW, "TagUpdate");
83
84         return Update::SUCCESS;
85 }
86
87 function update_1189()
88 {
89
90         if (strlen(Config::get('system', 'directory_submit_url')) &&
91                 !strlen(Config::get('system', 'directory'))) {
92                 Config::set('system', 'directory', dirname(Config::get('system', 'directory_submit_url')));
93                 Config::delete('system', 'directory_submit_url');
94         }
95
96         return Update::SUCCESS;
97 }
98
99 function update_1191()
100 {
101         Config::set('system', 'maintenance', 1);
102
103         if (Addon::isEnabled('forumlist')) {
104                 $addon = 'forumlist';
105                 $addons = Config::get('system', 'addon');
106                 $addons_arr = [];
107
108                 if ($addons) {
109                         $addons_arr = explode(",", str_replace(" ", "", $addons));
110
111                         $idx = array_search($addon, $addons_arr);
112                         if ($idx !== false) {
113                                 unset($addons_arr[$idx]);
114                                 //delete forumlist manually from addon and hook table
115                                 // since Addon::uninstall() don't work here
116                                 q("DELETE FROM `addon` WHERE `name` = 'forumlist' ");
117                                 q("DELETE FROM `hook` WHERE `file` = 'addon/forumlist/forumlist.php' ");
118                                 Config::set('system', 'addon', implode(", ", $addons_arr));
119                         }
120                 }
121         }
122
123         // select old formlist addon entries
124         $r = q("SELECT `uid`, `cat`, `k`, `v` FROM `pconfig` WHERE `cat` = '%s' ",
125                 DBA::escape('forumlist')
126         );
127
128         // convert old forumlist addon entries in new config entries
129         if (DBA::isResult($r)) {
130                 foreach ($r as $rr) {
131                         $uid = $rr['uid'];
132                         $family = $rr['cat'];
133                         $key = $rr['k'];
134                         $value = $rr['v'];
135
136                         if ($key === 'randomise') {
137                                 PConfig::delete($uid, $family, $key);
138                         }
139
140                         if ($key === 'show_on_profile') {
141                                 if ($value) {
142                                         PConfig::set($uid, feature, forumlist_profile, $value);
143                                 }
144
145                                 PConfig::delete($uid, $family, $key);
146                         }
147
148                         if ($key === 'show_on_network') {
149                                 if ($value) {
150                                         PConfig::set($uid, feature, forumlist_widget, $value);
151                                 }
152
153                                 PConfig::delete($uid, $family, $key);
154                         }
155                 }
156         }
157
158         Config::set('system', 'maintenance', 0);
159
160         return Update::SUCCESS;
161 }
162
163 function update_1203()
164 {
165         $r = q("UPDATE `user` SET `account-type` = %d WHERE `page-flags` IN (%d, %d)",
166                 DBA::escape(User::ACCOUNT_TYPE_COMMUNITY),
167                 DBA::escape(User::PAGE_FLAGS_COMMUNITY),
168                 DBA::escape(User::PAGE_FLAGS_PRVGROUP)
169         );
170 }
171
172 function update_1244()
173 {
174         // Sets legacy_password for all legacy hashes
175         DBA::update('user', ['legacy_password' => true], ['SUBSTR(password, 1, 4) != "$2y$"']);
176
177         // All legacy hashes are re-hashed using the new secure hashing function
178         $stmt = DBA::select('user', ['uid', 'password'], ['legacy_password' => true]);
179         while ($user = DBA::fetch($stmt)) {
180                 DBA::update('user', ['password' => User::hashPassword($user['password'])], ['uid' => $user['uid']]);
181         }
182
183         // Logged in users are forcibly logged out
184         DBA::delete('session', ['1 = 1']);
185
186         return Update::SUCCESS;
187 }
188
189 function update_1245()
190 {
191         $rino = Config::get('system', 'rino_encrypt');
192
193         if (!$rino) {
194                 return Update::SUCCESS;
195         }
196
197         Config::set('system', 'rino_encrypt', 1);
198
199         return Update::SUCCESS;
200 }
201
202 function update_1247()
203 {
204         // Removing hooks with the old name
205         DBA::e("DELETE FROM `hook`
206 WHERE `hook` LIKE 'plugin_%'");
207
208         // Make sure we install the new renamed ones
209         Addon::reload();
210 }
211
212 function update_1260()
213 {
214         Config::set('system', 'maintenance', 1);
215         Config::set(
216                 'system',
217                 'maintenance_reason',
218                 L10n::t(
219                         '%s: Updating author-id and owner-id in item and thread table. ',
220                         DateTimeFormat::utcNow().' '.date('e')
221                 )
222         );
223
224         $items = DBA::p("SELECT `id`, `owner-link`, `owner-name`, `owner-avatar`, `network` FROM `item`
225                 WHERE `owner-id` = 0 AND `owner-link` != ''");
226         while ($item = DBA::fetch($items)) {
227                 $contact = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
228                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
229                 $cid = Contact::getIdForURL($item['owner-link'], 0, false, $contact);
230                 if (empty($cid)) {
231                         continue;
232                 }
233                 Item::update(['owner-id' => $cid], ['id' => $item['id']]);
234         }
235         DBA::close($items);
236
237         DBA::e("UPDATE `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`id`
238                 SET `thread`.`owner-id` = `item`.`owner-id` WHERE `thread`.`owner-id` = 0");
239
240         $items = DBA::p("SELECT `id`, `author-link`, `author-name`, `author-avatar`, `network` FROM `item`
241                 WHERE `author-id` = 0 AND `author-link` != ''");
242         while ($item = DBA::fetch($items)) {
243                 $contact = ['url' => $item['author-link'], 'name' => $item['author-name'],
244                         'photo' => $item['author-avatar'], 'network' => $item['network']];
245                 $cid = Contact::getIdForURL($item['author-link'], 0, false, $contact);
246                 if (empty($cid)) {
247                         continue;
248                 }
249                 Item::update(['author-id' => $cid], ['id' => $item['id']]);
250         }
251         DBA::close($items);
252
253         DBA::e("UPDATE `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`id`
254                 SET `thread`.`author-id` = `item`.`author-id` WHERE `thread`.`author-id` = 0");
255
256         Config::set('system', 'maintenance', 0);
257         return Update::SUCCESS;
258 }
259
260 function update_1261()
261 {
262         // This fixes the results of an issue in the develop branch of 2018-05.
263         DBA::update('contact', ['blocked' => false, 'pending' => false], ['uid' => 0, 'blocked' => true, 'pending' => true]);
264         return Update::SUCCESS;
265 }
266
267 function update_1278()
268 {
269         Config::set('system', 'maintenance', 1);
270         Config::set(
271                 'system',
272                 'maintenance_reason',
273                 L10n::t(
274                         '%s: Updating post-type.',
275                         DateTimeFormat::utcNow().' '.date('e')
276                 )
277         );
278
279         Item::update(['post-type' => Item::PT_PAGE], ['bookmark' => true]);
280         Item::update(['post-type' => Item::PT_PERSONAL_NOTE], ['type' => 'note']);
281
282         Config::set('system', 'maintenance', 0);
283
284         return Update::SUCCESS;
285 }
286
287 function update_1288()
288 {
289         // Updates missing `uri-id` values
290
291         DBA::e("UPDATE `item-activity` INNER JOIN `item` ON `item`.`iaid` = `item-activity`.`id` SET `item-activity`.`uri-id` = `item`.`uri-id` WHERE `item-activity`.`uri-id` IS NULL OR `item-activity`.`uri-id` = 0");
292         DBA::e("UPDATE `item-content` INNER JOIN `item` ON `item`.`icid` = `item-content`.`id` SET `item-content`.`uri-id` = `item`.`uri-id` WHERE `item-content`.`uri-id` IS NULL OR `item-content`.`uri-id` = 0");
293
294         return Update::SUCCESS;
295 }
296
297 // Post-update script of PR 5751
298 function update_1298()
299 {
300         $keys = ['gender', 'marital', 'sexual'];
301         foreach ($keys as $translateKey) {
302                 $allData = DBA::select('profile', ['id', $translateKey]);
303                 $allLangs = L10n::getAvailableLanguages();
304                 $success = 0;
305                 $fail = 0;
306                 foreach ($allData as $key => $data) {
307                         $toTranslate = $data[$translateKey];
308                         if ($toTranslate != '') {
309                                 foreach ($allLangs as $key => $lang) {
310                                         $a = new \stdClass();
311                                         $a->strings = [];
312
313                                         // First we get the the localizations
314                                         if (file_exists("view/lang/$lang/strings.php")) {
315                                                 include "view/lang/$lang/strings.php";
316                                         }
317                                         if (file_exists("addon/morechoice/lang/$lang/strings.php")) {
318                                                 include "addon/morechoice/lang/$lang/strings.php";
319                                         }
320
321                                         $localizedStrings = $a->strings;
322                                         unset($a);
323
324                                         $key = array_search($toTranslate, $localizedStrings);
325                                         if ($key !== false) {
326                                                 break;
327                                         }
328
329                                         // defaulting to empty string
330                                         $key = '';
331                                 }
332
333                                 if ($key == '') {
334                                         $fail++;
335                                 } else {
336                                         DBA::update('profile', [$translateKey => $key], ['id' => $data['id']]);
337                                         Logger::notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key,
338                                                 'was' => $data[$translateKey]]);
339                                         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $data['id']);
340                                         Contact::updateSelfFromUserID($data['id']);
341                                         GContact::updateForUser($data['id']);
342                                         $success++;
343                                 }
344                         }
345                 }
346
347                 Logger::notice($translateKey . " fix completed", ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]);
348         }
349         return Update::SUCCESS;
350 }
351
352 function update_1309()
353 {
354         $queue = DBA::select('queue', ['id', 'cid', 'guid']);
355         while ($entry = DBA::fetch($queue)) {
356                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $entry['cid']]);
357                 if (!DBA::isResult($contact)) {
358                         continue;
359                 }
360
361                 $item = Item::selectFirst(['id', 'gravity'], ['uid' => $contact['uid'], 'guid' => $entry['guid']]);
362                 if (!DBA::isResult($item)) {
363                         continue;
364                 }
365
366                 $deliver_options = ['priority' => PRIORITY_MEDIUM, 'dont_fork' => true];
367                 Worker::add($deliver_options, 'Delivery', Delivery::POST, $item['id'], $entry['cid']);
368                 Logger::info('Added delivery worker', ['command' => $cmd, 'item' => $item['id'], 'contact' => $entry['cid']]);
369                 DBA::delete('queue', ['id' => $entry['id']]);
370         }
371         return Update::SUCCESS;
372 }
373
374 function update_1315()
375 {
376         DBA::delete('item-delivery-data', ['postopts' => '', 'inform' => '', 'queue_count' => 0, 'queue_done' => 0]);
377         return Update::SUCCESS;
378 }
379
380 function update_1318()
381 {
382         DBA::update('profile', ['marital' => "In a relation"], ['marital' => "Unavailable"]);
383         DBA::update('profile', ['marital' => "Single"], ['marital' => "Available"]);
384
385         Worker::add(PRIORITY_LOW, 'ProfileUpdate');
386         return Update::SUCCESS;
387 }
388
389 function update_1323()
390 {
391         $users = DBA::select('user', ['uid']);
392         while ($user = DBA::fetch($users)) {
393                 Contact::updateSelfFromUserID($user['uid']);
394         }
395         DBA::close($users);
396
397         return Update::SUCCESS;
398 }
399
400 function update_1327()
401 {
402         $contacts = DBA::select('contact', ['uid', 'id', 'blocked', 'readonly'], ["`uid` != ? AND (`blocked` OR `readonly`) AND NOT `pending`", 0]);
403         while ($contact = DBA::fetch($contacts)) {
404                 Contact::setBlockedForUser($contact['id'], $contact['uid'], $contact['blocked']);
405                 Contact::setIgnoredForUser($contact['id'], $contact['uid'], $contact['readonly']);
406         }
407         DBA::close($contacts);
408
409         return Update::SUCCESS;
410 }
411
412 function update_1330()
413 {
414         $currStorage = Config::get('storage', 'class', '');
415
416         // set the name of the storage instead of the classpath as config
417         if (!empty($currStorage)) {
418                 /** @var Storage\IStorage $currStorage */
419                 if (!Config::set('storage', 'name', $currStorage::getName())) {
420                         return Update::FAILED;
421                 }
422
423                 // try to delete the class since it isn't needed. This won't work with config files
424                 Config::delete('storage', 'class');
425         }
426
427         // Update attachments and photos
428         if (!DBA::p("UPDATE `photo` SET `photo`.`backend-class` = SUBSTR(`photo`.`backend-class`, 22) WHERE `photo`.`backend-class` LIKE 'Friendica\\Model\\Storage\\%'") ||
429             !DBA::p("UPDATE `attach` SET `attach`.`backend-class` = SUBSTR(`attach`.`backend-class`, 22) WHERE `attach`.`backend-class` LIKE 'Friendica\\Model\\Storage\\%'")) {
430                 return Update::FAILED;
431         };
432
433         return Update::SUCCESS;
434 }