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