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