3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Core;
24 use Friendica\Database\DBA;
25 use Friendica\Database\DBStructure;
27 use Friendica\Model\Photo;
28 use Friendica\Object\Image;
29 use Friendica\Security\PermissionSet\Depository\PermissionSet;
30 use Friendica\Util\Strings;
31 use Friendica\Worker\Delivery;
38 const IMPORT_DEBUG = false;
40 private static function lastInsertId()
42 if (self::IMPORT_DEBUG) {
46 return DBA::lastInsertId();
50 * Remove columns from array $arr that aren't in table $table
52 * @param string $table Table name
53 * @param array &$arr Column=>Value array from json (by ref)
56 private static function checkCols($table, &$arr)
58 $tableColumns = DBStructure::getColumns($table);
62 // get a plain array of column names
63 foreach ($tableColumns as $tcol) {
64 $tcols[] = $tcol['Field'];
65 $ttype[$tcol['Field']] = $tcol['Type'];
67 // remove inexistent columns
68 foreach ($arr as $icol => $ival) {
69 if (!in_array($icol, $tcols)) {
74 if ($ttype[$icol] === 'datetime') {
75 $arr[$icol] = $ival ?? DBA::NULL_DATETIME;
81 * Import data into table $table
83 * @param string $table Table name
84 * @param array $arr Column=>Value array from json
88 private static function dbImportAssoc($table, $arr)
90 if (isset($arr['id'])) {
94 self::checkCols($table, $arr);
96 if (self::IMPORT_DEBUG) {
100 return DBA::insert($table, $arr);
104 * Import account file exported from mod/uexport
106 * @param array $file array from $_FILES
107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
108 * @throws \ImagickException
110 public static function importAccount($file)
112 Logger::log("Start user import from " . $file['tmp_name']);
116 2. replace old baseurl with new baseurl
117 3. import data (look at user id and contacts id)
118 4. archive non-dfrn contacts
119 5. send message to dfrn contacts
122 $account = json_decode(file_get_contents($file['tmp_name']), true);
123 if ($account === null) {
124 notice(DI::l10n()->t("Error decoding account file"));
129 if (empty($account['version'])) {
130 notice(DI::l10n()->t("Error! No version data in file! This is not a Friendica account file?"));
134 // check for username
135 // check if username matches deleted account
136 if (DBA::exists('user', ['nickname' => $account['user']['nickname']])
137 || DBA::exists('userd', ['username' => $account['user']['nickname']])) {
138 notice(DI::l10n()->t("User '%s' already exists on this server!", $account['user']['nickname']));
142 $oldbaseurl = $account['baseurl'];
143 $newbaseurl = DI::baseUrl();
145 $oldaddr = str_replace('http://', '@', Strings::normaliseLink($oldbaseurl));
146 $newaddr = str_replace('http://', '@', Strings::normaliseLink($newbaseurl));
148 if (!empty($account['profile']['addr'])) {
149 $old_handle = $account['profile']['addr'];
151 $old_handle = $account['user']['nickname'].$oldaddr;
154 // Creating a new guid to avoid problems with Diaspora
155 $account['user']['guid'] = System::createUUID();
157 $olduid = $account['user']['uid'];
159 unset($account['user']['uid']);
160 unset($account['user']['account_expired']);
161 unset($account['user']['account_expires_on']);
162 unset($account['user']['expire_notification_sent']);
164 $callback = function (&$value) use ($oldbaseurl, $oldaddr, $newbaseurl, $newaddr) {
165 $value = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $value);
168 array_walk($account['user'], $callback);
171 $r = self::dbImportAssoc('user', $account['user']);
173 Logger::log("uimport:insert user : ERROR : " . DBA::errorMessage(), Logger::INFO);
174 notice(DI::l10n()->t("User creation error"));
177 $newuid = self::lastInsertId();
179 DI::pConfig()->set($newuid, 'system', 'previous_addr', $old_handle);
182 foreach ($account['contact'] as &$contact) {
183 if ($contact['uid'] == $olduid && $contact['self'] == '1') {
184 foreach ($contact as $k => &$v) {
185 $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
186 foreach (["profile", "avatar", "micro"] as $k) {
187 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
191 if ($contact['uid'] == $olduid && $contact['self'] == '0') {
192 // set contacts 'avatar-date' to NULL_DATE to let worker to update urls
193 $contact["avatar-date"] = DBA::NULL_DATETIME;
195 switch ($contact['network']) {
197 case Protocol::DIASPORA:
198 // send relocate message (below)
205 // archive other contacts
206 $contact['archive'] = "1";
209 $contact['uid'] = $newuid;
210 $r = self::dbImportAssoc('contact', $contact);
212 Logger::log("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
215 $contact['newid'] = self::lastInsertId();
218 if ($errorcount > 0) {
219 notice(DI::l10n()->tt("%d contact not imported", "%d contacts not imported", $errorcount));
222 foreach ($account['group'] as &$group) {
223 $group['uid'] = $newuid;
224 $r = self::dbImportAssoc('group', $group);
226 Logger::log("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
228 $group['newid'] = self::lastInsertId();
232 foreach ($account['group_member'] as &$group_member) {
234 foreach ($account['group'] as $group) {
235 if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
236 $group_member['gid'] = $group['newid'];
241 foreach ($account['contact'] as $contact) {
242 if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
243 $group_member['contact-id'] = $contact['newid'];
249 $r = self::dbImportAssoc('group_member', $group_member);
251 Logger::log("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
256 foreach ($account['profile'] as &$profile) {
257 unset($profile['id']);
258 $profile['uid'] = $newuid;
260 foreach ($profile as $k => &$v) {
261 $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
262 foreach (["profile", "avatar"] as $k) {
263 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
267 if (count($account['profile']) === 1 || $profile['is-default']) {
268 $r = self::dbImportAssoc('profile', $profile);
271 Logger::log("uimport:insert profile: ERROR : " . DBA::errorMessage(), Logger::INFO);
272 notice(DI::l10n()->t("User profile creation error"));
273 DBA::delete('user', ['uid' => $newuid]);
274 DBA::delete('profile_field', ['uid' => $newuid]);
278 $profile['id'] = DBA::lastInsertId();
281 DI::profileField()->migrateFromLegacyProfile($profile);
284 $permissionSet = DI::permissionSet()->selectDefaultForUser($newuid);
286 foreach ($account['profile_fields'] ?? [] as $profile_field) {
287 $profile_field['uid'] = $newuid;
289 ///@TODO Replace with permissionset import
290 $profile_field['psid'] = $profile_field['psid'] ? $permissionSet->uid : PermissionSet::PUBLIC;
292 if (self::dbImportAssoc('profile_field', $profile_field) === false) {
293 Logger::info("uimport:insert profile field " . $profile_field['id'] . " : ERROR : " . DBA::errorMessage());
297 foreach ($account['photo'] as &$photo) {
298 $photo['uid'] = $newuid;
299 $photo['data'] = hex2bin($photo['data']);
301 $Image = new Image($photo['data'], $photo['type']);
304 $photo['uid'], $photo['contact-id'], //0
305 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
306 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
310 Logger::log("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
314 foreach ($account['pconfig'] as &$pconfig) {
315 $pconfig['uid'] = $newuid;
316 $r = self::dbImportAssoc('pconfig', $pconfig);
318 Logger::log("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
322 // send relocate messages
323 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::RELOCATION, $newuid);
325 info(DI::l10n()->t("Done. You can now login with your username and password"));
326 DI::baseUrl()->redirect('login');