]> git.mxchange.org Git - friendica.git/blob - src/Core/UserImport.php
3557b12cb8f115d56e2d92d6f9dde7b4ff340d3a
[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 define("IMPORT_DEBUG", false);
19
20 /**
21  * @brief UserImport class
22  */
23 class UserImport
24 {
25         private static function lastInsertId()
26         {
27                 if (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 = array();
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 (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                 foreach ($account['user'] as $k => &$v) {
159                         $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
160                 }
161
162                 // import user
163                 $r = self::dbImportAssoc('user', $account['user']);
164                 if ($r === false) {
165                         logger("uimport:insert user : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
166                         notice(t("User creation error"));
167                         return;
168                 }
169                 $newuid = self::lastInsertId();
170
171                 PConfig::set($newuid, 'system', 'previous_addr', $old_handle);
172
173                 // Generate a new guid for the account. Otherwise there will be problems with diaspora
174                 dba::update('user', ['guid' => generate_user_guid()], ['uid' => $newuid]);
175
176                 foreach ($account['profile'] as &$profile) {
177                         foreach ($profile as $k => &$v) {
178                                 $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
179                                 foreach (array("profile", "avatar") as $k) {
180                                         $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
181                                 }
182                         }
183                         $profile['uid'] = $newuid;
184                         $r = self::dbImportAssoc('profile', $profile);
185                         if ($r === false) {
186                                 logger("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
187                                 info(t("User profile creation error"));
188                                 dba::delete('user', array('uid' => $newuid));
189                                 return;
190                         }
191                 }
192
193                 $errorcount = 0;
194                 foreach ($account['contact'] as &$contact) {
195                         if ($contact['uid'] == $olduid && $contact['self'] == '1') {
196                                 foreach ($contact as $k => &$v) {
197                                         $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
198                                         foreach (array("profile", "avatar", "micro") as $k) {
199                                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
200                                         }
201                                 }
202                         }
203                         if ($contact['uid'] == $olduid && $contact['self'] == '0') {
204                                 // set contacts 'avatar-date' to NULL_DATE to let worker to update urls
205                                 $contact["avatar-date"] = NULL_DATE;
206
207                                 switch ($contact['network']) {
208                                         case NETWORK_DFRN:
209                                         case NETWORK_DIASPORA:
210                                                 //  send relocate message (below)
211                                                 break;
212                                         case NETWORK_FEED:
213                                         case NETWORK_MAIL:
214                                                 // Nothing to do
215                                                 break;
216                                         default:
217                                                 // archive other contacts
218                                                 $contact['archive'] = "1";
219                                 }
220                         }
221                         $contact['uid'] = $newuid;
222                         $r = self::dbImportAssoc('contact', $contact);
223                         if ($r === false) {
224                                 logger("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
225                                 $errorcount++;
226                         } else {
227                                 $contact['newid'] = self::lastInsertId();
228                         }
229                 }
230                 if ($errorcount > 0) {
231                         notice(sprintf(tt("%d contact not imported", "%d contacts not imported", $errorcount), $errorcount));
232                 }
233
234                 foreach ($account['group'] as &$group) {
235                         $group['uid'] = $newuid;
236                         $r = self::dbImportAssoc('group', $group);
237                         if ($r === false) {
238                                 logger("uimport:insert group " . $group['name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
239                         } else {
240                                 $group['newid'] = self::lastInsertId();
241                         }
242                 }
243
244                 foreach ($account['group_member'] as &$group_member) {
245                         $import = 0;
246                         foreach ($account['group'] as $group) {
247                                 if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
248                                         $group_member['gid'] = $group['newid'];
249                                         $import++;
250                                         break;
251                                 }
252                         }
253                         foreach ($account['contact'] as $contact) {
254                                 if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
255                                         $group_member['contact-id'] = $contact['newid'];
256                                         $import++;
257                                         break;
258                                 }
259                         }
260                         if ($import == 2) {
261                                 $r = self::dbImportAssoc('group_member', $group_member);
262                                 if ($r === false) {
263                                         logger("uimport:insert group member " . $group_member['id'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
264                                 }
265                         }
266                 }
267
268                 foreach ($account['photo'] as &$photo) {
269                         $photo['uid'] = $newuid;
270                         $photo['data'] = hex2bin($photo['data']);
271
272                         $Image = new Image($photo['data'], $photo['type']);
273                         $r = Photo::store(
274                                 $Image,
275                                 $photo['uid'], $photo['contact-id'], //0
276                                 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
277                                 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
278                         );
279
280                         if ($r === false) {
281                                 logger("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
282                         }
283                 }
284
285                 foreach ($account['pconfig'] as &$pconfig) {
286                         $pconfig['uid'] = $newuid;
287                         $r = self::dbImportAssoc('pconfig', $pconfig);
288                         if ($r === false) {
289                                 logger("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
290                         }
291                 }
292
293                 // send relocate messages
294                 Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $newuid);
295
296                 info(t("Done. You can now login with your username and password"));
297                 goaway(System::baseUrl() . "/login");
298         }
299 }