]> git.mxchange.org Git - friendica.git/blob - include/uimport.php
Class file relocations
[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 use Friendica\Database\DBM;
8
9 require_once("include/Photo.php");
10 define("IMPORT_DEBUG", False);
11
12 function last_insert_id() {
13         if (IMPORT_DEBUG) {
14                 return 1;
15         }
16
17         return dba::lastInsertId();
18 }
19
20 /**
21  * Remove columns from array $arr that aren't in table $table
22  *
23  * @param string $table Table name
24  * @param array &$arr Column=>Value array from json (by ref)
25  */
26 function check_cols($table, &$arr) {
27         $query = sprintf("SHOW COLUMNS IN `%s`", dbesc($table));
28         logger("uimport: $query", LOGGER_DEBUG);
29         $r = q($query);
30         $tcols = array();
31         // get a plain array of column names
32         foreach ($r as $tcol) {
33                 $tcols[] = $tcol['Field'];
34         }
35         // remove inexistent columns
36         foreach ($arr as $icol => $ival) {
37                 if (!in_array($icol, $tcols)) {
38                         unset($arr[$icol]);
39                 }
40         }
41 }
42
43 /**
44  * Import data into table $table
45  *
46  * @param string $table Table name
47  * @param array $arr Column=>Value array from json
48  */
49 function db_import_assoc($table, $arr) {
50         if (isset($arr['id']))
51                 unset($arr['id']);
52         check_cols($table, $arr);
53         $cols = implode("`,`", array_map('dbesc', array_keys($arr)));
54         $vals = implode("','", array_map('dbesc', array_values($arr)));
55         $query = "INSERT INTO `$table` (`$cols`) VALUES ('$vals')";
56         logger("uimport: $query", LOGGER_TRACE);
57         if (IMPORT_DEBUG) {
58                 return true;
59         }
60         return q($query);
61 }
62
63 /**
64  * @brief Import account file exported from mod/uexport
65  *
66  * @param App $a Friendica App Class
67  * @param array $file array from $_FILES
68  */
69 function import_account(App $a, $file) {
70         logger("Start user import from " . $file['tmp_name']);
71         /*
72           STEPS
73           1. checks
74           2. replace old baseurl with new baseurl
75           3. import data (look at user id and contacts id)
76           4. archive non-dfrn contacts
77           5. send message to dfrn contacts
78          */
79
80         $account = json_decode(file_get_contents($file['tmp_name']), true);
81         if ($account === null) {
82                 notice(t("Error decoding account file"));
83                 return;
84         }
85
86
87         if (!x($account, 'version')) {
88                 notice(t("Error! No version data in file! This is not a Friendica account file?"));
89                 return;
90         }
91
92         /*
93          * @TODO Old-lost code?
94         // this is not required as we remove columns in json not in current db schema
95         if ($account['schema'] != DB_UPDATE_VERSION) {
96                 notice(t("Error! I can't import this file: DB schema version is not compatible."));
97                 return;
98         }
99         */
100
101         // check for username
102         $r = q("SELECT uid FROM user WHERE nickname='%s'", $account['user']['nickname']);
103         if ($r === false) {
104                 logger("uimport:check nickname : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
105                 notice(t('Error! Cannot check nickname'));
106                 return;
107         }
108         if (DBM::is_result($r) > 0) {
109                 notice(sprintf(t("User '%s' already exists on this server!"), $account['user']['nickname']));
110                 return;
111         }
112         // check if username matches deleted account
113         $r = q("SELECT id FROM userd WHERE username='%s'", $account['user']['nickname']);
114         if ($r === false) {
115                 logger("uimport:check nickname : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
116                 notice(t('Error! Cannot check nickname'));
117                 return;
118         }
119         if (DBM::is_result($r) > 0) {
120                 notice(sprintf(t("User '%s' already exists on this server!"), $account['user']['nickname']));
121                 return;
122         }
123
124         $oldbaseurl = $account['baseurl'];
125         $newbaseurl = System::baseUrl();
126
127         $oldaddr = str_replace('http://', '@', normalise_link($oldbaseurl));
128         $newaddr = str_replace('http://', '@', normalise_link($newbaseurl));
129
130         if (!empty($account['profile']['addr'])) {
131                 $old_handle = $account['profile']['addr'];
132         } else {
133                 $old_handle = $account['user']['nickname'].$oldaddr;
134         }
135
136         $olduid = $account['user']['uid'];
137
138         unset($account['user']['uid']);
139         unset($account['user']['account_expired']);
140         unset($account['user']['account_expires_on']);
141         unset($account['user']['expire_notification_sent']);
142
143         foreach ($account['user'] as $k => &$v) {
144                 $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
145         }
146
147         // import user
148         $r = db_import_assoc('user', $account['user']);
149         if ($r === false) {
150                 //echo "<pre>"; var_dump($r, $query, mysql_error()); killme();
151                 logger("uimport:insert user : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
152                 notice(t("User creation error"));
153                 return;
154         }
155         $newuid = last_insert_id();
156         //~ $newuid = 1;
157
158         PConfig::set($newuid, 'system', 'previous_addr', $old_handle);
159
160         // Generate a new guid for the account. Otherwise there will be problems with diaspora
161         q("UPDATE `user` SET `guid` = '%s' WHERE `uid` = %d",
162                 dbesc(generate_user_guid()), intval($newuid));
163
164         foreach ($account['profile'] as &$profile) {
165                 foreach ($profile as $k => &$v) {
166                         $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
167                         foreach (array("profile", "avatar") as $k) {
168                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
169                         }
170                 }
171                 $profile['uid'] = $newuid;
172                 $r = db_import_assoc('profile', $profile);
173                 if ($r === false) {
174                         logger("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
175                         info(t("User profile creation error"));
176                         dba::delete('user', array('uid' => $newuid));
177                         return;
178                 }
179         }
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(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
186                                 foreach (array("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 poller to update urls
193                         $contact["avatar-date"] = NULL_DATE;
194
195                         switch ($contact['network']) {
196                                 case NETWORK_DFRN:
197                                 case NETWORK_DIASPORA:
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 : " . dba::errorMessage(), 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 : " . dba::errorMessage(), 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 : " . dba::errorMessage(), 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 : " . dba::errorMessage(), 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 : " . dba::errorMessage(), LOGGER_NORMAL);
285                 }
286         }
287
288         // send relocate messages
289         Worker::add(PRIORITY_HIGH, 'notifier', 'relocate', $newuid);
290
291         info(t("Done. You can now login with your username and password"));
292         goaway(System::baseUrl() . "/login");
293 }