]> git.mxchange.org Git - friendica.git/blob - src/Core/UserImport.php
Merge pull request #6456 from annando/long-url
[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          */
38         private static function checkCols($table, &$arr)
39         {
40                 $query = sprintf("SHOW COLUMNS IN `%s`", DBA::escape($table));
41                 Logger::log("uimport: $query", Logger::DEBUG);
42                 $r = q($query);
43                 $tcols = [];
44                 // get a plain array of column names
45                 foreach ($r as $tcol) {
46                         $tcols[] = $tcol['Field'];
47                 }
48                 // remove inexistent columns
49                 foreach ($arr as $icol => $ival) {
50                         if (!in_array($icol, $tcols)) {
51                                 unset($arr[$icol]);
52                         }
53                 }
54         }
55
56         /**
57          * Import data into table $table
58          *
59          * @param string $table Table name
60          * @param array $arr Column=>Value array from json
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          */
87         public static function importAccount(App $a, $file)
88         {
89                 Logger::log("Start user import from " . $file['tmp_name']);
90                 /*
91                 STEPS
92                 1. checks
93                 2. replace old baseurl with new baseurl
94                 3. import data (look at user id and contacts id)
95                 4. archive non-dfrn contacts
96                 5. send message to dfrn contacts
97                 */
98
99                 $account = json_decode(file_get_contents($file['tmp_name']), true);
100                 if ($account === null) {
101                         notice(L10n::t("Error decoding account file"));
102                         return;
103                 }
104
105
106                 if (empty($account['version'])) {
107                         notice(L10n::t("Error! No version data in file! This is not a Friendica account file?"));
108                         return;
109                 }
110
111                 // check for username
112                 // check if username matches deleted account
113                 if (DBA::exists('user', ['nickname' => $account['user']['nickname']])
114                         || DBA::exists('userd', ['username' => $account['user']['nickname']])) {
115                         notice(L10n::t("User '%s' already exists on this server!", $account['user']['nickname']));
116                         return;
117                 }
118
119                 $oldbaseurl = $account['baseurl'];
120                 $newbaseurl = System::baseUrl();
121
122                 $oldaddr = str_replace('http://', '@', Strings::normaliseLink($oldbaseurl));
123                 $newaddr = str_replace('http://', '@', Strings::normaliseLink($newbaseurl));
124
125                 if (!empty($account['profile']['addr'])) {
126                         $old_handle = $account['profile']['addr'];
127                 } else {
128                         $old_handle = $account['user']['nickname'].$oldaddr;
129                 }
130
131                 // Creating a new guid to avoid problems with Diaspora
132                 $account['user']['guid'] = System::createUUID();
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::log("uimport:insert user : ERROR : " . DBA::errorMessage(), Logger::INFO);
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::log("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
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"] = DBA::NULL_DATETIME;
188
189                                 switch ($contact['network']) {
190                                         case Protocol::DFRN:
191                                         case Protocol::DIASPORA:
192                                                 //  send relocate message (below)
193                                                 break;
194                                         case Protocol::FEED:
195                                         case Protocol::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::log("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
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::log("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
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::log("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
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::log("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
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::log("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
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                 $a->internalRedirect('login');
280         }
281 }