]> git.mxchange.org Git - friendica.git/blob - src/Core/UserImport.php
Remove confirm template obsolete uses (except for contacts)
[friendica.git] / src / Core / UserImport.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  */
21
22 namespace Friendica\Core;
23
24 use Friendica\App;
25 use Friendica\Database\DBA;
26 use Friendica\Database\DBStructure;
27 use Friendica\DI;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Photo;
30 use Friendica\Object\Image;
31 use Friendica\Repository\PermissionSet;
32 use Friendica\Util\Strings;
33 use Friendica\Worker\Delivery;
34
35 /**
36  * UserImport class
37  */
38 class UserImport
39 {
40         const IMPORT_DEBUG = false;
41
42         private static function lastInsertId()
43         {
44                 if (self::IMPORT_DEBUG) {
45                         return 1;
46                 }
47
48                 return DBA::lastInsertId();
49         }
50
51         /**
52          * Remove columns from array $arr that aren't in table $table
53          *
54          * @param string $table Table name
55          * @param array &$arr   Column=>Value array from json (by ref)
56          * @throws \Exception
57          */
58         private static function checkCols($table, &$arr)
59         {
60                 $tableColumns = DBStructure::getColumns($table);
61
62                 $tcols = [];
63                 $ttype = [];
64                 // get a plain array of column names
65                 foreach ($tableColumns as $tcol) {
66                         $tcols[] = $tcol['Field'];
67                         $ttype[$tcol['Field']] = $tcol['Type'];
68                 }
69                 // remove inexistent columns
70                 foreach ($arr as $icol => $ival) {
71                         if (!in_array($icol, $tcols)) {
72                                 unset($arr[$icol]);
73                                 continue;
74                         }
75
76                         if ($ttype[$icol] === 'datetime') {
77                                 $arr[$icol] = $ival ?? DBA::NULL_DATETIME;
78                         }
79                 }
80         }
81
82         /**
83          * Import data into table $table
84          *
85          * @param string $table Table name
86          * @param array  $arr   Column=>Value array from json
87          * @return array|bool
88          * @throws \Exception
89          */
90         private static function dbImportAssoc($table, $arr)
91         {
92                 if (isset($arr['id'])) {
93                         unset($arr['id']);
94                 }
95
96                 self::checkCols($table, $arr);
97
98                 if (self::IMPORT_DEBUG) {
99                         return true;
100                 }
101
102                 return DBA::insert($table, $arr);
103         }
104
105         /**
106          * Import account file exported from mod/uexport
107          *
108          * @param array $file array from $_FILES
109          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110          * @throws \ImagickException
111          */
112         public static function importAccount($file)
113         {
114                 Logger::log("Start user import from " . $file['tmp_name']);
115                 /*
116                 STEPS
117                 1. checks
118                 2. replace old baseurl with new baseurl
119                 3. import data (look at user id and contacts id)
120                 4. archive non-dfrn contacts
121                 5. send message to dfrn contacts
122                 */
123
124                 $account = json_decode(file_get_contents($file['tmp_name']), true);
125                 if ($account === null) {
126                         notice(DI::l10n()->t("Error decoding account file"));
127                         return;
128                 }
129
130
131                 if (empty($account['version'])) {
132                         notice(DI::l10n()->t("Error! No version data in file! This is not a Friendica account file?"));
133                         return;
134                 }
135
136                 // check for username
137                 // check if username matches deleted account
138                 if (DBA::exists('user', ['nickname' => $account['user']['nickname']])
139                         || DBA::exists('userd', ['username' => $account['user']['nickname']])) {
140                         notice(DI::l10n()->t("User '%s' already exists on this server!", $account['user']['nickname']));
141                         return;
142                 }
143
144                 $oldbaseurl = $account['baseurl'];
145                 $newbaseurl = DI::baseUrl();
146
147                 $oldaddr = str_replace('http://', '@', Strings::normaliseLink($oldbaseurl));
148                 $newaddr = str_replace('http://', '@', Strings::normaliseLink($newbaseurl));
149
150                 if (!empty($account['profile']['addr'])) {
151                         $old_handle = $account['profile']['addr'];
152                 } else {
153                         $old_handle = $account['user']['nickname'].$oldaddr;
154                 }
155
156                 // Creating a new guid to avoid problems with Diaspora
157                 $account['user']['guid'] = System::createUUID();
158
159                 $olduid = $account['user']['uid'];
160
161                 unset($account['user']['uid']);
162                 unset($account['user']['account_expired']);
163                 unset($account['user']['account_expires_on']);
164                 unset($account['user']['expire_notification_sent']);
165
166                 $callback = function (&$value) use ($oldbaseurl, $oldaddr, $newbaseurl, $newaddr) {
167                         $value =  str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $value);
168                 };
169
170                 array_walk($account['user'], $callback);
171
172                 // import user
173                 $r = self::dbImportAssoc('user', $account['user']);
174                 if ($r === false) {
175                         Logger::log("uimport:insert user : ERROR : " . DBA::errorMessage(), Logger::INFO);
176                         notice(DI::l10n()->t("User creation error"));
177                         return;
178                 }
179                 $newuid = self::lastInsertId();
180
181                 DI::pConfig()->set($newuid, 'system', 'previous_addr', $old_handle);
182
183                 $errorcount = 0;
184                 foreach ($account['contact'] as &$contact) {
185                         if ($contact['uid'] == $olduid && $contact['self'] == '1') {
186                                 foreach ($contact as $k => &$v) {
187                                         $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
188                                         foreach (["profile", "avatar", "micro"] as $k) {
189                                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
190                                         }
191                                 }
192                         }
193                         if ($contact['uid'] == $olduid && $contact['self'] == '0') {
194                                 // set contacts 'avatar-date' to NULL_DATE to let worker to update urls
195                                 $contact["avatar-date"] = DBA::NULL_DATETIME;
196
197                                 switch ($contact['network']) {
198                                         case Protocol::DFRN:
199                                         case Protocol::DIASPORA:
200                                                 //  send relocate message (below)
201                                                 break;
202                                         case Protocol::FEED:
203                                         case Protocol::MAIL:
204                                                 // Nothing to do
205                                                 break;
206                                         default:
207                                                 // archive other contacts
208                                                 $contact['archive'] = "1";
209                                 }
210                         }
211                         $contact['uid'] = $newuid;
212                         $r = self::dbImportAssoc('contact', $contact);
213                         if ($r === false) {
214                                 Logger::log("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
215                                 $errorcount++;
216                         } else {
217                                 $contact['newid'] = self::lastInsertId();
218                         }
219                 }
220                 if ($errorcount > 0) {
221                         notice(DI::l10n()->tt("%d contact not imported", "%d contacts not imported", $errorcount));
222                 }
223
224                 foreach ($account['group'] as &$group) {
225                         $group['uid'] = $newuid;
226                         $r = self::dbImportAssoc('group', $group);
227                         if ($r === false) {
228                                 Logger::log("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
229                         } else {
230                                 $group['newid'] = self::lastInsertId();
231                         }
232                 }
233
234                 foreach ($account['group_member'] as &$group_member) {
235                         $import = 0;
236                         foreach ($account['group'] as $group) {
237                                 if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
238                                         $group_member['gid'] = $group['newid'];
239                                         $import++;
240                                         break;
241                                 }
242                         }
243                         foreach ($account['contact'] as $contact) {
244                                 if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
245                                         $group_member['contact-id'] = $contact['newid'];
246                                         $import++;
247                                         break;
248                                 }
249                         }
250                         if ($import == 2) {
251                                 $r = self::dbImportAssoc('group_member', $group_member);
252                                 if ($r === false) {
253                                         Logger::log("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
254                                 }
255                         }
256                 }
257
258                 foreach ($account['profile'] as &$profile) {
259                         unset($profile['id']);
260                         $profile['uid'] = $newuid;
261
262                         foreach ($profile as $k => &$v) {
263                                 $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
264                                 foreach (["profile", "avatar"] as $k) {
265                                         $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
266                                 }
267                         }
268
269                         if (count($account['profile']) === 1 || $profile['is-default']) {
270                                 $r = self::dbImportAssoc('profile', $profile);
271
272                                 if ($r === false) {
273                                         Logger::log("uimport:insert profile: ERROR : " . DBA::errorMessage(), Logger::INFO);
274                                         notice(DI::l10n()->t("User profile creation error"));
275                                         DBA::delete('user', ['uid' => $newuid]);
276                                         DBA::delete('profile_field', ['uid' => $newuid]);
277                                         return;
278                                 }
279
280                                 $profile['id'] = DBA::lastInsertId();
281                         }
282
283                         DI::profileField()->migrateFromLegacyProfile($profile);
284                 }
285
286                 ///@TODO Replace with permissionset import
287                 $self_contact = Contact::selectFirst(['id'], ['uid' => $newuid, 'self' => true]);
288                 $allow_cid = DI::aclFormatter()->toString($self_contact['id']);
289                 $self_psid = DI::permissionSet()->getIdFromACL($newuid, $allow_cid);
290
291                 foreach ($account['profile_fields'] ?? [] as $profile_field) {
292                         $profile_field['uid'] = $newuid;
293
294                         ///@TODO Replace with permissionset import
295                         $profile_field['psid'] = $profile_field['psid'] ? $self_psid : PermissionSet::PUBLIC;
296
297                         if (self::dbImportAssoc('profile_field', $profile_field) === false) {
298                                 Logger::info("uimport:insert profile field " . $profile_field['id'] . " : ERROR : " . DBA::errorMessage());
299                         }
300                 }
301
302                 foreach ($account['photo'] as &$photo) {
303                         $photo['uid'] = $newuid;
304                         $photo['data'] = hex2bin($photo['data']);
305
306                         $Image = new Image($photo['data'], $photo['type']);
307                         $r = Photo::store(
308                                 $Image,
309                                 $photo['uid'], $photo['contact-id'], //0
310                                 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
311                                 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
312                         );
313
314                         if ($r === false) {
315                                 Logger::log("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
316                         }
317                 }
318
319                 foreach ($account['pconfig'] as &$pconfig) {
320                         $pconfig['uid'] = $newuid;
321                         $r = self::dbImportAssoc('pconfig', $pconfig);
322                         if ($r === false) {
323                                 Logger::log("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
324                         }
325                 }
326
327                 // send relocate messages
328                 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::RELOCATION, $newuid);
329
330                 info(DI::l10n()->t("Done. You can now login with your username and password"));
331                 DI::baseUrl()->redirect('login');
332         }
333 }