]> git.mxchange.org Git - friendica.git/blob - src/Core/UserImport.php
Remove api test pconfig debug
[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::checkCols($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                 // check if username matches deleted account
116                 if (dba::exists('user', ['nickname' => $account['user']['nickname']])
117                         || dba::exists('userd', ['username' => $account['user']['nickname']])) {
118                         notice(L10n::t("User '%s' already exists on this server!", $account['user']['nickname']));
119                         return;
120                 }
121
122                 $oldbaseurl = $account['baseurl'];
123                 $newbaseurl = System::baseUrl();
124
125                 $oldaddr = str_replace('http://', '@', normalise_link($oldbaseurl));
126                 $newaddr = str_replace('http://', '@', normalise_link($newbaseurl));
127
128                 if (!empty($account['profile']['addr'])) {
129                         $old_handle = $account['profile']['addr'];
130                 } else {
131                         $old_handle = $account['user']['nickname'].$oldaddr;
132                 }
133
134                 $olduid = $account['user']['uid'];
135
136                 unset($account['user']['uid']);
137                 unset($account['user']['account_expired']);
138                 unset($account['user']['account_expires_on']);
139                 unset($account['user']['expire_notification_sent']);
140
141                 $callback = function (&$value) use ($oldbaseurl, $oldaddr, $newbaseurl, $newaddr) {
142                         $value =  str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $value);
143                 };
144
145                 array_walk($account['user'], $callback);
146
147                 // import user
148                 $r = self::dbImportAssoc('user', $account['user']);
149                 if ($r === false) {
150                         logger("uimport:insert user : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
151                         notice(L10n::t("User creation error"));
152                         return;
153                 }
154                 $newuid = self::lastInsertId();
155
156                 PConfig::set($newuid, 'system', 'previous_addr', $old_handle);
157
158                 foreach ($account['profile'] as &$profile) {
159                         foreach ($profile as $k => &$v) {
160                                 $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
161                                 foreach (["profile", "avatar"] as $k) {
162                                         $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
163                                 }
164                         }
165                         $profile['uid'] = $newuid;
166                         $r = self::dbImportAssoc('profile', $profile);
167                         if ($r === false) {
168                                 logger("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
169                                 info(L10n::t("User profile creation error"));
170                                 dba::delete('user', ['uid' => $newuid]);
171                                 return;
172                         }
173                 }
174
175                 $errorcount = 0;
176                 foreach ($account['contact'] as &$contact) {
177                         if ($contact['uid'] == $olduid && $contact['self'] == '1') {
178                                 foreach ($contact as $k => &$v) {
179                                         $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
180                                         foreach (["profile", "avatar", "micro"] as $k) {
181                                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
182                                         }
183                                 }
184                         }
185                         if ($contact['uid'] == $olduid && $contact['self'] == '0') {
186                                 // set contacts 'avatar-date' to NULL_DATE to let worker to update urls
187                                 $contact["avatar-date"] = NULL_DATE;
188
189                                 switch ($contact['network']) {
190                                         case NETWORK_DFRN:
191                                         case NETWORK_DIASPORA:
192                                                 //  send relocate message (below)
193                                                 break;
194                                         case NETWORK_FEED:
195                                         case NETWORK_MAIL:
196                                                 // Nothing to do
197                                                 break;
198                                         default:
199                                                 // archive other contacts
200                                                 $contact['archive'] = "1";
201                                 }
202                         }
203                         $contact['uid'] = $newuid;
204                         $r = self::dbImportAssoc('contact', $contact);
205                         if ($r === false) {
206                                 logger("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
207                                 $errorcount++;
208                         } else {
209                                 $contact['newid'] = self::lastInsertId();
210                         }
211                 }
212                 if ($errorcount > 0) {
213                         notice(L10n::tt("%d contact not imported", "%d contacts not imported", $errorcount));
214                 }
215
216                 foreach ($account['group'] as &$group) {
217                         $group['uid'] = $newuid;
218                         $r = self::dbImportAssoc('group', $group);
219                         if ($r === false) {
220                                 logger("uimport:insert group " . $group['name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
221                         } else {
222                                 $group['newid'] = self::lastInsertId();
223                         }
224                 }
225
226                 foreach ($account['group_member'] as &$group_member) {
227                         $import = 0;
228                         foreach ($account['group'] as $group) {
229                                 if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
230                                         $group_member['gid'] = $group['newid'];
231                                         $import++;
232                                         break;
233                                 }
234                         }
235                         foreach ($account['contact'] as $contact) {
236                                 if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
237                                         $group_member['contact-id'] = $contact['newid'];
238                                         $import++;
239                                         break;
240                                 }
241                         }
242                         if ($import == 2) {
243                                 $r = self::dbImportAssoc('group_member', $group_member);
244                                 if ($r === false) {
245                                         logger("uimport:insert group member " . $group_member['id'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
246                                 }
247                         }
248                 }
249
250                 foreach ($account['photo'] as &$photo) {
251                         $photo['uid'] = $newuid;
252                         $photo['data'] = hex2bin($photo['data']);
253
254                         $Image = new Image($photo['data'], $photo['type']);
255                         $r = Photo::store(
256                                 $Image,
257                                 $photo['uid'], $photo['contact-id'], //0
258                                 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
259                                 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
260                         );
261
262                         if ($r === false) {
263                                 logger("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
264                         }
265                 }
266
267                 foreach ($account['pconfig'] as &$pconfig) {
268                         $pconfig['uid'] = $newuid;
269                         $r = self::dbImportAssoc('pconfig', $pconfig);
270                         if ($r === false) {
271                                 logger("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
272                         }
273                 }
274
275                 // send relocate messages
276                 Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $newuid);
277
278                 info(L10n::t("Done. You can now login with your username and password"));
279                 goaway(System::baseUrl() . "/login");
280         }
281 }