]> git.mxchange.org Git - friendica.git/blob - include/uimport.php
New database version
[friendica.git] / include / uimport.php
1 <?php
2
3 use Friendica\App;
4
5 require_once("include/Photo.php");
6 define("IMPORT_DEBUG", False);
7
8 function last_insert_id() {
9         if (IMPORT_DEBUG) {
10                 return 1;
11         }
12
13         return dba::lastInsertId();
14 }
15
16 function last_error() {
17         global $db;
18         return $db->error;
19 }
20
21 /**
22  * Remove columns from array $arr that aren't in table $table
23  *
24  * @param string $table Table name
25  * @param array &$arr Column=>Value array from json (by ref)
26  */
27 function check_cols($table, &$arr) {
28         $query = sprintf("SHOW COLUMNS IN `%s`", dbesc($table));
29         logger("uimport: $query", LOGGER_DEBUG);
30         $r = q($query);
31         $tcols = array();
32         // get a plain array of column names
33         foreach ($r as $tcol) {
34                 $tcols[] = $tcol['Field'];
35         }
36         // remove inexistent columns
37         foreach ($arr as $icol => $ival) {
38                 if (!in_array($icol, $tcols)) {
39                         unset($arr[$icol]);
40                 }
41         }
42 }
43
44 /**
45  * Import data into table $table
46  *
47  * @param string $table Table name
48  * @param array $arr Column=>Value array from json
49  */
50 function db_import_assoc($table, $arr) {
51         if (isset($arr['id']))
52                 unset($arr['id']);
53         check_cols($table, $arr);
54         $cols = implode("`,`", array_map('dbesc', array_keys($arr)));
55         $vals = implode("','", array_map('dbesc', array_values($arr)));
56         $query = "INSERT INTO `$table` (`$cols`) VALUES ('$vals')";
57         logger("uimport: $query", LOGGER_TRACE);
58         if (IMPORT_DEBUG) {
59                 return true;
60         }
61         return q($query);
62 }
63
64 /**
65  * @brief Import account file exported from mod/uexport
66  *
67  * @param App $a Friendica App Class
68  * @param array $file array from $_FILES
69  */
70 function import_account(App $a, $file) {
71         logger("Start user import from " . $file['tmp_name']);
72         /*
73           STEPS
74           1. checks
75           2. replace old baseurl with new baseurl
76           3. import data (look at user id and contacts id)
77           4. archive non-dfrn contacts
78           5. send message to dfrn contacts
79          */
80
81         $account = json_decode(file_get_contents($file['tmp_name']), true);
82         if ($account === null) {
83                 notice(t("Error decoding account file"));
84                 return;
85         }
86
87
88         if (!x($account, 'version')) {
89                 notice(t("Error! No version data in file! This is not a Friendica account file?"));
90                 return;
91         }
92
93         /*
94          * @TODO Old-lost code?
95         // this is not required as we remove columns in json not in current db schema
96         if ($account['schema'] != DB_UPDATE_VERSION) {
97                 notice(t("Error! I can't import this file: DB schema version is not compatible."));
98                 return;
99         }
100         */
101
102         // check for username
103         $r = q("SELECT uid FROM user WHERE nickname='%s'", $account['user']['nickname']);
104         if ($r === false) {
105                 logger("uimport:check nickname : ERROR : " . last_error(), LOGGER_NORMAL);
106                 notice(t('Error! Cannot check nickname'));
107                 return;
108         }
109         if (dbm::is_result($r) > 0) {
110                 notice(sprintf(t("User '%s' already exists on this server!"), $account['user']['nickname']));
111                 return;
112         }
113         // check if username matches deleted account
114         $r = q("SELECT id FROM userd WHERE username='%s'", $account['user']['nickname']);
115         if ($r === false) {
116                 logger("uimport:check nickname : ERROR : " . last_error(), LOGGER_NORMAL);
117                 notice(t('Error! Cannot check nickname'));
118                 return;
119         }
120         if (dbm::is_result($r) > 0) {
121                 notice(sprintf(t("User '%s' already exists on this server!"), $account['user']['nickname']));
122                 return;
123         }
124
125         $oldbaseurl = $account['baseurl'];
126         $newbaseurl = App::get_baseurl();
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($oldbaseurl, $newbaseurl, $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 : " . last_error(), 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($oldbaseurl, $newbaseurl, $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 : " . last_error(), 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($oldbaseurl, $newbaseurl, $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 : " . last_error(), 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 : " . last_error(), 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 : " . last_error(), 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 : " . last_error(), 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 : " . last_error(), 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(App::get_baseurl() . "/login");
281 }