Move mod/maintenance to src/Module/Maintenance
[friendica.git/.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\Model\Photo;
11 use Friendica\Object\Image;
12 use Friendica\Util\Strings;
13
14 /**
15  * @brief UserImport class
16  */
17 class UserImport
18 {
19         const IMPORT_DEBUG = false;
20
21         private static function lastInsertId()
22         {
23                 if (self::IMPORT_DEBUG) {
24                         return 1;
25                 }
26
27                 return DBA::lastInsertId();
28         }
29
30         /**
31          * Remove columns from array $arr that aren't in table $table
32          *
33          * @param string $table Table name
34          * @param array &$arr   Column=>Value array from json (by ref)
35          * @throws \Exception
36          */
37         private static function checkCols($table, &$arr)
38         {
39                 $tableColumns = DBStructure::getColumns($table);
40
41                 $tcols = [];
42                 // get a plain array of column names
43                 foreach ($tableColumns 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
70                 if (self::IMPORT_DEBUG) {
71                         return true;
72                 }
73
74                 return DBA::insert($table, $arr);
75         }
76
77         /**
78          * @brief Import account file exported from mod/uexport
79          *
80          * @param App   $a    Friendica App Class
81          * @param array $file array from $_FILES
82          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
83          * @throws \ImagickException
84          */
85         public static function importAccount(App $a, $file)
86         {
87                 Logger::log("Start user import from " . $file['tmp_name']);
88                 /*
89                 STEPS
90                 1. checks
91                 2. replace old baseurl with new baseurl
92                 3. import data (look at user id and contacts id)
93                 4. archive non-dfrn contacts
94                 5. send message to dfrn contacts
95                 */
96
97                 $account = json_decode(file_get_contents($file['tmp_name']), true);
98                 if ($account === null) {
99                         notice(L10n::t("Error decoding account file"));
100                         return;
101                 }
102
103
104                 if (empty($account['version'])) {
105                         notice(L10n::t("Error! No version data in file! This is not a Friendica account file?"));
106                         return;
107                 }
108
109                 // check for username
110                 // check if username matches deleted account
111                 if (DBA::exists('user', ['nickname' => $account['user']['nickname']])
112                         || DBA::exists('userd', ['username' => $account['user']['nickname']])) {
113                         notice(L10n::t("User '%s' already exists on this server!", $account['user']['nickname']));
114                         return;
115                 }
116
117                 $oldbaseurl = $account['baseurl'];
118                 $newbaseurl = System::baseUrl();
119
120                 $oldaddr = str_replace('http://', '@', Strings::normaliseLink($oldbaseurl));
121                 $newaddr = str_replace('http://', '@', Strings::normaliseLink($newbaseurl));
122
123                 if (!empty($account['profile']['addr'])) {
124                         $old_handle = $account['profile']['addr'];
125                 } else {
126                         $old_handle = $account['user']['nickname'].$oldaddr;
127                 }
128
129                 // Creating a new guid to avoid problems with Diaspora
130                 $account['user']['guid'] = System::createUUID();
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 }