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