]> git.mxchange.org Git - friendica.git/blob - src/Module/Settings/UserExport.php
Refactor deprecated App::internalRedirect() to DI::baseUrl()->redirect()
[friendica.git] / src / Module / Settings / UserExport.php
1 <?php
2 /**
3  * @file src/Modules/Settings/UserExport.php
4  */
5
6 namespace Friendica\Module\Settings;
7
8 use Friendica\App;
9 use Friendica\App\Arguments;
10 use Friendica\BaseModule;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
16 use Friendica\Database\DBStructure;
17 use Friendica\DI;
18 use Friendica\Module\BaseSettingsModule;
19
20 /**
21  * Module to export user data
22  **/
23 class UserExport extends BaseSettingsModule
24 {
25         /**
26          * Handle the request to export data.
27          * At the moment one can export three different data set
28          * 1. The profile data that can be used by uimport to resettle
29          *    to a different Friendica instance
30          * 2. The entire data-set, profile plus postings
31          * 3. A list of contacts as CSV file similar to the export of Mastodon
32          *
33          * If there is an action required through the URL / path, react
34          * accordingly and export the requested data.
35          **/
36         public static function content(array $parameters = [])
37         {
38                 parent::content($parameters);
39
40                 /**
41                  * options shown on "Export personal data" page
42                  * list of array( 'link url', 'link text', 'help text' )
43                  */
44                 $options = [
45                         ['settings/userexport/account', L10n::t('Export account'), 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.')],
46                         ['settings/userexport/backup', L10n::t('Export all'), L10n::t("Export your accout 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")],
47                         ['settings/userexport/contact', L10n::t('Export Contacts to CSV'), L10n::t("Export the list of the accounts you are following as CSV file. Compatible to e.g. Mastodon.")],
48                 ];
49                 Hook::callAll('uexport_options', $options);
50
51                 $tpl = Renderer::getMarkupTemplate("settings/userexport.tpl");
52                 return Renderer::replaceMacros($tpl, [
53                         '$title' => L10n::t('Export personal data'),
54                         '$options' => $options
55                 ]);
56         }
57         /**
58          * raw content generated for the different choices made
59          * by the user. At the moment this returns a JSON file
60          * to the browser which then offers a save / open dialog
61          * to the user.
62          **/
63         public static function rawContent(array $parameters = [])
64         {
65                 $args = DI::args();
66                 if ($args->getArgc() == 3) {
67                         // @TODO Replace with router-provided arguments
68                         $action = $args->get(2);
69                         $user = DI::app()->user;
70                         switch ($action) {
71                                 case "backup":
72                                         header("Content-type: application/json");
73                                         header('Content-Disposition: attachment; filename="' . $user['nickname'] . '.' . $action . '"');
74                                         self::exportAll(DI::app());
75                                         exit();
76                                         break;
77                                 case "account":
78                                         header("Content-type: application/json");
79                                         header('Content-Disposition: attachment; filename="' . $user['nickname'] . '.' . $action . '"');
80                                         self::exportAccount(DI::app());
81                                         exit();
82                                         break;
83                                 case "contact":
84                                         header("Content-type: application/csv");
85                                         header('Content-Disposition: attachment; filename="' . $user['nickname'] . '-contacts.csv'. '"');
86                                         self::exportContactsAsCSV();
87                                         exit();
88                                         break;
89                                 default:
90                                         exit();
91                         }
92                 }
93         }
94         private static function exportMultiRow(string $query)
95         {
96                 $dbStructure = DBStructure::definition(DI::app()->getBasePath(), false);
97
98                 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
99                 $table = $match[1];
100
101                 $result = [];
102                 $rows = DBA::p($query);
103                 while ($row = DBA::fetch($rows)) {
104                         $p = [];
105                         foreach ($row as $k => $v) {
106                                 switch ($dbStructure[$table]['fields'][$k]['type']) {
107                                         case 'datetime':
108                                                 $p[$k] = $v ?? DBA::NULL_DATETIME;
109                                                 break;
110                                         default:
111                                                 $p[$k] = $v;
112                                                 break;
113                                 }
114                         }
115                         $result[] = $p;
116                 }
117                 DBA::close($rows);
118                 return $result;
119         }
120
121         private static function exportRow(string $query)
122         {
123                 $dbStructure = DBStructure::definition(DI::app()->getBasePath(), false);
124
125                 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
126                 $table = $match[1];
127
128                 $result = [];
129                 $r = q($query);
130                 if (DBA::isResult($r)) {
131
132                         foreach ($r as $rr) {
133                                 foreach ($rr as $k => $v) {
134                                         switch ($dbStructure[$table]['fields'][$k]['type']) {
135                                                 case 'datetime':
136                                                         $result[$k] = $v ?? DBA::NULL_DATETIME;
137                                                         break;
138                                                 default:
139                                                         $result[$k] = $v;
140                                                         break;
141                                         }
142                                 }
143                         }
144                 }
145                 return $result;
146         }
147
148         /**
149          * Export a list of the contacts as CSV file as e.g. Mastodon and Pleroma are doing.
150          **/
151         private static function exportContactsAsCSV()
152         {
153                 // write the table header (like Mastodon)
154                 echo "Account address, Show boosts\n";
155                 // get all the contacts
156                 $contacts = DBA::select('contact', ['addr'], ['uid' => $_SESSION['uid'], 'self' => false, 'rel' => [1,3], 'deleted' => false]);
157                 while ($contact = DBA::fetch($contacts)) {
158                         echo $contact['addr'] . ", true\n";
159                 }
160                 DBA::close($contacts);
161         }
162         private static function exportAccount(App $a)
163         {
164                 $user = self::exportRow(
165                         sprintf("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval(local_user()))
166                 );
167
168                 $contact = self::exportMultiRow(
169                         sprintf("SELECT * FROM `contact` WHERE `uid` = %d ", intval(local_user()))
170                 );
171
172
173                 $profile = self::exportMultiRow(
174                         sprintf("SELECT * FROM `profile` WHERE `uid` = %d ", intval(local_user()))
175                 );
176
177                 $photo = self::exportMultiRow(
178                         sprintf("SELECT * FROM `photo` WHERE uid = %d AND profile = 1", intval(local_user()))
179                 );
180                 foreach ($photo as &$p) {
181                         $p['data'] = bin2hex($p['data']);
182                 }
183
184                 $pconfig = self::exportMultiRow(
185                         sprintf("SELECT * FROM `pconfig` WHERE uid = %d", intval(local_user()))
186                 );
187
188                 $group = self::exportMultiRow(
189                         sprintf("SELECT * FROM `group` WHERE uid = %d", intval(local_user()))
190                 );
191
192                 $group_member = self::exportMultiRow(
193                         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", intval(local_user()))
194                 );
195
196                 $output = [
197                         'version' => FRIENDICA_VERSION,
198                         'schema' => DB_UPDATE_VERSION,
199                         'baseurl' => System::baseUrl(),
200                         'user' => $user,
201                         'contact' => $contact,
202                         'profile' => $profile,
203                         'photo' => $photo,
204                         'pconfig' => $pconfig,
205                         'group' => $group,
206                         'group_member' => $group_member,
207                 ];
208
209                 echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR);
210         }
211
212         /**
213          * echoes account data and items as separated json, one per line
214          *
215          * @param App $a
216          * @throws Exception
217          */
218         private static function exportAll(App $a)
219         {
220                 self::exportAccount($a);
221                 echo "\n";
222
223                 $total = DBA::count('item', ['uid' => local_user()]);
224                 // chunk the output to avoid exhausting memory
225
226                 for ($x = 0; $x < $total; $x += 500) {
227                         $r = q("SELECT * FROM `item` WHERE `uid` = %d LIMIT %d, %d",
228                                 intval(local_user()),
229                                 intval($x),
230                                 intval(500)
231                         );
232
233                         $output = ['item' => $r];
234                         echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR). "\n";
235                 }
236         }
237 }