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