]> git.mxchange.org Git - friendica.git/blob - src/Module/Settings/UserExport.php
41072d7ef5882e0299857f430a2b79c7ba064545
[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/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.')],
44                         ['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")],
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                 $rows = DBA::p($query);
92                 while ($row = DBA::fetch($rows)) {
93                         $p = [];
94                         foreach ($row as $k => $v) {
95                                 switch ($dbStructure[$table]['fields'][$k]['type']) {
96                                         case 'datetime':
97                                                 $p[$k] = $v ?? DBA::NULL_DATETIME;
98                                                 break;
99                                         default:
100                                                 $p[$k] = $v;
101                                                 break;
102                                 }
103                         }
104                         $result[] = $p;
105                 }
106                 DBA::close($rows);
107                 return $result;
108         }
109
110         private static function exportRow(string $query)
111         {
112                 $dbStructure = DBStructure::definition(self::getApp()->getBasePath(), false);
113
114                 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
115                 $table = $match[1];
116
117                 $result = [];
118                 $r = q($query);
119                 if (DBA::isResult($r)) {
120
121                         foreach ($r as $rr) {
122                                 foreach ($rr as $k => $v) {
123                                         switch ($dbStructure[$table]['fields'][$k]['type']) {
124                                                 case 'datetime':
125                                                         $result[$k] = $v ?? DBA::NULL_DATETIME;
126                                                         break;
127                                                 default:
128                                                         $result[$k] = $v;
129                                                         break;
130                                         }
131                                 }
132                         }
133                 }
134                 return $result;
135         }
136
137         private static function exportAccount(App $a)
138         {
139                 $user = self::exportRow(
140                         sprintf("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval(local_user()))
141                 );
142
143                 $contact = self::exportMultiRow(
144                         sprintf("SELECT * FROM `contact` WHERE `uid` = %d ", intval(local_user()))
145                 );
146
147
148                 $profile = self::exportMultiRow(
149                         sprintf("SELECT * FROM `profile` WHERE `uid` = %d ", intval(local_user()))
150                 );
151
152                 $photo = self::exportMultiRow(
153                         sprintf("SELECT * FROM `photo` WHERE uid = %d AND profile = 1", intval(local_user()))
154                 );
155                 foreach ($photo as &$p) {
156                         $p['data'] = bin2hex($p['data']);
157                 }
158
159                 $pconfig = self::exportMultiRow(
160                         sprintf("SELECT * FROM `pconfig` WHERE uid = %d", intval(local_user()))
161                 );
162
163                 $group = self::exportMultiRow(
164                         sprintf("SELECT * FROM `group` WHERE uid = %d", intval(local_user()))
165                 );
166
167                 $group_member = self::exportMultiRow(
168                         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()))
169                 );
170
171                 $output = [
172                         'version' => FRIENDICA_VERSION,
173                         'schema' => DB_UPDATE_VERSION,
174                         'baseurl' => System::baseUrl(),
175                         'user' => $user,
176                         'contact' => $contact,
177                         'profile' => $profile,
178                         'photo' => $photo,
179                         'pconfig' => $pconfig,
180                         'group' => $group,
181                         'group_member' => $group_member,
182                 ];
183
184                 echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR);
185         }
186
187         /**
188          * echoes account data and items as separated json, one per line
189          *
190          * @param App $a
191          * @throws Exception
192          */
193         private static function exportAll(App $a)
194         {
195                 self::exportAccount($a);
196                 echo "\n";
197
198                 $total = DBA::count('item', ['uid' => local_user()]);
199                 // chunk the output to avoid exhausting memory
200
201                 for ($x = 0; $x < $total; $x += 500) {
202                         $r = q("SELECT * FROM `item` WHERE `uid` = %d LIMIT %d, %d",
203                                 intval(local_user()),
204                                 intval($x),
205                                 intval(500)
206                         );
207
208                         $output = ['item' => $r];
209                         echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR). "\n";
210                 }
211         }
212 }