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