Empty lines removed
[friendica.git/.git] / update.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * Automatic post-databse structure change updates
21  *
22  * These functions are responsible for doing critical post update changes to the data (not the structure) in the database.
23  *
24  * Database structure changes are done in static/dbstructure.config.php
25  *
26  * For non-critical database migrations, please add a method in the Database\PostUpdate class
27  *
28  * If there is a need for a post update 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 use Friendica\Core\Addon;
44 use Friendica\Core\Logger;
45 use Friendica\Core\Update;
46 use Friendica\Core\Worker;
47 use Friendica\Database\DBA;
48 use Friendica\Database\DBStructure;
49 use Friendica\DI;
50 use Friendica\Model\Contact;
51 use Friendica\Model\GContact;
52 use Friendica\Model\Item;
53 use Friendica\Model\User;
54 use Friendica\Model\Storage;
55 use Friendica\Util\DateTimeFormat;
56 use Friendica\Worker\Delivery;
57
58 function update_1179()
59 {
60         if (DI::config()->get('system', 'no_community_page')) {
61                 DI::config()->set('system', 'community_page_style', CP_NO_COMMUNITY_PAGE);
62         }
63
64         // Update the central item storage with uid=0
65         Worker::add(PRIORITY_LOW, "threadupdate");
66
67         return Update::SUCCESS;
68 }
69
70 function update_1181()
71 {
72
73         // Fill the new fields in the term table.
74         // deactivated, the "term" table is deprecated
75         // Worker::add(PRIORITY_LOW, "TagUpdate");
76
77         return Update::SUCCESS;
78 }
79
80 function update_1189()
81 {
82
83         if (strlen(DI::config()->get('system', 'directory_submit_url')) &&
84                 !strlen(DI::config()->get('system', 'directory'))) {
85                 DI::config()->set('system', 'directory', dirname(DI::config()->get('system', 'directory_submit_url')));
86                 DI::config()->delete('system', 'directory_submit_url');
87         }
88
89         return Update::SUCCESS;
90 }
91
92 function update_1191()
93 {
94         DI::config()->set('system', 'maintenance', 1);
95
96         if (Addon::isEnabled('forumlist')) {
97                 Addon::uninstall('forumlist');
98         }
99
100         // select old formlist addon entries
101         $r = q("SELECT `uid`, `cat`, `k`, `v` FROM `pconfig` WHERE `cat` = '%s' ",
102                 DBA::escape('forumlist')
103         );
104
105         // convert old forumlist addon entries in new config entries
106         if (DBA::isResult($r)) {
107                 foreach ($r as $rr) {
108                         $uid = $rr['uid'];
109                         $family = $rr['cat'];
110                         $key = $rr['k'];
111                         $value = $rr['v'];
112
113                         if ($key === 'randomise') {
114                                 DI::pConfig()->delete($uid, $family, $key);
115                         }
116
117                         if ($key === 'show_on_profile') {
118                                 if ($value) {
119                                         DI::pConfig()->set($uid, 'feature', 'forumlist_profile', $value);
120                                 }
121
122                                 DI::pConfig()->delete($uid, $family, $key);
123                         }
124
125                         if ($key === 'show_on_network') {
126                                 if ($value) {
127                                         DI::pConfig()->set($uid, 'feature', 'forumlist_widget', $value);
128                                 }
129
130                                 DI::pConfig()->delete($uid, $family, $key);
131                         }
132                 }
133         }
134
135         DI::config()->set('system', 'maintenance', 0);
136
137         return Update::SUCCESS;
138 }
139
140 function update_1203()
141 {
142         $r = q("UPDATE `user` SET `account-type` = %d WHERE `page-flags` IN (%d, %d)",
143                 DBA::escape(User::ACCOUNT_TYPE_COMMUNITY),
144                 DBA::escape(User::PAGE_FLAGS_COMMUNITY),
145                 DBA::escape(User::PAGE_FLAGS_PRVGROUP)
146         );
147 }
148
149 function update_1244()
150 {
151         // Sets legacy_password for all legacy hashes
152         DBA::update('user', ['legacy_password' => true], ['SUBSTR(password, 1, 4) != "$2y$"']);
153
154         // All legacy hashes are re-hashed using the new secure hashing function
155         $stmt = DBA::select('user', ['uid', 'password'], ['legacy_password' => true]);
156         while ($user = DBA::fetch($stmt)) {
157                 DBA::update('user', ['password' => User::hashPassword($user['password'])], ['uid' => $user['uid']]);
158         }
159
160         // Logged in users are forcibly logged out
161         DBA::delete('session', ['1 = 1']);
162
163         return Update::SUCCESS;
164 }
165
166 function update_1245()
167 {
168         $rino = DI::config()->get('system', 'rino_encrypt');
169
170         if (!$rino) {
171                 return Update::SUCCESS;
172         }
173
174         DI::config()->set('system', 'rino_encrypt', 1);
175
176         return Update::SUCCESS;
177 }
178
179 function update_1247()
180 {
181         // Removing hooks with the old name
182         DBA::e("DELETE FROM `hook`
183 WHERE `hook` LIKE 'plugin_%'");
184
185         // Make sure we install the new renamed ones
186         Addon::reload();
187 }
188
189 function update_1260()
190 {
191         DI::config()->set('system', 'maintenance', 1);
192         DI::config()->set(
193                 'system',
194                 'maintenance_reason',
195                 DI::l10n()->t(
196                         '%s: Updating author-id and owner-id in item and thread table. ',
197                         DateTimeFormat::utcNow().' '.date('e')
198                 )
199         );
200
201         $items = DBA::p("SELECT `id`, `owner-link`, `owner-name`, `owner-avatar`, `network` FROM `item`
202                 WHERE `owner-id` = 0 AND `owner-link` != ''");
203         while ($item = DBA::fetch($items)) {
204                 $contact = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
205                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
206                 $cid = Contact::getIdForURL($item['owner-link'], 0, false, $contact);
207                 if (empty($cid)) {
208                         continue;
209                 }
210                 Item::update(['owner-id' => $cid], ['id' => $item['id']]);
211         }
212         DBA::close($items);
213
214         DBA::e("UPDATE `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`id`
215                 SET `thread`.`owner-id` = `item`.`owner-id` WHERE `thread`.`owner-id` = 0");
216
217         $items = DBA::p("SELECT `id`, `author-link`, `author-name`, `author-avatar`, `network` FROM `item`
218                 WHERE `author-id` = 0 AND `author-link` != ''");
219         while ($item = DBA::fetch($items)) {
220                 $contact = ['url' => $item['author-link'], 'name' => $item['author-name'],
221                         'photo' => $item['author-avatar'], 'network' => $item['network']];
222                 $cid = Contact::getIdForURL($item['author-link'], 0, false, $contact);
223                 if (empty($cid)) {
224                         continue;
225                 }
226                 Item::update(['author-id' => $cid], ['id' => $item['id']]);
227         }
228         DBA::close($items);
229
230         DBA::e("UPDATE `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`id`
231                 SET `thread`.`author-id` = `item`.`author-id` WHERE `thread`.`author-id` = 0");
232
233         DI::config()->set('system', 'maintenance', 0);
234         return Update::SUCCESS;
235 }
236
237 function update_1261()
238 {
239         // This fixes the results of an issue in the develop branch of 2018-05.
240         DBA::update('contact', ['blocked' => false, 'pending' => false], ['uid' => 0, 'blocked' => true, 'pending' => true]);
241         return Update::SUCCESS;
242 }
243
244 function update_1278()
245 {
246         DI::config()->set('system', 'maintenance', 1);
247         DI::config()->set(
248                 'system',
249                 'maintenance_reason',
250                 DI::l10n()->t(
251                         '%s: Updating post-type.',
252                         DateTimeFormat::utcNow().' '.date('e')
253                 )
254         );
255
256         Item::update(['post-type' => Item::PT_PAGE], ['bookmark' => true]);
257         Item::update(['post-type' => Item::PT_PERSONAL_NOTE], ['type' => 'note']);
258
259         DI::config()->set('system', 'maintenance', 0);
260
261         return Update::SUCCESS;
262 }
263
264 function update_1288()
265 {
266         // Updates missing `uri-id` values
267
268         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");
269         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");
270
271         return Update::SUCCESS;
272 }
273
274 // Post-update script of PR 5751
275 function update_1298()
276 {
277         $keys = ['gender', 'marital', 'sexual'];
278         foreach ($keys as $translateKey) {
279                 $allData = DBA::select('profile', ['id', $translateKey]);
280                 $allLangs = DI::l10n()->getAvailableLanguages();
281                 $success = 0;
282                 $fail = 0;
283                 foreach ($allData as $key => $data) {
284                         $toTranslate = $data[$translateKey];
285                         if ($toTranslate != '') {
286                                 foreach ($allLangs as $key => $lang) {
287                                         $a = new \stdClass();
288                                         $a->strings = [];
289
290                                         // First we get the the localizations
291                                         if (file_exists("view/lang/$lang/strings.php")) {
292                                                 include "view/lang/$lang/strings.php";
293                                         }
294                                         if (file_exists("addon/morechoice/lang/$lang/strings.php")) {
295                                                 include "addon/morechoice/lang/$lang/strings.php";
296                                         }
297
298                                         $localizedStrings = $a->strings;
299                                         unset($a);
300
301                                         $key = array_search($toTranslate, $localizedStrings);
302                                         if ($key !== false) {
303                                                 break;
304                                         }
305
306                                         // defaulting to empty string
307                                         $key = '';
308                                 }
309
310                                 if ($key == '') {
311                                         $fail++;
312                                 } else {
313                                         DBA::update('profile', [$translateKey => $key], ['id' => $data['id']]);
314                                         Logger::notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key,
315                                                 'was' => $data[$translateKey]]);
316                                         Worker::add(PRIORITY_LOW, 'ProfileUpdate', $data['id']);
317                                         Contact::updateSelfFromUserID($data['id']);
318                                         GContact::updateForUser($data['id']);
319                                         $success++;
320                                 }
321                         }
322                 }
323
324                 Logger::notice($translateKey . " fix completed", ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]);
325         }
326         return Update::SUCCESS;
327 }
328
329 function update_1309()
330 {
331         $queue = DBA::select('queue', ['id', 'cid', 'guid']);
332         while ($entry = DBA::fetch($queue)) {
333                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $entry['cid']]);
334                 if (!DBA::isResult($contact)) {
335                         continue;
336                 }
337
338                 $item = Item::selectFirst(['id', 'gravity'], ['uid' => $contact['uid'], 'guid' => $entry['guid']]);
339                 if (!DBA::isResult($item)) {
340                         continue;
341                 }
342
343                 $deliver_options = ['priority' => PRIORITY_MEDIUM, 'dont_fork' => true];
344                 Worker::add($deliver_options, 'Delivery', Delivery::POST, $item['id'], $entry['cid']);
345                 Logger::info('Added delivery worker', ['item' => $item['id'], 'contact' => $entry['cid']]);
346                 DBA::delete('queue', ['id' => $entry['id']]);
347         }
348         return Update::SUCCESS;
349 }
350
351 function update_1315()
352 {
353         DBA::delete('item-delivery-data', ['postopts' => '', 'inform' => '', 'queue_count' => 0, 'queue_done' => 0]);
354         return Update::SUCCESS;
355 }
356
357 function update_1318()
358 {
359         DBA::update('profile', ['marital' => "In a relation"], ['marital' => "Unavailable"]);
360         DBA::update('profile', ['marital' => "Single"], ['marital' => "Available"]);
361
362         Worker::add(PRIORITY_LOW, 'ProfileUpdate');
363         return Update::SUCCESS;
364 }
365
366 function update_1323()
367 {
368         $users = DBA::select('user', ['uid']);
369         while ($user = DBA::fetch($users)) {
370                 Contact::updateSelfFromUserID($user['uid']);
371         }
372         DBA::close($users);
373
374         return Update::SUCCESS;
375 }
376
377 function update_1327()
378 {
379         $contacts = DBA::select('contact', ['uid', 'id', 'blocked', 'readonly'], ["`uid` != ? AND (`blocked` OR `readonly`) AND NOT `pending`", 0]);
380         while ($contact = DBA::fetch($contacts)) {
381                 Contact::setBlockedForUser($contact['id'], $contact['uid'], $contact['blocked']);
382                 Contact::setIgnoredForUser($contact['id'], $contact['uid'], $contact['readonly']);
383         }
384         DBA::close($contacts);
385
386         return Update::SUCCESS;
387 }
388
389 function update_1330()
390 {
391         $currStorage = DI::config()->get('storage', 'class', '');
392
393         // set the name of the storage instead of the classpath as config
394         if (!empty($currStorage)) {
395                 /** @var Storage\IStorage $currStorage */
396                 if (!DI::config()->set('storage', 'name', $currStorage::getName())) {
397                         return Update::FAILED;
398                 }
399
400                 // try to delete the class since it isn't needed. This won't work with config files
401                 DI::config()->delete('storage', 'class');
402         }
403
404         // Update attachments and photos
405         if (!DBA::p("UPDATE `photo` SET `photo`.`backend-class` = SUBSTR(`photo`.`backend-class`, 25) WHERE `photo`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'") ||
406             !DBA::p("UPDATE `attach` SET `attach`.`backend-class` = SUBSTR(`attach`.`backend-class`, 25) WHERE `attach`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'")) {
407                 return Update::FAILED;
408         };
409
410         return Update::SUCCESS;
411 }
412
413 function update_1332()
414 {
415         $condition = ["`is-default` IS NOT NULL"];
416         $profiles = DBA::select('profile', [], $condition);
417
418         while ($profile = DBA::fetch($profiles)) {
419                 DI::profileField()->migrateFromLegacyProfile($profile);
420         }
421         DBA::close($profiles);
422
423         DBA::update('contact', ['profile-id' => null], ['`profile-id` IS NOT NULL']);
424
425         return Update::SUCCESS;
426 }
427
428 function update_1347()
429 {
430         foreach (Item::ACTIVITIES as $index => $activity) {
431                 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], true);
432         }
433
434         return Update::SUCCESS;
435 }
436
437 function pre_update_1348()
438 {
439         if (!DBA::exists('contact', ['id' => 0])) {
440                 DBA::insert('contact', ['nurl' => '']);
441                 $lastid = DBA::lastInsertId();
442                 if ($lastid != 0) {
443                         DBA::update('contact', ['id' => 0], ['id' => $lastid]);
444                 }
445         }
446
447         // The tables "permissionset" and "tag" could or could not exist during the update.
448         // This depends upon the previous version. Depending upon this situation we have to add
449         // the "0" values before adding the foreign keys - or after would be sufficient.
450
451         update_1348();
452
453         return Update::SUCCESS;
454 }
455
456 function update_1348()
457 {
458         // Insert a permissionset with id=0
459         // Inserting it without an ID and then changing the value to 0 tricks the auto increment
460         if (!DBA::exists('permissionset', ['id' => 0])) {
461                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);       
462                 $lastid = DBA::lastInsertId();
463                 if ($lastid != 0) {
464                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
465                 }
466         }
467
468         if (!DBA::exists('tag', ['id' => 0])) {
469                 DBA::insert('tag', ['name' => '']);
470                 $lastid = DBA::lastInsertId();
471                 if ($lastid != 0) {
472                         DBA::update('tag', ['id' => 0], ['id' => $lastid]);
473                 }
474         }
475
476         return Update::SUCCESS;
477 }
478
479 function update_1349()
480 {
481         $correct = true;
482         foreach (Item::ACTIVITIES as $index => $activity) {
483                 if (!DBA::exists('verb', ['id' => $index + 1, 'name' => $activity])) {
484                         $correct = false;
485                 }
486         }
487
488         if (!$correct) {
489                 // The update failed - but it cannot be recovered, since the data doesn't match our expectation
490                 // This means that we can't use this "shortcut" to fill the "vid" field and we have to rely upon
491                 // the postupdate. This is not fatal, but means that it will take some longer time for the system
492                 // to fill all data.
493                 return Update::SUCCESS;
494         }
495
496         if (!DBA::e("UPDATE `item` INNER JOIN `item-activity` ON `item`.`uri-id` = `item-activity`.`uri-id`
497                 SET `vid` = `item-activity`.`activity` + 1 WHERE `gravity` = ? AND (`vid` IS NULL OR `vid` = 0)", GRAVITY_ACTIVITY)) {
498                 return Update::FAILED;
499         }
500
501         return Update::SUCCESS;
502 }
503
504 function update_1351()
505 {
506         if (!DBA::e("UPDATE `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`id` SET `thread`.`uri-id` = `item`.`uri-id`")) {
507                 return Update::FAILED;
508         }
509
510         return Update::SUCCESS;
511 }
512
513 function pre_update_1354()
514 {
515         if (DBStructure::existsColumn('contact', ['ffi_keyword_blacklist'])
516                 && !DBA::e("ALTER TABLE `contact` CHANGE `ffi_keyword_blacklist` `ffi_keyword_denylist` text null")) {
517                 return Update::FAILED;
518         }
519
520         return Update::SUCCESS;
521 }