]> git.mxchange.org Git - friendica.git/blob - src/Module/Settings/UserExport.php
Introduce `Response` for Modules to create a testable way for module responses
[friendica.git] / src / Module / Settings / UserExport.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license   GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Settings;
23
24 use Friendica\Core\Hook;
25 use Friendica\Core\Renderer;
26 use Friendica\Database\DBA;
27 use Friendica\Database\DBStructure;
28 use Friendica\DI;
29 use Friendica\Model\Item;
30 use Friendica\Model\Post;
31 use Friendica\Module\BaseSettings;
32 use Friendica\Network\HTTPException;
33
34 /**
35  * Module to export user data
36  **/
37 class UserExport extends BaseSettings
38 {
39         /**
40          * Handle the request to export data.
41          * At the moment one can export three different data set
42          * 1. The profile data that can be used by uimport to resettle
43          *    to a different Friendica instance
44          * 2. The entire data-set, profile plus postings
45          * 3. A list of contacts as CSV file similar to the export of Mastodon
46          *
47          * If there is an action required through the URL / path, react
48          * accordingly and export the requested data.
49          *
50          * @return string
51          * @throws HTTPException\ForbiddenException
52          * @throws HTTPException\InternalServerErrorException
53          */
54         protected function content(array $request = []): string
55         {
56                 if (!local_user()) {
57                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
58                 }
59
60                 parent::content();
61
62                 /**
63                  * options shown on "Export personal data" page
64                  * list of array( 'link url', 'link text', 'help text' )
65                  */
66                 $options = [
67                         ['settings/userexport/account', DI::l10n()->t('Export account'), DI::l10n()->t('Export your account info and contacts. Use this to make a backup of your account and/or to move it to another server.')],
68                         ['settings/userexport/backup', DI::l10n()->t('Export all'), DI::l10n()->t("Export your account info, contacts and all your items as json. Could be a very big file, and could take a lot of time. Use this to make a full backup of your account \x28photos are not exported\x29")],
69                         ['settings/userexport/contact', DI::l10n()->t('Export Contacts to CSV'), DI::l10n()->t("Export the list of the accounts you are following as CSV file. Compatible to e.g. Mastodon.")],
70                 ];
71                 Hook::callAll('uexport_options', $options);
72
73                 $tpl = Renderer::getMarkupTemplate("settings/userexport.tpl");
74                 return Renderer::replaceMacros($tpl, [
75                         '$title' => DI::l10n()->t('Export personal data'),
76                         '$options' => $options
77                 ]);
78         }
79
80         /**
81          * raw content generated for the different choices made
82          * by the user. At the moment this returns a JSON file
83          * to the browser which then offers a save / open dialog
84          * to the user.
85          *
86          * @throws HTTPException\ForbiddenException
87          */
88         protected function rawContent(array $request = [])
89         {
90                 if (!DI::app()->isLoggedIn()) {
91                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
92                 }
93
94                 $args = DI::args();
95                 if ($args->getArgc() == 3) {
96                         // @TODO Replace with router-provided arguments
97                         $action = $args->get(2);
98                         switch ($action) {
99                                 case "backup":
100                                         header("Content-type: application/json");
101                                         header('Content-Disposition: attachment; filename="' . DI::app()->getLoggedInUserNickname() . '.' . $action . '"');
102                                         self::exportAll(local_user());
103                                         break;
104                                 case "account":
105                                         header("Content-type: application/json");
106                                         header('Content-Disposition: attachment; filename="' . DI::app()->getLoggedInUserNickname() . '.' . $action . '"');
107                                         self::exportAccount(local_user());
108                                         break;
109                                 case "contact":
110                                         header("Content-type: application/csv");
111                                         header('Content-Disposition: attachment; filename="' . DI::app()->getLoggedInUserNickname() . '-contacts.csv' . '"');
112                                         self::exportContactsAsCSV(local_user());
113                                         break;
114                         }
115
116                         exit();
117                 }
118         }
119
120         /**
121          * @param string $query
122          * @return array
123          * @throws \Exception
124          */
125         private static function exportMultiRow(string $query)
126         {
127                 $dbStructure = DBStructure::definition(DI::app()->getBasePath(), false);
128
129                 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
130                 $table = $match[1];
131
132                 $result = [];
133                 $rows = DBA::p($query);
134                 while ($row = DBA::fetch($rows)) {
135                         $p = [];
136                         foreach ($dbStructure[$table]['fields'] as $column => $field) {
137                                 if (!isset($row[$column])) {
138                                         continue;
139                                 }
140                                 if ($field['type'] == 'datetime') {
141                                         $p[$column] = $row[$column] ?? DBA::NULL_DATETIME;
142                                 } else {
143                                         $p[$column] = $row[$column];
144                                 }
145                         }
146                         $result[] = $p;
147                 }
148                 DBA::close($rows);
149                 return $result;
150         }
151
152         /**
153          * @param string $query
154          * @return array
155          * @throws \Exception
156          */
157         private static function exportRow(string $query)
158         {
159                 $dbStructure = DBStructure::definition(DI::app()->getBasePath(), false);
160
161                 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
162                 $table = $match[1];
163
164                 $result = [];
165                 $rows = DBA::p($query);
166                 while ($row = DBA::fetch($rows)) {
167                         foreach ($row as $k => $v) {
168                                 if (empty($dbStructure[$table]['fields'][$k])) {
169                                         continue;
170                                 }
171
172                                 switch ($dbStructure[$table]['fields'][$k]['type']) {
173                                         case 'datetime':
174                                                 $result[$k] = $v ?? DBA::NULL_DATETIME;
175                                                 break;
176                                         default:
177                                                 $result[$k] = $v;
178                                                 break;
179                                 }
180                         }
181                 }
182                 DBA::close($rows);
183
184                 return $result;
185         }
186
187         /**
188          * Export a list of the contacts as CSV file as e.g. Mastodon and Pleroma are doing.
189          *
190          * @param int $user_id
191          * @throws \Exception
192          */
193         private static function exportContactsAsCSV(int $user_id)
194         {
195                 if (!$user_id) {
196                         throw new \RuntimeException(DI::l10n()->t('Permission denied.'));
197                 }
198
199                 // write the table header (like Mastodon)
200                 echo "Account address, Show boosts\n";
201                 // get all the contacts
202                 $contacts = DBA::select('contact', ['addr', 'url'], ['uid' => $user_id, 'self' => false, 'rel' => [1, 3], 'deleted' => false]);
203                 while ($contact = DBA::fetch($contacts)) {
204                         echo ($contact['addr'] ?: $contact['url']) . ", true\n";
205                 }
206                 DBA::close($contacts);
207         }
208
209         /**
210          * @param int $user_id
211          * @throws \Exception
212          */
213         private static function exportAccount(int $user_id)
214         {
215                 if (!$user_id) {
216                         throw new \RuntimeException(DI::l10n()->t('Permission denied.'));
217                 }
218
219                 $user = self::exportRow(
220                         sprintf("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", $user_id)
221                 );
222
223                 $contact = self::exportMultiRow(
224                         sprintf("SELECT * FROM `contact` WHERE `uid` = %d ", $user_id)
225                 );
226
227
228                 $profile = self::exportMultiRow(
229                         sprintf("SELECT *, 'default' AS `profile_name`, 1 AS `is-default` FROM `profile` WHERE `uid` = %d ", $user_id)
230                 );
231
232                 $profile_fields = self::exportMultiRow(
233                         sprintf("SELECT * FROM `profile_field` WHERE `uid` = %d ", $user_id)
234                 );
235
236                 $photo = self::exportMultiRow(
237                         sprintf("SELECT * FROM `photo` WHERE uid = %d AND profile = 1", $user_id)
238                 );
239                 foreach ($photo as &$p) {
240                         $p['data'] = bin2hex($p['data']);
241                 }
242
243                 $pconfig = self::exportMultiRow(
244                         sprintf("SELECT * FROM `pconfig` WHERE uid = %d", $user_id)
245                 );
246
247                 $group = self::exportMultiRow(
248                         sprintf("SELECT * FROM `group` WHERE uid = %d", $user_id)
249                 );
250
251                 $group_member = self::exportMultiRow(
252                         sprintf("SELECT `group_member`.`gid`, `group_member`.`contact-id` FROM `group_member` INNER JOIN `group` ON `group`.`id` = `group_member`.`gid` WHERE `group`.`uid` = %d", $user_id)
253                 );
254
255                 $output = [
256                         'version' => FRIENDICA_VERSION,
257                         'schema' => DB_UPDATE_VERSION,
258                         'baseurl' => DI::baseUrl(),
259                         'user' => $user,
260                         'contact' => $contact,
261                         'profile' => $profile,
262                         'profile_fields' => $profile_fields,
263                         'photo' => $photo,
264                         'pconfig' => $pconfig,
265                         'group' => $group,
266                         'group_member' => $group_member,
267                 ];
268
269                 echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR);
270         }
271
272         /**
273          * echoes account data and items as separated json, one per line
274          *
275          * @param int $user_id
276          * @throws \Exception
277          */
278         private static function exportAll(int $user_id)
279         {
280                 if (!$user_id) {
281                         throw new \RuntimeException(DI::l10n()->t('Permission denied.'));
282                 }
283
284                 self::exportAccount($user_id);
285                 echo "\n";
286
287                 $total = Post::count(['uid' => $user_id]);
288                 // chunk the output to avoid exhausting memory
289
290                 for ($x = 0; $x < $total; $x += 500) {
291                         $items = Post::selectToArray(Item::ITEM_FIELDLIST, ['uid' => $user_id], ['limit' => [$x, 500]]);
292                         $output = ['item' => $items];
293                         echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR) . "\n";
294                 }
295         }
296 }