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