]> git.mxchange.org Git - friendica.git/blob - include/uimport.php
On participation send all the old content of the thread
[friendica.git] / include / uimport.php
1 <?php
2 /**
3  * @file include/uimport.php
4  */
5 use Friendica\App;
6 use Friendica\Core\System;
7 use Friendica\Core\PConfig;
8 use Friendica\Core\Worker;
9 use Friendica\Database\DBM;
10 use Friendica\Model\Photo;
11 use Friendica\Object\Image;
12
13 define("IMPORT_DEBUG", False);
14
15 function last_insert_id() {
16         if (IMPORT_DEBUG) {
17                 return 1;
18         }
19
20         return dba::lastInsertId();
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 : " . dba::errorMessage(), 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 : " . dba::errorMessage(), 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 = System::baseUrl();
129
130         $oldaddr = str_replace('http://', '@', normalise_link($oldbaseurl));
131         $newaddr = str_replace('http://', '@', normalise_link($newbaseurl));
132
133         if (!empty($account['profile']['addr'])) {
134                 $old_handle = $account['profile']['addr'];
135         } else {
136                 $old_handle = $account['user']['nickname'].$oldaddr;
137         }
138
139         $olduid = $account['user']['uid'];
140
141         unset($account['user']['uid']);
142         unset($account['user']['account_expired']);
143         unset($account['user']['account_expires_on']);
144         unset($account['user']['expire_notification_sent']);
145
146         foreach ($account['user'] as $k => &$v) {
147                 $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
148         }
149
150         // import user
151         $r = db_import_assoc('user', $account['user']);
152         if ($r === false) {
153                 logger("uimport:insert user : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
154                 notice(t("User creation error"));
155                 return;
156         }
157         $newuid = last_insert_id();
158         //~ $newuid = 1;
159
160         PConfig::set($newuid, 'system', 'previous_addr', $old_handle);
161
162         // Generate a new guid for the account. Otherwise there will be problems with diaspora
163         q("UPDATE `user` SET `guid` = '%s' WHERE `uid` = %d",
164                 dbesc(generate_user_guid()), intval($newuid));
165
166         foreach ($account['profile'] as &$profile) {
167                 foreach ($profile as $k => &$v) {
168                         $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
169                         foreach (array("profile", "avatar") as $k) {
170                                 $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
171                         }
172                 }
173                 $profile['uid'] = $newuid;
174                 $r = db_import_assoc('profile', $profile);
175                 if ($r === false) {
176                         logger("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
177                         info(t("User profile creation error"));
178                         dba::delete('user', array('uid' => $newuid));
179                         return;
180                 }
181         }
182
183         $errorcount = 0;
184         foreach ($account['contact'] as &$contact) {
185                 if ($contact['uid'] == $olduid && $contact['self'] == '1') {
186                         foreach ($contact as $k => &$v) {
187                                 $v = str_replace(array($oldbaseurl, $oldaddr), array($newbaseurl, $newaddr), $v);
188                                 foreach (array("profile", "avatar", "micro") as $k) {
189                                         $v = str_replace($oldbaseurl . "/photo/" . $k . "/" . $olduid . ".jpg", $newbaseurl . "/photo/" . $k . "/" . $newuid . ".jpg", $v);
190                                 }
191                         }
192                 }
193                 if ($contact['uid'] == $olduid && $contact['self'] == '0') {
194                         // set contacts 'avatar-date' to NULL_DATE to let worker to update urls
195                         $contact["avatar-date"] = NULL_DATE;
196
197                         switch ($contact['network']) {
198                                 case NETWORK_DFRN:
199                                 case NETWORK_DIASPORA:
200                                         //  send relocate message (below)
201                                         break;
202                                 case NETWORK_FEED:
203                                 case NETWORK_MAIL:
204                                         // Nothing to do
205                                         break;
206                                 default:
207                                         // archive other contacts
208                                         $contact['archive'] = "1";
209                         }
210                 }
211                 $contact['uid'] = $newuid;
212                 $r = db_import_assoc('contact', $contact);
213                 if ($r === false) {
214                         logger("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
215                         $errorcount++;
216                 } else {
217                         $contact['newid'] = last_insert_id();
218                 }
219         }
220         if ($errorcount > 0) {
221                 notice(sprintf(tt("%d contact not imported", "%d contacts not imported", $errorcount), $errorcount));
222         }
223
224         foreach ($account['group'] as &$group) {
225                 $group['uid'] = $newuid;
226                 $r = db_import_assoc('group', $group);
227                 if ($r === false) {
228                         logger("uimport:insert group " . $group['name'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
229                 } else {
230                         $group['newid'] = last_insert_id();
231                 }
232         }
233
234         foreach ($account['group_member'] as &$group_member) {
235                 $import = 0;
236                 foreach ($account['group'] as $group) {
237                         if ($group['id'] == $group_member['gid'] && isset($group['newid'])) {
238                                 $group_member['gid'] = $group['newid'];
239                                 $import++;
240                                 break;
241                         }
242                 }
243                 foreach ($account['contact'] as $contact) {
244                         if ($contact['id'] == $group_member['contact-id'] && isset($contact['newid'])) {
245                                 $group_member['contact-id'] = $contact['newid'];
246                                 $import++;
247                                 break;
248                         }
249                 }
250                 if ($import == 2) {
251                         $r = db_import_assoc('group_member', $group_member);
252                         if ($r === false) {
253                                 logger("uimport:insert group member " . $group_member['id'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
254                         }
255                 }
256         }
257
258         foreach ($account['photo'] as &$photo) {
259                 $photo['uid'] = $newuid;
260                 $photo['data'] = hex2bin($photo['data']);
261
262                 $Image = new Image($photo['data'], $photo['type']);
263                 $r = Photo::store(
264                                 $Image,
265                                 $photo['uid'], $photo['contact-id'], //0
266                                 $photo['resource-id'], $photo['filename'], $photo['album'], $photo['scale'], $photo['profile'], //1
267                                 $photo['allow_cid'], $photo['allow_gid'], $photo['deny_cid'], $photo['deny_gid']
268                 );
269
270                 if ($r === false) {
271                         logger("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
272                 }
273         }
274
275         foreach ($account['pconfig'] as &$pconfig) {
276                 $pconfig['uid'] = $newuid;
277                 $r = db_import_assoc('pconfig', $pconfig);
278                 if ($r === false) {
279                         logger("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . dba::errorMessage(), LOGGER_NORMAL);
280                 }
281         }
282
283         // send relocate messages
284         Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $newuid);
285
286         info(t("Done. You can now login with your username and password"));
287         goaway(System::baseUrl() . "/login");
288 }