3 * @file src/Core/UserImport.php
5 namespace Friendica\Core;
8 use Friendica\Database\DBA;
9 use Friendica\Database\DBStructure;
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;
23 const IMPORT_DEBUG = false;
25 private static function lastInsertId()
27 if (self::IMPORT_DEBUG) {
31 return DBA::lastInsertId();
35 * Remove columns from array $arr that aren't in table $table
37 * @param string $table Table name
38 * @param array &$arr Column=>Value array from json (by ref)
41 private static function checkCols($table, &$arr)
43 $tableColumns = DBStructure::getColumns($table);
47 // get a plain array of column names
48 foreach ($tableColumns as $tcol) {
49 $tcols[] = $tcol['Field'];
50 $ttype[$tcol['Field']] = $tcol['Type'];
52 // remove inexistent columns
53 foreach ($arr as $icol => $ival) {
54 if (!in_array($icol, $tcols)) {
59 if ($ttype[$icol] === 'datetime') {
60 $arr[$icol] = $ival ?? DBA::NULL_DATETIME;
66 * Import data into table $table
68 * @param string $table Table name
69 * @param array $arr Column=>Value array from json
73 private static function dbImportAssoc($table, $arr)
75 if (isset($arr['id'])) {
79 self::checkCols($table, $arr);
81 if (self::IMPORT_DEBUG) {
85 return DBA::insert($table, $arr);
89 * Import account file exported from mod/uexport
91 * @param array $file array from $_FILES
92 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
93 * @throws \ImagickException
95 public static function importAccount($file)
97 Logger::log("Start user import from " . $file['tmp_name']);
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
107 $account = json_decode(file_get_contents($file['tmp_name']), true);
108 if ($account === null) {
109 notice(DI::l10n()->t("Error decoding account file"));
114 if (empty($account['version'])) {
115 notice(DI::l10n()->t("Error! No version data in file! This is not a Friendica account file?"));
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']));
127 $oldbaseurl = $account['baseurl'];
128 $newbaseurl = DI::baseUrl();
130 $oldaddr = str_replace('http://', '@', Strings::normaliseLink($oldbaseurl));
131 $newaddr = str_replace('http://', '@', Strings::normaliseLink($newbaseurl));
133 if (!empty($account['profile']['addr'])) {
134 $old_handle = $account['profile']['addr'];
136 $old_handle = $account['user']['nickname'].$oldaddr;
139 // Creating a new guid to avoid problems with Diaspora
140 $account['user']['guid'] = System::createUUID();
142 $olduid = $account['user']['uid'];
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']);
149 $callback = function (&$value) use ($oldbaseurl, $oldaddr, $newbaseurl, $newaddr) {
150 $value = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $value);
153 array_walk($account['user'], $callback);
156 $r = self::dbImportAssoc('user', $account['user']);
158 Logger::log("uimport:insert user : ERROR : " . DBA::errorMessage(), Logger::INFO);
159 notice(DI::l10n()->t("User creation error"));
162 $newuid = self::lastInsertId();
164 DI::pConfig()->set($newuid, 'system', 'previous_addr', $old_handle);
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);
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;
180 switch ($contact['network']) {
182 case Protocol::DIASPORA:
183 // send relocate message (below)
190 // archive other contacts
191 $contact['archive'] = "1";
194 $contact['uid'] = $newuid;
195 $r = self::dbImportAssoc('contact', $contact);
197 Logger::log("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
200 $contact['newid'] = self::lastInsertId();
203 if ($errorcount > 0) {
204 notice(DI::l10n()->tt("%d contact not imported", "%d contacts not imported", $errorcount));
207 foreach ($account['group'] as &$group) {
208 $group['uid'] = $newuid;
209 $r = self::dbImportAssoc('group', $group);
211 Logger::log("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
213 $group['newid'] = self::lastInsertId();
217 foreach ($account['group_member'] as &$group_member) {
219 foreach ($account['group'] as $group) {
220 if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
221 $group_member['gid'] = $group['newid'];
226 foreach ($account['contact'] as $contact) {
227 if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
228 $group_member['contact-id'] = $contact['newid'];
234 $r = self::dbImportAssoc('group_member', $group_member);
236 Logger::log("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
241 foreach ($account['profile'] as &$profile) {
242 unset($profile['id']);
243 $profile['uid'] = $newuid;
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);
252 if (count($account['profile']) === 1 || $profile['is-default']) {
253 $r = self::dbImportAssoc('profile', $profile);
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]);
263 $profile['id'] = DBA::lastInsertId();
266 DI::profileField()->migrateFromLegacyProfile($profile);
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);
274 foreach ($account['profile_fields'] ?? [] as $profile_field) {
275 $profile_field['uid'] = $newuid;
277 ///@TODO Replace with permissionset import
278 $profile_field['psid'] = $profile_field['psid'] ? $self_psid : PermissionSet::PUBLIC;
280 if (self::dbImportAssoc('profile_field', $profile_field) === false) {
281 Logger::info("uimport:insert profile field " . $profile_field['id'] . " : ERROR : " . DBA::errorMessage());
285 foreach ($account['photo'] as &$photo) {
286 $photo['uid'] = $newuid;
287 $photo['data'] = hex2bin($photo['data']);
289 $Image = new Image($photo['data'], $photo['type']);
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']
298 Logger::log("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
302 foreach ($account['pconfig'] as &$pconfig) {
303 $pconfig['uid'] = $newuid;
304 $r = self::dbImportAssoc('pconfig', $pconfig);
306 Logger::log("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
310 // send relocate messages
311 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::RELOCATION, $newuid);
313 info(DI::l10n()->t("Done. You can now login with your username and password"));
314 DI::baseUrl()->redirect('login');