3 * @file src/Modules/Settings/UserExport.php
6 namespace Friendica\Module\Settings;
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;
18 use Friendica\Module\BaseSettingsModule;
21 * Module to export user data
23 class UserExport extends BaseSettingsModule
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
33 * If there is an action required through the URL / path, react
34 * accordingly and export the requested data.
36 public static function content(array $parameters = [])
38 parent::content($parameters);
41 * options shown on "Export personal data" page
42 * list of array( 'link url', 'link text', 'help text' )
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.")],
49 Hook::callAll('uexport_options', $options);
51 $tpl = Renderer::getMarkupTemplate("settings/userexport.tpl");
52 return Renderer::replaceMacros($tpl, [
53 '$title' => L10n::t('Export personal data'),
54 '$options' => $options
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
63 public static function rawContent(array $parameters = [])
65 $args = self::getClass(Arguments::class);
66 if ($args->getArgc() == 3) {
67 // @TODO Replace with router-provided arguments
68 $action = $args->get(2);
69 $user = DI::app()->user;
72 header("Content-type: application/json");
73 header('Content-Disposition: attachment; filename="' . $user['nickname'] . '.' . $action . '"');
74 self::exportAll(DI::app());
78 header("Content-type: application/json");
79 header('Content-Disposition: attachment; filename="' . $user['nickname'] . '.' . $action . '"');
80 self::exportAccount(DI::app());
84 header("Content-type: application/csv");
85 header('Content-Disposition: attachment; filename="' . $user['nickname'] . '-contacts.csv'. '"');
86 self::exportContactsAsCSV();
94 private static function exportMultiRow(string $query)
96 $dbStructure = DBStructure::definition(DI::app()->getBasePath(), false);
98 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
102 $rows = DBA::p($query);
103 while ($row = DBA::fetch($rows)) {
105 foreach ($row as $k => $v) {
106 switch ($dbStructure[$table]['fields'][$k]['type']) {
108 $p[$k] = $v ?? DBA::NULL_DATETIME;
121 private static function exportRow(string $query)
123 $dbStructure = DBStructure::definition(DI::app()->getBasePath(), false);
125 preg_match("/\s+from\s+`?([a-z\d_]+)`?/i", $query, $match);
130 if (DBA::isResult($r)) {
132 foreach ($r as $rr) {
133 foreach ($rr as $k => $v) {
134 switch ($dbStructure[$table]['fields'][$k]['type']) {
136 $result[$k] = $v ?? DBA::NULL_DATETIME;
149 * Export a list of the contacts as CSV file as e.g. Mastodon and Pleroma are doing.
151 private static function exportContactsAsCSV()
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";
160 DBA::close($contacts);
162 private static function exportAccount(App $a)
164 $user = self::exportRow(
165 sprintf("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval(local_user()))
168 $contact = self::exportMultiRow(
169 sprintf("SELECT * FROM `contact` WHERE `uid` = %d ", intval(local_user()))
173 $profile = self::exportMultiRow(
174 sprintf("SELECT * FROM `profile` WHERE `uid` = %d ", intval(local_user()))
177 $photo = self::exportMultiRow(
178 sprintf("SELECT * FROM `photo` WHERE uid = %d AND profile = 1", intval(local_user()))
180 foreach ($photo as &$p) {
181 $p['data'] = bin2hex($p['data']);
184 $pconfig = self::exportMultiRow(
185 sprintf("SELECT * FROM `pconfig` WHERE uid = %d", intval(local_user()))
188 $group = self::exportMultiRow(
189 sprintf("SELECT * FROM `group` WHERE uid = %d", intval(local_user()))
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()))
197 'version' => FRIENDICA_VERSION,
198 'schema' => DB_UPDATE_VERSION,
199 'baseurl' => System::baseUrl(),
201 'contact' => $contact,
202 'profile' => $profile,
204 'pconfig' => $pconfig,
206 'group_member' => $group_member,
209 echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR);
213 * echoes account data and items as separated json, one per line
218 private static function exportAll(App $a)
220 self::exportAccount($a);
223 $total = DBA::count('item', ['uid' => local_user()]);
224 // chunk the output to avoid exhausting memory
226 for ($x = 0; $x < $total; $x += 500) {
227 $r = q("SELECT * FROM `item` WHERE `uid` = %d LIMIT %d, %d",
228 intval(local_user()),
233 $output = ['item' => $r];
234 echo json_encode($output, JSON_PARTIAL_OUTPUT_ON_ERROR). "\n";