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