]> git.mxchange.org Git - friendica.git/blob - include/uimport.php
eb971387fde449c0afaf4592172884d3878df376
[friendica.git] / include / uimport.php
1 <?php
2
3 use Friendica\App;
4
5 require_once("include/Photo.php");
6 define("IMPORT_DEBUG", False);
7
8 function last_insert_id() {
9         global $db;
10
11         if (IMPORT_DEBUG) {
12                 return 1;
13         }
14
15         return $db->insert_id();
16 }
17
18 function last_error() {
19         global $db;
20         return $db->error;
21 }
22
23 /**
24  * Remove columns from array $arr that aren't in table $table
25  *
26  * @param string $table Table name
27  * @param array &$arr Column=>Value array from json (by ref)
28  */
29 function check_cols($table, &$arr) {
30         $query = sprintf("SHOW COLUMNS IN `%s`", dbesc($table));
31         logger("uimport: $query", LOGGER_DEBUG);
32         $r = q($query);
33         $tcols = array();
34         // get a plain array of column names
35         foreach ($r as $tcol) {
36                 $tcols[] = $tcol['Field'];
37         }
38         // remove inexistent columns
39         foreach ($arr as $icol => $ival) {
40                 if (!in_array($icol, $tcols)) {
41                         unset($arr[$icol]);
42                 }
43         }
44 }
45
46 /**
47  * Import data into table $table
48  *
49  * @param string $table Table name
50  * @param array $arr Column=>Value array from json
51  */
52 function db_import_assoc($table, $arr) {
53         if (isset($arr['id']))
54                 unset($arr['id']);
55         check_cols($table, $arr);
56         $cols = implode("`,`", array_map('dbesc', array_keys($arr)));
57         $vals = implode("','", array_map('dbesc', array_values($arr)));
58         $query = "INSERT INTO `$table` (`$cols`) VALUES ('$vals')";
59         logger("uimport: $query", LOGGER_TRACE);
60         if (IMPORT_DEBUG) {
61                 return true;
62         }
63         return q($query);
64 }
65
66 function import_cleanup($newuid) {
67         q("DELETE FROM `user` WHERE uid = %d", $newuid);
68         q("DELETE FROM `contact` WHERE uid = %d", $newuid);
69         q("DELETE FROM `profile` WHERE uid = %d", $newuid);
70         q("DELETE FROM `photo` WHERE uid = %d", $newuid);
71         q("DELETE FROM `group` WHERE uid = %d", $newuid);
72         q("DELETE FROM `group_member` WHERE uid = %d", $newuid);
73         q("DELETE FROM `pconfig` WHERE uid = %d", $newuid);
74 }
75
76 /**
77  * @brief Import account file exported from mod/uexport
78  *
79  * @param App $a Friendica App Class
80  * @param array $file array from $_FILES
81  */
82 function import_account(App $a, $file) {
83         logger("Start user import from " . $file['tmp_name']);
84         /*
85           STEPS
86           1. checks
87           2. replace old baseurl with new baseurl
88           3. import data (look at user id and contacts id)
89           4. archive non-dfrn contacts
90           5. send message to dfrn contacts
91          */
92
93         $account = json_decode(file_get_contents($file['tmp_name']), true);
94         if ($account === null) {
95                 notice(t("Error decoding account file"));
96                 return;
97         }
98
99
100         if (!x($account, 'version')) {
101                 notice(t("Error! No version data in file! This is not a Friendica account file?"));
102                 return;
103         }
104
105         /*
106          * @TODO Old-lost code?
107         // this is not required as we remove columns in json not in current db schema
108         if ($account['schema'] != DB_UPDATE_VERSION) {
109                 notice(t("Error! I can't import this file: DB schema version is not compatible."));
110                 return;
111         }
112         */
113
114         // check for username
115         $r = q("SELECT uid FROM user WHERE nickname='%s'", $account['user']['nickname']);
116         if ($r === false) {
117                 logger("uimport:check nickname : ERROR : " . last_error(), LOGGER_NORMAL);
118                 notice(t('Error! Cannot check nickname'));
119                 return;
120         }
121         if (dbm::is_result($r) > 0) {
122                 notice(sprintf(t("User '%s' already exists on this server!"), $account['user']['nickname']));
123                 return;
124         }
125         // check if username matches deleted account
126         $r = q("SELECT id FROM userd WHERE username='%s'", $account['user']['nickname']);
127         if ($r === false) {
128                 logger("uimport:check nickname : ERROR : " . last_error(), LOGGER_NORMAL);
129                 notice(t('Error! Cannot check nickname'));
130                 return;
131         }
132         if (dbm::is_result($r) > 0) {
133                 notice(sprintf(t("User '%s' already exists on this server!"), $account['user']['nickname']));
134                 return;
135         }
136
137         $oldbaseurl = $account['baseurl'];
138         $newbaseurl = App::get_baseurl();
139         $olduid = $account['user']['uid'];
140
141         unset($account['user']['uid']);
142         unset($account['user']['account_expired']);
143         unset($account['user']['account_expires_on']);
144         unset($account['user']['expire_notification_sent']);
145
146         foreach ($account['user'] as $k => &$v) {
147                 $v = str_replace($oldbaseurl, $newbaseurl, $v);
148         }
149
150         // import user
151         $r = db_import_assoc('user', $account['user']);
152         if ($r === false) {
153                 //echo "<pre>"; var_dump($r, $query, mysql_error()); killme();
154                 logger("uimport:insert user : ERROR : " . last_error(), LOGGER_NORMAL);
155                 notice(t("User creation error"));
156                 return;
157         }
158         $newuid = last_insert_id();
159         //~ $newuid = 1;
160
161         // Generate a new guid for the account. Otherwise there will be problems with diaspora
162         q("UPDATE `user` SET `guid` = '%s' WHERE `uid` = %d",
163                 dbesc(generate_user_guid()), intval($newuid));
164
165         foreach ($account['profile'] as &$profile) {
166                 foreach ($profile as $k => &$v) {
167                         $v = str_replace($oldbaseurl, $newbaseurl, $v);
168                         foreach (array("profile", "avatar") as $k) {
169                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
170                         }
171                 }
172                 $profile['uid'] = $newuid;
173                 $r = db_import_assoc('profile', $profile);
174                 if ($r === false) {
175                         logger("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . last_error(), LOGGER_NORMAL);
176                         info(t("User profile creation error"));
177                         import_cleanup($newuid);
178                         return;
179                 }
180         }
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, $newbaseurl, $v);
187                                 foreach (array("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 poller to update urls
194                         $contact["avatar-date"] = NULL_DATE;
195
196                         switch ($contact['network']) {
197                                 case NETWORK_DFRN:
198                                         //  send relocate message (below)
199                                         break;
200                                 case NETWORK_ZOT:
201                                         /// @TODO handle zot network
202                                         break;
203                                 case NETWORK_MAIL2:
204                                         /// @TODO ?
205                                         break;
206                                 case NETWORK_FEED:
207                                 case NETWORK_MAIL:
208                                         // Nothing to do
209                                         break;
210                                 default:
211                                         // archive other contacts
212                                         $contact['archive'] = "1";
213                         }
214                 }
215                 $contact['uid'] = $newuid;
216                 $r = db_import_assoc('contact', $contact);
217                 if ($r === false) {
218                         logger("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . last_error(), LOGGER_NORMAL);
219                         $errorcount++;
220                 } else {
221                         $contact['newid'] = last_insert_id();
222                 }
223         }
224         if ($errorcount > 0) {
225                 notice(sprintf(tt("%d contact not imported", "%d contacts not imported", $errorcount), $errorcount));
226         }
227
228         foreach ($account['group'] as &$group) {
229                 $group['uid'] = $newuid;
230                 $r = db_import_assoc('group', $group);
231                 if ($r === false) {
232                         logger("uimport:insert group " . $group['name'] . " : ERROR : " . last_error(), LOGGER_NORMAL);
233                 } else {
234                         $group['newid'] = last_insert_id();
235                 }
236         }
237
238         foreach ($account['group_member'] as &$group_member) {
239                 $group_member['uid'] = $newuid;
240
241                 $import = 0;
242                 foreach ($account['group'] as $group) {
243                         if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
244                                 $group_member['gid'] = $group['newid'];
245                                 $import++;
246                                 break;
247                         }
248                 }
249                 foreach ($account['contact'] as $contact) {
250                         if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
251                                 $group_member['contact-id'] = $contact['newid'];
252                                 $import++;
253                                 break;
254                         }
255                 }
256                 if ($import == 2) {
257                         $r = db_import_assoc('group_member', $group_member);
258                         if ($r === false) {
259                                 logger("uimport:insert group member " . $group_member['id'] . " : ERROR : " . last_error(), LOGGER_NORMAL);
260                         }
261                 }
262         }
263
264         foreach ($account['photo'] as &$photo) {
265                 $photo['uid'] = $newuid;
266                 $photo['data'] = hex2bin($photo['data']);
267
268                 $p = new Photo($photo['data'], $photo['type']);
269                 $r = $p->store(
270                                 $photo['uid'], $photo['contact-id'], //0
271                                 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
272                                 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
273                 );
274
275                 if ($r === false) {
276                         logger("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . last_error(), LOGGER_NORMAL);
277                 }
278         }
279
280         foreach ($account['pconfig'] as &$pconfig) {
281                 $pconfig['uid'] = $newuid;
282                 $r = db_import_assoc('pconfig', $pconfig);
283                 if ($r === false) {
284                         logger("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . last_error(), LOGGER_NORMAL);
285                 }
286         }
287
288         // send relocate messages
289         proc_run(PRIORITY_HIGH, 'include/notifier.php', 'relocate', $newuid);
290
291         info(t("Done. You can now login with your username and password"));
292         goaway(App::get_baseurl() . "/login");
293 }