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