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