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