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