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