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