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