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