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