]> git.mxchange.org Git - friendica.git/blob - src/Core/UserImport.php
Merge pull request #11520 from annando/display-polls
[friendica.git] / src / Core / UserImport.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\Database\DBA;
25 use Friendica\Database\DBStructure;
26 use Friendica\DI;
27 use Friendica\Model\Photo;
28 use Friendica\Model\Profile;
29 use Friendica\Object\Image;
30 use Friendica\Security\PermissionSet\Repository\PermissionSet;
31 use Friendica\Util\Strings;
32 use Friendica\Worker\Delivery;
33
34 /**
35  * UserImport class
36  */
37 class UserImport
38 {
39         const IMPORT_DEBUG = false;
40
41         private static function lastInsertId()
42         {
43                 if (self::IMPORT_DEBUG) {
44                         return 1;
45                 }
46
47                 return DBA::lastInsertId();
48         }
49
50         /**
51          * Remove columns from array $arr that aren't in table $table
52          *
53          * @param string $table Table name
54          * @param array &$arr   Column=>Value array from json (by ref)
55          * @throws \Exception
56          */
57         private static function checkCols($table, &$arr)
58         {
59                 $tableColumns = DBStructure::getColumns($table);
60
61                 $tcols = [];
62                 $ttype = [];
63                 // get a plain array of column names
64                 foreach ($tableColumns as $tcol) {
65                         $tcols[] = $tcol['Field'];
66                         $ttype[$tcol['Field']] = $tcol['Type'];
67                 }
68                 // remove inexistent columns
69                 foreach ($arr as $icol => $ival) {
70                         if (!in_array($icol, $tcols)) {
71                                 unset($arr[$icol]);
72                                 continue;
73                         }
74
75                         if ($ttype[$icol] === 'datetime') {
76                                 $arr[$icol] = $ival ?? DBA::NULL_DATETIME;
77                         }
78                 }
79         }
80
81         /**
82          * Import data into table $table
83          *
84          * @param string $table Table name
85          * @param array  $arr   Column=>Value array from json
86          * @return array|bool
87          * @throws \Exception
88          */
89         private static function dbImportAssoc($table, $arr)
90         {
91                 if (isset($arr['id'])) {
92                         unset($arr['id']);
93                 }
94
95                 self::checkCols($table, $arr);
96
97                 if (self::IMPORT_DEBUG) {
98                         return true;
99                 }
100
101                 return DBA::insert($table, $arr);
102         }
103
104         /**
105          * Import account file exported from mod/uexport
106          *
107          * @param array $file array from $_FILES
108          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
109          * @throws \ImagickException
110          */
111         public static function importAccount($file)
112         {
113                 Logger::notice("Start user import from " . $file['tmp_name']);
114                 /*
115                 STEPS
116                 1. checks
117                 2. replace old baseurl with new baseurl
118                 3. import data (look at user id and contacts id)
119                 4. archive non-dfrn contacts
120                 5. send message to dfrn contacts
121                 */
122
123                 $account = json_decode(file_get_contents($file['tmp_name']), true);
124                 if ($account === null) {
125                         notice(DI::l10n()->t("Error decoding account file"));
126                         return;
127                 }
128
129
130                 if (empty($account['version'])) {
131                         notice(DI::l10n()->t("Error! No version data in file! This is not a Friendica account file?"));
132                         return;
133                 }
134
135                 // check for username
136                 // check if username matches deleted account
137                 if (DBA::exists('user', ['nickname' => $account['user']['nickname']])
138                         || DBA::exists('userd', ['username' => $account['user']['nickname']])) {
139                         notice(DI::l10n()->t("User '%s' already exists on this server!", $account['user']['nickname']));
140                         return;
141                 }
142
143                 $oldbaseurl = $account['baseurl'];
144                 $newbaseurl = DI::baseUrl();
145
146                 $oldaddr = str_replace('http://', '@', Strings::normaliseLink($oldbaseurl));
147                 $newaddr = str_replace('http://', '@', Strings::normaliseLink($newbaseurl));
148
149                 if (!empty($account['profile']['addr'])) {
150                         $old_handle = $account['profile']['addr'];
151                 } else {
152                         $old_handle = $account['user']['nickname'].$oldaddr;
153                 }
154
155                 // Creating a new guid to avoid problems with Diaspora
156                 $account['user']['guid'] = System::createUUID();
157
158                 $olduid = $account['user']['uid'];
159
160                 unset($account['user']['uid']);
161                 unset($account['user']['account_expired']);
162                 unset($account['user']['account_expires_on']);
163                 unset($account['user']['expire_notification_sent']);
164
165                 $callback = function (&$value) use ($oldbaseurl, $oldaddr, $newbaseurl, $newaddr) {
166                         $value =  str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $value);
167                 };
168
169                 array_walk($account['user'], $callback);
170
171                 // import user
172                 $r = self::dbImportAssoc('user', $account['user']);
173                 if ($r === false) {
174                         Logger::warning("uimport:insert user : ERROR : " . DBA::errorMessage());
175                         notice(DI::l10n()->t("User creation error"));
176                         return;
177                 }
178                 $newuid = self::lastInsertId();
179
180                 DI::pConfig()->set($newuid, 'system', 'previous_addr', $old_handle);
181
182                 $errorcount = 0;
183                 foreach ($account['contact'] as &$contact) {
184                         if ($contact['uid'] == $olduid && $contact['self'] == '1') {
185                                 foreach ($contact as $k => &$v) {
186                                         $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
187                                         foreach (["profile", "avatar", "micro"] as $k) {
188                                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
189                                         }
190                                 }
191                         }
192                         if ($contact['uid'] == $olduid && $contact['self'] == '0') {
193                                 // set contacts 'avatar-date' to NULL_DATE to let worker to update urls
194                                 $contact["avatar-date"] = DBA::NULL_DATETIME;
195
196                                 switch ($contact['network']) {
197                                         case Protocol::DFRN:
198                                         case Protocol::DIASPORA:
199                                                 //  send relocate message (below)
200                                                 break;
201                                         case Protocol::FEED:
202                                         case Protocol::MAIL:
203                                                 // Nothing to do
204                                                 break;
205                                         default:
206                                                 // archive other contacts
207                                                 $contact['archive'] = "1";
208                                 }
209                         }
210                         $contact['uid'] = $newuid;
211                         $r = self::dbImportAssoc('contact', $contact);
212                         if ($r === false) {
213                                 Logger::warning("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage());
214                                 $errorcount++;
215                         } else {
216                                 $contact['newid'] = self::lastInsertId();
217                         }
218                 }
219                 if ($errorcount > 0) {
220                         notice(DI::l10n()->tt("%d contact not imported", "%d contacts not imported", $errorcount));
221                 }
222
223                 foreach ($account['group'] as &$group) {
224                         $group['uid'] = $newuid;
225                         $r = self::dbImportAssoc('group', $group);
226                         if ($r === false) {
227                                 Logger::warning("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage());
228                         } else {
229                                 $group['newid'] = self::lastInsertId();
230                         }
231                 }
232
233                 foreach ($account['group_member'] as &$group_member) {
234                         $import = 0;
235                         foreach ($account['group'] as $group) {
236                                 if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
237                                         $group_member['gid'] = $group['newid'];
238                                         $import++;
239                                         break;
240                                 }
241                         }
242                         foreach ($account['contact'] as $contact) {
243                                 if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
244                                         $group_member['contact-id'] = $contact['newid'];
245                                         $import++;
246                                         break;
247                                 }
248                         }
249                         if ($import == 2) {
250                                 $r = self::dbImportAssoc('group_member', $group_member);
251                                 if ($r === false) {
252                                         Logger::warning("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage());
253                                 }
254                         }
255                 }
256
257                 foreach ($account['profile'] as &$profile) {
258                         unset($profile['id']);
259                         $profile['uid'] = $newuid;
260
261                         foreach ($profile as $k => &$v) {
262                                 $v = str_replace([$oldbaseurl, $oldaddr], [$newbaseurl, $newaddr], $v);
263                                 foreach (["profile", "avatar"] as $k) {
264                                         $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
265                                 }
266                         }
267
268                         if (count($account['profile']) === 1 || $profile['is-default']) {
269                                 $r = self::dbImportAssoc('profile', $profile);
270
271                                 if ($r === false) {
272                                         Logger::warning("uimport:insert profile: ERROR : " . DBA::errorMessage());
273                                         notice(DI::l10n()->t("User profile creation error"));
274                                         DBA::delete('user', ['uid' => $newuid]);
275                                         DBA::delete('profile_field', ['uid' => $newuid]);
276                                         return;
277                                 }
278
279                                 $profile['id'] = DBA::lastInsertId();
280                         }
281
282                         Profile::migrate($profile);
283                 }
284
285                 $permissionSet = DI::permissionSet()->selectDefaultForUser($newuid);
286
287                 foreach ($account['profile_fields'] ?? [] as $profile_field) {
288                         $profile_field['uid'] = $newuid;
289
290                         ///@TODO Replace with permissionset import
291                         $profile_field['psid'] = $profile_field['psid'] ? $permissionSet->uid : PermissionSet::PUBLIC;
292
293                         if (self::dbImportAssoc('profile_field', $profile_field) === false) {
294                                 Logger::info("uimport:insert profile field " . $profile_field['id'] . " : ERROR : " . DBA::errorMessage());
295                         }
296                 }
297
298                 foreach ($account['photo'] as &$photo) {
299                         $photo['uid'] = $newuid;
300                         $photo['data'] = hex2bin($photo['data']);
301
302                         $Image = new Image($photo['data'], $photo['type']);
303                         $r = Photo::store(
304                                 $Image,
305                                 $photo['uid'], $photo['contact-id'], //0
306                                 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
307                                 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
308                         );
309
310                         if ($r === false) {
311                                 Logger::warning("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage());
312                         }
313                 }
314
315                 foreach ($account['pconfig'] as &$pconfig) {
316                         $pconfig['uid'] = $newuid;
317                         $r = self::dbImportAssoc('pconfig', $pconfig);
318                         if ($r === false) {
319                                 Logger::warning("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage());
320                         }
321                 }
322
323                 // send relocate messages
324                 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::RELOCATION, $newuid);
325
326                 info(DI::l10n()->t("Done. You can now login with your username and password"));
327                 DI::baseUrl()->redirect('login');
328         }
329 }