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