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