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