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