]> git.mxchange.org Git - friendica.git/blob - mod/admin.php
cc2256b73dd37ba36585f1cb78c4a16e0fa0e963
[friendica.git] / mod / admin.php
1 <?php
2 /**
3  * @file mod/admin.php
4  *
5  * @brief Friendica admin
6  */
7
8 use Friendica\App;
9 use Friendica\BaseModule;
10 use Friendica\Content\Feature;
11 use Friendica\Content\Pager;
12 use Friendica\Content\Text\Markdown;
13 use Friendica\Core\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Renderer;
18 use Friendica\Core\System;
19 use Friendica\Core\Theme;
20 use Friendica\Core\Update;
21 use Friendica\Core\Worker;
22 use Friendica\Core\StorageManager;
23 use Friendica\Database\DBA;
24 use Friendica\Database\DBStructure;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Item;
27 use Friendica\Model\Register;
28 use Friendica\Model\User;
29 use Friendica\Module;
30 use Friendica\Module\Login;
31 use Friendica\Module\Tos;
32 use Friendica\Util\Arrays;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\Strings;
36 use Friendica\Util\Temporal;
37 use Psr\Log\LogLevel;
38
39 /**
40  * Sets the current theme for theme settings pages.
41  *
42  * This needs to be done before the post() or content() methods are called.
43  *
44  * @param App $a
45  */
46 function admin_init(App $a)
47 {
48         if ($a->argc > 2 && $a->argv[1] == 'themes') {
49                 $theme = $a->argv[2];
50                 if (is_file("view/theme/$theme/config.php")) {
51                         $a->setCurrentTheme($theme);
52                 }
53         }
54 }
55
56 /**
57  * @brief Process send data from the admin panels subpages
58  *
59  * This function acts as relay for processing the data send from the subpages
60  * of the admin panel. Depending on the 1st parameter of the url (argv[1])
61  * specialized functions are called to process the data from the subpages.
62  *
63  * The function itself does not return anything, but the subsequently function
64  * return the HTML for the pages of the admin panel.
65  *
66  * @param App $a
67  * @throws ImagickException
68  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69  */
70 function admin_post(App $a)
71 {
72         if (!is_site_admin()) {
73                 return;
74         }
75
76         // do not allow a page manager to access the admin panel at all.
77
78         if (!empty($_SESSION['submanage'])) {
79                 return;
80         }
81
82         $return_path = 'admin';
83         if ($a->argc > 1) {
84                 switch ($a->argv[1]) {
85                         case 'site':
86                                 admin_page_site_post($a);
87                                 break;
88                         case 'users':
89                                 admin_page_users_post($a);
90                                 break;
91                         case 'addons':
92                                 if ($a->argc > 2 &&
93                                         is_file("addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php")) {
94                                         include_once "addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php";
95                                         if (function_exists($a->argv[2] . '_addon_admin_post')) {
96                                                 $func = $a->argv[2] . '_addon_admin_post';
97                                                 $func($a);
98                                         }
99                                 }
100                                 $return_path = 'admin/addons/' . $a->argv[2];
101                                 break;
102                         case 'themes':
103                                 if ($a->argc < 2) {
104                                         if ($a->isAjax()) {
105                                                 return;
106                                         }
107                                         $a->internalRedirect('admin/');
108                                         return;
109                                 }
110
111                                 $theme = $a->argv[2];
112                                 if (is_file("view/theme/$theme/config.php")) {
113                                         require_once "view/theme/$theme/config.php";
114
115                                         if (function_exists('theme_admin_post')) {
116                                                 theme_admin_post($a);
117                                         }
118                                 }
119
120                                 info(L10n::t('Theme settings updated.'));
121                                 if ($a->isAjax()) {
122                                         return;
123                                 }
124                                 $return_path = 'admin/themes/' . $theme . (!empty($_GET['mode']) ? '?mode=' . $_GET['mode'] : '');
125                                 break;
126                         case 'tos':
127                                 admin_page_tos_post($a);
128                                 break;
129                         case 'features':
130                                 admin_page_features_post($a);
131                                 break;
132                         case 'logs':
133                                 admin_page_logs_post($a);
134                                 break;
135                         case 'contactblock':
136                                 admin_page_contactblock_post($a);
137                                 break;
138                         case 'blocklist':
139                                 admin_page_blocklist_post($a);
140                                 break;
141                         case 'deleteitem':
142                                 admin_page_deleteitem_post($a);
143                                 break;
144                 }
145         }
146
147         $a->internalRedirect($return_path);
148         return; // NOTREACHED
149 }
150
151 /**
152  * @brief Generates content of the admin panel pages
153  *
154  * This function generates the content for the admin panel. It consists of the
155  * aside menu (same for the entire admin panel) and the code for the soecified
156  * subpage of the panel.
157  *
158  * The structure of the adress is: /admin/subpage/details though "details" is
159  * only necessary for some subpages, like themes or addons where it is the name
160  * of one theme resp. addon from which the details should be shown. Content for
161  * the subpages is generated in separate functions for each of the subpages.
162  *
163  * The returned string hold the generated HTML code of the page.
164  *
165  * @param App $a
166  * @return string
167  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168  */
169 function admin_content(App $a)
170 {
171         if (!is_site_admin()) {
172                 return Login::form();
173         }
174
175         if (!empty($_SESSION['submanage'])) {
176                 return "";
177         }
178
179         // APC deactivated, since there are problems with PHP 5.5
180         //if (function_exists("apc_delete")) {
181         // $toDelete = new APCIterator('user', APC_ITER_VALUE);
182         // apc_delete($toDelete);
183         //}
184         // Header stuff
185         $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('admin/settings_head.tpl'), []);
186
187         /*
188          * Side bar links
189          */
190         $aside_tools = [];
191         // array(url, name, extra css classes)
192         // not part of $aside to make the template more adjustable
193         $aside_sub = [
194                 'information' => [L10n::t('Information'), [
195                         'overview' => ['admin/', L10n::t('Overview'), 'overview'],
196                         'federation'   => ['admin/federation/'  , L10n::t('Federation Statistics'), 'federation']]],
197                 'configuration' => [L10n::t('Configuration'), [
198                         'site'         => ['admin/site/'        , L10n::t('Site')                    , 'site'],
199                         'users'        => ['admin/users/'       , L10n::t('Users')                   , 'users'],
200                         'addons'       => ['admin/addons/'      , L10n::t('Addons')                  , 'addons'],
201                         'themes'       => ['admin/themes/'      , L10n::t('Themes')                  , 'themes'],
202                         'features'     => ['admin/features/'    , L10n::t('Additional features')     , 'features'],
203                         'tos'          => ['admin/tos/'         , L10n::t('Terms of Service')        , 'tos']]],
204                 'database' => [L10n::t('Database'), [
205                         'dbsync'       => ['admin/dbsync/'      , L10n::t('DB updates')              , 'dbsync'],
206                         'queue'        => ['admin/queue/'       , L10n::t('Inspect Queue')           , 'queue'],
207                         'deferred'     => ['admin/deferred/'    , L10n::t('Inspect Deferred Workers'), 'deferred'],
208                         'workerqueue'  => ['admin/workerqueue/' , L10n::t('Inspect worker Queue')    , 'workerqueue']]],
209                 'tools' => [L10n::t('Tools'), [
210                         'contactblock' => ['admin/contactblock/', L10n::t('Contact Blocklist')       , 'contactblock'],
211                         'blocklist'    => ['admin/blocklist/'   , L10n::t('Server Blocklist')        , 'blocklist'],
212                         'deleteitem'   => ['admin/deleteitem/'  , L10n::t('Delete Item')             , 'deleteitem'],]],
213                 'logs' => [L10n::t('Logs'), [
214                         'logsconfig' => ['admin/logs/', L10n::t('Logs'), 'logs'],
215                         'logsview' => ['admin/viewlogs/', L10n::t('View Logs'), 'viewlogs']
216                 ]],
217                 'diagnostics' => [L10n::t('Diagnostics'), [
218                         'phpinfo' => ['phpinfo/', L10n::t('PHP Info'), 'phpinfo'],
219                         'probe' => ['probe/', L10n::t('probe address'), 'probe'],
220                         'webfinger' =>['webfinger/', L10n::t('check webfinger'), 'webfinger']
221                 ]]
222         ];
223
224         /* get addons admin page */
225
226         $r = q("SELECT `name` FROM `addon` WHERE `plugin_admin` = 1 ORDER BY `name`");
227         $aside_tools['addons_admin'] = [];
228         $addons_admin = [];
229         foreach ($r as $h) {
230                 $addon = $h['name'];
231                 $aside_tools['addons_admin'][] = ["admin/addons/" . $addon, $addon, "addon"];
232                 // temp addons with admin
233                 $addons_admin[] = $addon;
234         }
235
236         $t = Renderer::getMarkupTemplate('admin/aside.tpl');
237         $a->page['aside'] .= Renderer::replaceMacros($t, [
238                 '$admin' => $aside_tools,
239                 '$subpages' => $aside_sub,
240                 '$admtxt' => L10n::t('Admin'),
241                 '$plugadmtxt' => L10n::t('Addon Features'),
242                 '$h_pending' => L10n::t('User registrations waiting for confirmation'),
243                 '$admurl' => "admin/"
244         ]);
245
246         // Page content
247         $o = '';
248         // urls
249         if ($a->argc > 1) {
250                 switch ($a->argv[1]) {
251                         case 'site':
252                                 $o = admin_page_site($a);
253                                 break;
254                         case 'users':
255                                 $o = admin_page_users($a);
256                                 break;
257                         case 'addons':
258                                 $o = admin_page_addons($a, $addons_admin);
259                                 break;
260                         case 'themes':
261                                 $o = admin_page_themes($a);
262                                 break;
263                         case 'features':
264                                 $o = admin_page_features($a);
265                                 break;
266                         case 'logs':
267                                 $o = admin_page_logs($a);
268                                 break;
269                         case 'viewlogs':
270                                 $o = admin_page_viewlogs($a);
271                                 break;
272                         case 'dbsync':
273                                 $o = admin_page_dbsync($a);
274                                 break;
275                         case 'queue':
276                                 $o = admin_page_queue($a);
277                                 break;
278                         case 'deferred':
279                                 $o = admin_page_workerqueue($a, true);
280                                 break;
281                         case 'workerqueue':
282                                 $o = admin_page_workerqueue($a, false);
283                                 break;
284                         case 'federation':
285                                 $o = admin_page_federation($a);
286                                 break;
287                         case 'contactblock':
288                                 $o = admin_page_contactblock($a);
289                                 break;
290                         case 'blocklist':
291                                 $o = admin_page_blocklist($a);
292                                 break;
293                         case 'deleteitem':
294                                 $o = admin_page_deleteitem($a);
295                                 break;
296                         case 'tos':
297                                 $o = admin_page_tos($a);
298                                 break;
299                         default:
300                                 notice(L10n::t("Item not found."));
301                 }
302         } else {
303                 $o = admin_page_summary($a);
304         }
305
306         if ($a->isAjax()) {
307                 echo $o;
308                 exit();
309         } else {
310                 return $o;
311         }
312 }
313
314 /**
315  * @brief Subpage to define the display of a Terms of Usage page.
316  *
317  * @param App $a
318  * @return string
319  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
320  */
321 function admin_page_tos(App $a)
322 {
323         $tos = new Tos();
324         $t = Renderer::getMarkupTemplate('admin/tos.tpl');
325         return Renderer::replaceMacros($t, [
326                 '$title' => L10n::t('Administration'),
327                 '$page' => L10n::t('Terms of Service'),
328                 '$displaytos' => ['displaytos', L10n::t('Display Terms of Service'), Config::get('system', 'tosdisplay'), L10n::t('Enable the Terms of Service page. If this is enabled a link to the terms will be added to the registration form and the general information page.')],
329                 '$displayprivstatement' => ['displayprivstatement', L10n::t('Display Privacy Statement'), Config::get('system', 'tosprivstatement'), L10n::t('Show some informations regarding the needed information to operate the node according e.g. to <a href="%s" target="_blank">EU-GDPR</a>.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')],
330                 '$preview' => L10n::t('Privacy Statement Preview'),
331                 '$privtext' => $tos->privacy_complete,
332                 '$tostext' => ['tostext', L10n::t('The Terms of Service'), Config::get('system', 'tostext'), L10n::t('Enter the Terms of Service for your node here. You can use BBCode. Headers of sections should be [h2] and below.')],
333                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_tos"),
334                 '$submit' => L10n::t('Save Settings'),
335         ]);
336 }
337
338 /**
339  * @brief Process send data from Admin TOS Page
340  *
341  * @param App $a
342  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
343  */
344 function admin_page_tos_post(App $a)
345 {
346         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/tos', 'admin_tos');
347
348         if (empty($_POST['page_tos'])) {
349                 return;
350         }
351
352         $displaytos = !empty($_POST['displaytos']);
353         $displayprivstatement = !empty($_POST['displayprivstatement']);
354         $tostext = (!empty($_POST['tostext']) ? strip_tags(trim($_POST['tostext'])) : '');
355
356         Config::set('system', 'tosdisplay', $displaytos);
357         Config::set('system', 'tosprivstatement', $displayprivstatement);
358         Config::set('system', 'tostext', $tostext);
359
360         $a->internalRedirect('admin/tos');
361
362         return; // NOTREACHED
363 }
364
365 /**
366  * @brief Subpage to modify the server wide block list via the admin panel.
367  *
368  * This function generates the subpage of the admin panel to allow the
369  * modification of the node wide block/black list to block entire
370  * remote servers from communication with this node. The page allows
371  * adding, removing and editing of entries from the blocklist.
372  *
373  * @param App $a
374  * @return string
375  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376  */
377 function admin_page_blocklist(App $a)
378 {
379         $blocklist = Config::get('system', 'blocklist');
380         $blocklistform = [];
381         if (is_array($blocklist)) {
382                 foreach ($blocklist as $id => $b) {
383                         $blocklistform[] = [
384                                 'domain' => ["domain[$id]", L10n::t('Blocked domain'), $b['domain'], '', L10n::t('The blocked domain'), 'required', '', ''],
385                                 'reason' => ["reason[$id]", L10n::t("Reason for the block"), $b['reason'], L10n::t('The reason why you blocked this domain.') . '(' . $b['domain'] . ')', 'required', '', ''],
386                                 'delete' => ["delete[$id]", L10n::t("Delete domain") . ' (' . $b['domain'] . ')', false, L10n::t("Check to delete this entry from the blocklist")]
387                         ];
388                 }
389         }
390         $t = Renderer::getMarkupTemplate('admin/blocklist.tpl');
391         return Renderer::replaceMacros($t, [
392                 '$title' => L10n::t('Administration'),
393                 '$page' => L10n::t('Server Blocklist'),
394                 '$intro' => L10n::t('This page can be used to define a black list of servers from the federated network that are not allowed to interact with your node. For all entered domains you should also give a reason why you have blocked the remote server.'),
395                 '$public' => L10n::t('The list of blocked servers will be made publically available on the /friendica page so that your users and people investigating communication problems can find the reason easily.'),
396                 '$addtitle' => L10n::t('Add new entry to block list'),
397                 '$newdomain' => ['newentry_domain', L10n::t('Server Domain'), '', L10n::t('The domain of the new server to add to the block list. Do not include the protocol.'), 'required', '', ''],
398                 '$newreason' => ['newentry_reason', L10n::t('Block reason'), '', L10n::t('The reason why you blocked this domain.'), 'required', '', ''],
399                 '$submit' => L10n::t('Add Entry'),
400                 '$savechanges' => L10n::t('Save changes to the blocklist'),
401                 '$currenttitle' => L10n::t('Current Entries in the Blocklist'),
402                 '$thurl' => L10n::t('Blocked domain'),
403                 '$threason' => L10n::t('Reason for the block'),
404                 '$delentry' => L10n::t('Delete entry from blocklist'),
405                 '$entries' => $blocklistform,
406                 '$baseurl' => System::baseUrl(true),
407                 '$confirm_delete' => L10n::t('Delete entry from blocklist?'),
408                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_blocklist")
409         ]);
410 }
411
412 /**
413  * @brief Process send data from Admin Blocklist Page
414  *
415  * @param App $a
416  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417  */
418 function admin_page_blocklist_post(App $a)
419 {
420         if (empty($_POST['page_blocklist_save']) && empty($_POST['page_blocklist_edit'])) {
421                 return;
422         }
423
424         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/blocklist', 'admin_blocklist');
425
426         if (!empty($_POST['page_blocklist_save'])) {
427                 //  Add new item to blocklist
428                 $blocklist = Config::get('system', 'blocklist');
429                 $blocklist[] = [
430                         'domain' => Strings::escapeTags(trim($_POST['newentry_domain'])),
431                         'reason' => Strings::escapeTags(trim($_POST['newentry_reason']))
432                 ];
433                 Config::set('system', 'blocklist', $blocklist);
434                 info(L10n::t('Server added to blocklist.') . EOL);
435         } else {
436                 // Edit the entries from blocklist
437                 $blocklist = [];
438                 foreach ($_POST['domain'] as $id => $domain) {
439                         // Trimming whitespaces as well as any lingering slashes
440                         $domain = Strings::escapeTags(trim($domain, "\x00..\x1F/"));
441                         $reason = Strings::escapeTags(trim($_POST['reason'][$id]));
442                         if (empty($_POST['delete'][$id])) {
443                                 $blocklist[] = [
444                                         'domain' => $domain,
445                                         'reason' => $reason
446                                 ];
447                         }
448                 }
449                 Config::set('system', 'blocklist', $blocklist);
450                 info(L10n::t('Site blocklist updated.') . EOL);
451         }
452         $a->internalRedirect('admin/blocklist');
453
454         return; // NOTREACHED
455 }
456
457 /**
458  * @brief Process data send by the contact block admin page
459  *
460  * @param App $a
461  * @throws ImagickException
462  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
463  */
464 function admin_page_contactblock_post(App $a)
465 {
466         $contact_url = defaults($_POST, 'contact_url', '');
467         $contacts    = defaults($_POST, 'contacts', []);
468
469         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/contactblock', 'admin_contactblock');
470
471         if (!empty($_POST['page_contactblock_block'])) {
472                 $contact_id = Contact::getIdForURL($contact_url);
473                 if ($contact_id) {
474                         Contact::block($contact_id);
475                         notice(L10n::t('The contact has been blocked from the node'));
476                 } else {
477                         notice(L10n::t("Could not find any contact entry for this URL \x28%s\x29", $contact_url));
478                 }
479         }
480         if (!empty($_POST['page_contactblock_unblock'])) {
481                 foreach ($contacts as $uid) {
482                         Contact::unblock($uid);
483                 }
484                 notice(L10n::tt("%s contact unblocked", "%s contacts unblocked", count($contacts)));
485         }
486         $a->internalRedirect('admin/contactblock');
487         return; // NOTREACHED
488 }
489
490 /**
491  * @brief Admin panel for server-wide contact block
492  *
493  * @param App $a
494  * @return string
495  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
496  */
497 function admin_page_contactblock(App $a)
498 {
499         $condition = ['uid' => 0, 'blocked' => true];
500
501         $total = DBA::count('contact', $condition);
502
503         $pager = new Pager($a->query_string, 30);
504
505         $statement = DBA::select('contact', [], $condition, ['limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
506
507         $contacts = DBA::toArray($statement);
508
509         $t = Renderer::getMarkupTemplate('admin/contactblock.tpl');
510         $o = Renderer::replaceMacros($t, [
511                 // strings //
512                 '$title'       => L10n::t('Administration'),
513                 '$page'        => L10n::t('Remote Contact Blocklist'),
514                 '$description' => L10n::t('This page allows you to prevent any message from a remote contact to reach your node.'),
515                 '$submit'      => L10n::t('Block Remote Contact'),
516                 '$select_all'  => L10n::t('select all'),
517                 '$select_none' => L10n::t('select none'),
518                 '$block'       => L10n::t('Block'),
519                 '$unblock'     => L10n::t('Unblock'),
520                 '$no_data'     => L10n::t('No remote contact is blocked from this node.'),
521
522                 '$h_contacts'  => L10n::t('Blocked Remote Contacts'),
523                 '$h_newblock'  => L10n::t('Block New Remote Contact'),
524                 '$th_contacts' => [L10n::t('Photo'), L10n::t('Name'), L10n::t('Address'), L10n::t('Profile URL')],
525
526                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_contactblock"),
527
528                 // values //
529                 '$baseurl'    => System::baseUrl(true),
530
531                 '$contacts'   => $contacts,
532                 '$total_contacts' => L10n::tt('%s total blocked contact', '%s total blocked contacts', $total),
533                 '$paginate'   => $pager->renderFull($total),
534                 '$contacturl' => ['contact_url', L10n::t("Profile URL"), '', L10n::t("URL of the remote contact to block.")],
535         ]);
536         return $o;
537 }
538
539 /**
540  * @brief Subpage where the admin can delete an item from their node given the GUID
541  *
542  * This subpage of the admin panel offers the nodes admin to delete an item from
543  * the node, given the GUID or the display URL such as http://example.com/display/123456.
544  * The item will then be marked as deleted in the database and processed accordingly.
545  *
546  * @param App $a
547  * @return string
548  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
549  */
550 function admin_page_deleteitem(App $a)
551 {
552         $t = Renderer::getMarkupTemplate('admin/deleteitem.tpl');
553
554         return Renderer::replaceMacros($t, [
555                 '$title' => L10n::t('Administration'),
556                 '$page' => L10n::t('Delete Item'),
557                 '$submit' => L10n::t('Delete this Item'),
558                 '$intro1' => L10n::t('On this page you can delete an item from your node. If the item is a top level posting, the entire thread will be deleted.'),
559                 '$intro2' => L10n::t('You need to know the GUID of the item. You can find it e.g. by looking at the display URL. The last part of http://example.com/display/123456 is the GUID, here 123456.'),
560                 '$deleteitemguid' => ['deleteitemguid', L10n::t("GUID"), '', L10n::t("The GUID of the item you want to delete."), 'required', 'autofocus'],
561                 '$baseurl' => System::baseUrl(),
562                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_deleteitem")
563         ]);
564 }
565
566 /**
567  * @brief Process send data from Admin Delete Item Page
568  *
569  * The GUID passed through the form should be only the GUID. But we also parse
570  * URLs like the full /display URL to make the process more easy for the admin.
571  *
572  * @param App $a
573  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
574  */
575 function admin_page_deleteitem_post(App $a)
576 {
577         if (empty($_POST['page_deleteitem_submit'])) {
578                 return;
579         }
580
581         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/deleteitem/', 'admin_deleteitem');
582
583         if (!empty($_POST['page_deleteitem_submit'])) {
584                 $guid = trim(Strings::escapeTags($_POST['deleteitemguid']));
585                 // The GUID should not include a "/", so if there is one, we got an URL
586                 // and the last part of it is most likely the GUID.
587                 if (strpos($guid, '/')) {
588                         $guid = substr($guid, strrpos($guid, '/') + 1);
589                 }
590                 // Now that we have the GUID, drop those items, which will also delete the
591                 // associated threads.
592                 Item::delete(['guid' => $guid]);
593         }
594
595         info(L10n::t('Item marked for deletion.') . EOL);
596         $a->internalRedirect('admin/deleteitem');
597         return; // NOTREACHED
598 }
599
600 /**
601  * @brief Subpage with some stats about "the federation" network
602  *
603  * This function generates the "Federation Statistics" subpage for the admin
604  * panel. The page lists some numbers to the part of "The Federation" known to
605  * the node. This data includes the different connected networks (e.g.
606  * Diaspora, Hubzilla, GNU Social) and the used versions in the different
607  * networks.
608  *
609  * The returned string contains the HTML code of the subpage for display.
610  *
611  * @param App $a
612  * @return string
613  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
614  */
615 function admin_page_federation(App $a)
616 {
617         // get counts on active friendica, diaspora, redmatrix, hubzilla, gnu
618         // social and statusnet nodes this node is knowing
619         //
620         // We are looking for the following platforms in the DB, "Red" should find
621         // all variants of that platform ID string as the q() function is stripping
622         // off one % two of them are needed in the query
623         // Add more platforms if you like, when one returns 0 known nodes it is not
624         // displayed on the stats page.
625         $platforms = ['Friendi%%a', 'Diaspora', '%%red%%', 'Hubzilla', 'BlaBlaNet', 'GNU Social', 'StatusNet', 'Mastodon', 'Pleroma', 'socialhome', 'ganggo'];
626         $colors = [
627                 'Friendi%%a' => '#ffc018', // orange from the logo
628                 'Diaspora'   => '#a1a1a1', // logo is black and white, makes a gray
629                 '%%red%%'    => '#c50001', // fire red from the logo
630                 'Hubzilla'   => '#43488a', // blue from the logo
631                 'BlaBlaNet'  => '#3B5998', // blue from the navbar at blablanet-dot-com
632                 'GNU Social' => '#a22430', // dark red from the logo
633                 'StatusNet'  => '#789240', // the green from the logo (red and blue have already others
634                 'Mastodon'   => '#1a9df9', // blue from the Mastodon logo
635                 'Pleroma'    => '#E46F0F', // Orange from the text that is used on Pleroma instances
636                 'socialhome' => '#52056b' , // lilac from the Django Image used at the Socialhome homepage
637                 'ganggo'     => '#69d7e2' // from the favicon
638         ];
639         $counts = [];
640         $total = 0;
641         $users = 0;
642
643         foreach ($platforms as $p) {
644                 // get a total count for the platform, the name and version of the
645                 // highest version and the protocol tpe
646                 $c = q('SELECT COUNT(*) AS `total`, SUM(`registered-users`) AS `users`, ANY_VALUE(`platform`) AS `platform`,
647                                 ANY_VALUE(`network`) AS `network`, MAX(`version`) AS `version` FROM `gserver`
648                                 WHERE `platform` LIKE "%s" AND `last_contact` >= `last_failure`
649                                 ORDER BY `version` ASC;', $p);
650                 $total += $c[0]['total'];
651                 $users += $c[0]['users'];
652
653                 // what versions for that platform do we know at all?
654                 // again only the active nodes
655                 $v = q('SELECT COUNT(*) AS `total`, `version` FROM `gserver`
656                                 WHERE `last_contact` >= `last_failure` AND `platform` LIKE "%s"
657                                 GROUP BY `version`
658                                 ORDER BY `version`;', $p);
659
660                 //
661                 // clean up version numbers
662                 //
663                 // some platforms do not provide version information, add a unkown there
664                 // to the version string for the displayed list.
665                 foreach ($v as $key => $value) {
666                         if ($v[$key]['version'] == '') {
667                                 $v[$key] = ['total' => $v[$key]['total'], 'version' => L10n::t('unknown')];
668                         }
669                 }
670
671                 // Reformat and compact version numbers
672                 if ($p == 'Pleroma') {
673                         $compacted = [];
674
675                         foreach ($v as $key => $value) {
676                                 $version = $v[$key]['version'];
677                                 $parts = explode(' ', trim($version));
678                                 do {
679                                         $part = array_pop($parts);
680                                 } while (!empty($parts) && ((strlen($part) >= 40) || (strlen($part) <= 3)));
681
682                                 if (!empty($part)) {
683                                         if (empty($compacted[$part])) {
684                                                 $compacted[$part] = $v[$key]['total'];
685                                         } else {
686                                                 $compacted[$part] += $v[$key]['total'];
687                                         }
688                                 }
689                         }
690
691                         $v = [];
692                         foreach ($compacted as $version => $pl_total) {
693                                 $v[] = ['version' => $version, 'total' => $pl_total];
694                         }
695                 }
696
697                 // in the DB the Diaspora versions have the format x.x.x.x-xx the last
698                 // part (-xx) should be removed to clean up the versions from the "head
699                 // commit" information and combined into a single entry for x.x.x.x
700                 if ($p == 'Diaspora') {
701                         $newV = [];
702                         $newVv = [];
703                         foreach ($v as $vv) {
704                                 $newVC = $vv['total'];
705                                 $newVV = $vv['version'];
706                                 $posDash = strpos($newVV, '-');
707                                 if ($posDash) {
708                                         $newVV = substr($newVV, 0, $posDash);
709                                 }
710                                 if (isset($newV[$newVV])) {
711                                         $newV[$newVV] += $newVC;
712                                 } else {
713                                         $newV[$newVV] = $newVC;
714                                 }
715                         }
716                         foreach ($newV as $key => $value) {
717                                 array_push($newVv, ['total' => $value, 'version' => $key]);
718                         }
719                         $v = $newVv;
720                 }
721
722                 // early friendica versions have the format x.x.xxxx where xxxx is the
723                 // DB version stamp; those should be operated out and versions be
724                 // conbined
725                 if ($p == 'Friendi%%a') {
726                         $newV = [];
727                         $newVv = [];
728                         foreach ($v as $vv) {
729                                 $newVC = $vv['total'];
730                                 $newVV = $vv['version'];
731                                 $lastDot = strrpos($newVV, '.');
732                                 $len = strlen($newVV) - 1;
733                                 if (($lastDot == $len - 4) && (!strrpos($newVV, '-rc') == $len - 3)) {
734                                         $newVV = substr($newVV, 0, $lastDot);
735                                 }
736                                 if (isset($newV[$newVV])) {
737                                         $newV[$newVV] += $newVC;
738                                 } else {
739                                         $newV[$newVV] = $newVC;
740                                 }
741                         }
742                         foreach ($newV as $key => $value) {
743                                 array_push($newVv, ['total' => $value, 'version' => $key]);
744                         }
745                         $v = $newVv;
746                 }
747
748                 // Assure that the versions are sorted correctly
749                 $v2 = [];
750                 $versions = [];
751                 foreach ($v as $vv) {
752                         $version = trim(strip_tags($vv["version"]));
753                         $v2[$version] = $vv;
754                         $versions[] = $version;
755                 }
756
757                 usort($versions, 'version_compare');
758
759                 $v = [];
760                 foreach ($versions as $version) {
761                         $v[] = $v2[$version];
762                 }
763
764                 // the 3rd array item is needed for the JavaScript graphs as JS does
765                 // not like some characters in the names of variables...
766                 $counts[$p] = [$c[0], $v, str_replace([' ', '%'], '', $p), $colors[$p]];
767         }
768
769         // some helpful text
770         $intro = L10n::t('This page offers you some numbers to the known part of the federated social network your Friendica node is part of. These numbers are not complete but only reflect the part of the network your node is aware of.');
771         $hint = L10n::t('The <em>Auto Discovered Contact Directory</em> feature is not enabled, it will improve the data displayed here.');
772
773         // load the template, replace the macros and return the page content
774         $t = Renderer::getMarkupTemplate('admin/federation.tpl');
775         return Renderer::replaceMacros($t, [
776                 '$title' => L10n::t('Administration'),
777                 '$page' => L10n::t('Federation Statistics'),
778                 '$intro' => $intro,
779                 '$hint' => $hint,
780                 '$autoactive' => Config::get('system', 'poco_completion'),
781                 '$counts' => $counts,
782                 '$version' => FRIENDICA_VERSION,
783                 '$legendtext' => L10n::t('Currently this node is aware of %d nodes with %d registered users from the following platforms:', $total, $users),
784                 '$baseurl' => System::baseUrl(),
785         ]);
786 }
787
788 /**
789  * @brief Admin Inspect Queue Page
790  *
791  * Generates a page for the admin to have a look into the current queue of
792  * postings that are not deliverable. Shown are the name and url of the
793  * recipient, the delivery network and the dates when the posting was generated
794  * and the last time tried to deliver the posting.
795  *
796  * The returned string holds the content of the page.
797  *
798  * @param App $a
799  * @return string
800  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
801  */
802 function admin_page_queue(App $a)
803 {
804         // get content from the queue table
805         $entries = DBA::p("SELECT `contact`.`name`, `contact`.`nurl`,
806                 `queue`.`id`, `queue`.`network`, `queue`.`created`, `queue`.`last`
807                 FROM `queue` INNER JOIN `contact` ON `contact`.`id` = `queue`.`cid`
808                 ORDER BY `queue`.`cid`, `queue`.`created`");
809
810         $r = [];
811         while ($entry = DBA::fetch($entries)) {
812                 $entry['created'] = DateTimeFormat::local($entry['created']);
813                 $entry['last'] = DateTimeFormat::local($entry['last']);
814                 $r[] = $entry;
815         }
816         DBA::close($entries);
817
818         $t = Renderer::getMarkupTemplate('admin/queue.tpl');
819         return Renderer::replaceMacros($t, [
820                 '$title' => L10n::t('Administration'),
821                 '$page' => L10n::t('Inspect Queue'),
822                 '$count' => count($r),
823                 'id_header' => L10n::t('ID'),
824                 '$to_header' => L10n::t('Recipient Name'),
825                 '$url_header' => L10n::t('Recipient Profile'),
826                 '$network_header' => L10n::t('Network'),
827                 '$created_header' => L10n::t('Created'),
828                 '$last_header' => L10n::t('Last Tried'),
829                 '$info' => L10n::t('This page lists the content of the queue for outgoing postings. These are postings the initial delivery failed for. They will be resend later and eventually deleted if the delivery fails permanently.'),
830                 '$entries' => $r,
831         ]);
832 }
833
834 /**
835  * @brief Admin Inspect Worker Queue Page
836  *
837  * Generates a page for the admin to have a look into the current queue of
838  * worker jobs. Shown are the parameters for the job and its priority.
839  *
840  * The returned string holds the content of the page.
841  *
842  * @param App $a
843  * @param     $deferred
844  * @return string
845  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
846  */
847 function admin_page_workerqueue(App $a, $deferred)
848 {
849         // get jobs from the workerqueue table
850         if ($deferred) {
851                 $condition = ["NOT `done` AND `next_try` > ?", DateTimeFormat::utcNow()];
852                 $sub_title = L10n::t('Inspect Deferred Worker Queue');
853                 $info = L10n::t("This page lists the deferred worker jobs. This are jobs that couldn't be executed at the first time.");
854         } else {
855                 $condition = ["NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
856                 $sub_title = L10n::t('Inspect Worker Queue');
857                 $info = L10n::t('This page lists the currently queued worker jobs. These jobs are handled by the worker cronjob you\'ve set up during install.');
858         }
859
860         $entries = DBA::select('workerqueue', ['id', 'parameter', 'created', 'priority'], $condition, ['order' => ['priority']]);
861
862         $r = [];
863         while ($entry = DBA::fetch($entries)) {
864                 // fix GH-5469. ref: src/Core/Worker.php:217
865                 $entry['parameter'] = Arrays::recursiveImplode(json_decode($entry['parameter'], true), ': ');
866                 $entry['created'] = DateTimeFormat::local($entry['created']);
867                 $r[] = $entry;
868         }
869         DBA::close($entries);
870
871         $t = Renderer::getMarkupTemplate('admin/workerqueue.tpl');
872         return Renderer::replaceMacros($t, [
873                 '$title' => L10n::t('Administration'),
874                 '$page' => $sub_title,
875                 '$count' => count($r),
876                 '$id_header' => L10n::t('ID'),
877                 '$param_header' => L10n::t('Job Parameters'),
878                 '$created_header' => L10n::t('Created'),
879                 '$prio_header' => L10n::t('Priority'),
880                 '$info' => $info,
881                 '$entries' => $r,
882         ]);
883 }
884
885 /**
886  * @brief Admin Summary Page
887  *
888  * The summary page is the "start page" of the admin panel. It gives the admin
889  * a first overview of the open adminastrative tasks.
890  *
891  * The returned string contains the HTML content of the generated page.
892  *
893  * @param App $a
894  * @return string
895  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
896  */
897 function admin_page_summary(App $a)
898 {
899         // are there MyISAM tables in the DB? If so, trigger a warning message
900         $r = q("SELECT `engine` FROM `information_schema`.`tables` WHERE `engine` = 'myisam' AND `table_schema` = '%s' LIMIT 1", DBA::escape(DBA::databaseName()));
901         $showwarning = false;
902         $warningtext = [];
903         if (DBA::isResult($r)) {
904                 $showwarning = true;
905                 $warningtext[] = L10n::t('Your DB still runs with MyISAM tables. You should change the engine type to InnoDB. As Friendica will use InnoDB only features in the future, you should change this! See <a href="%s">here</a> for a guide that may be helpful converting the table engines. You may also use the command <tt>php bin/console.php dbstructure toinnodb</tt> of your Friendica installation for an automatic conversion.<br />', 'https://dev.mysql.com/doc/refman/5.7/en/converting-tables-to-innodb.html');
906         }
907         // Check if github.com/friendica/master/VERSION is higher then
908         // the local version of Friendica. Check is opt-in, source may be master or devel branch
909         if (Config::get('system', 'check_new_version_url', 'none') != 'none') {
910                 $gitversion = Config::get('system', 'git_friendica_version');
911                 if (version_compare(FRIENDICA_VERSION, $gitversion) < 0) {
912                         $warningtext[] = L10n::t('There is a new version of Friendica available for download. Your current version is %1$s, upstream version is %2$s', FRIENDICA_VERSION, $gitversion);
913                         $showwarning = true;
914                 }
915         }
916
917         if (Config::get('system', 'dbupdate', DBStructure::UPDATE_NOT_CHECKED) == DBStructure::UPDATE_NOT_CHECKED) {
918                 DBStructure::update(false, true);
919         }
920         if (Config::get('system', 'dbupdate') == DBStructure::UPDATE_FAILED) {
921                 $showwarning = true;
922                 $warningtext[] = L10n::t('The database update failed. Please run "php bin/console.php dbstructure update" from the command line and have a look at the errors that might appear.');
923         }
924
925         $last_worker_call = Config::get('system', 'last_worker_execution', false);
926         if (!$last_worker_call) {
927                 $showwarning = true;
928                 $warningtext[] = L10n::t('The worker was never executed. Please check your database structure!');
929         } elseif ((strtotime(DateTimeFormat::utcNow()) - strtotime($last_worker_call)) > 60 * 60) {
930                 $showwarning = true;
931                 $warningtext[] = L10n::t('The last worker execution was on %s UTC. This is older than one hour. Please check your crontab settings.', $last_worker_call);
932         }
933
934         // Legacy config file warning
935         if (file_exists('.htconfig.php')) {
936                 $showwarning = true;
937                 $warningtext[] = L10n::t('Friendica\'s configuration now is stored in config/local.config.php, please copy config/local-sample.config.php and move your config from <code>.htconfig.php</code>. See <a href="%s">the Config help page</a> for help with the transition.', $a->getBaseURL() . '/help/Config');
938         }
939
940         // Check server vitality
941         if (!admin_page_server_vital()) {
942                 $showwarning = true;
943                 $well_known = $a->getBaseURL() . '/.well-known/host-meta';
944                 $warningtext[] = L10n::t('<a href="%s">%s</a> is not reachable on your system. This is a severe configuration issue that prevents server to server communication. See <a href="%s">the installation page</a> for help.',
945                         $well_known, $well_known, $a->getBaseURL() . '/help/Install');
946         }
947
948         $r = q("SELECT `page-flags`, COUNT(`uid`) AS `count` FROM `user` GROUP BY `page-flags`");
949         $accounts = [
950                 [L10n::t('Normal Account'), 0],
951                 [L10n::t('Automatic Follower Account'), 0],
952                 [L10n::t('Public Forum Account'), 0],
953                 [L10n::t('Automatic Friend Account'), 0],
954                 [L10n::t('Blog Account'), 0],
955                 [L10n::t('Private Forum Account'), 0]
956         ];
957
958         $users = 0;
959         foreach ($r as $u) {
960                 $accounts[$u['page-flags']][1] = $u['count'];
961                 $users += $u['count'];
962         }
963
964         Logger::log('accounts: ' . print_r($accounts, true), Logger::DATA);
965
966         $pending = Register::getPendingCount();
967
968         $queue = DBA::count('queue', []);
969
970         $deferred = DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` > ?",
971                 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
972
973         $workerqueue = DBA::count('workerqueue', ["`executed` <= ? AND NOT `done` AND `next_try` < ?",
974                 DBA::NULL_DATETIME, DateTimeFormat::utcNow()]);
975
976         // We can do better, but this is a quick queue status
977
978         $queues = ['label' => L10n::t('Message queues'), 'queue' => $queue, 'deferred' => $deferred, 'workerq' => $workerqueue];
979
980
981         $r = q("SHOW variables LIKE 'max_allowed_packet'");
982         $max_allowed_packet = (($r) ? $r[0]['Value'] : 0);
983
984         $server_settings = ['label' => L10n::t('Server Settings'),
985                 'php' => ['upload_max_filesize' => ini_get('upload_max_filesize'),
986                         'post_max_size' => ini_get('post_max_size'),
987                         'memory_limit' => ini_get('memory_limit')],
988                 'mysql' => ['max_allowed_packet' => $max_allowed_packet]];
989
990         $t = Renderer::getMarkupTemplate('admin/summary.tpl');
991         return Renderer::replaceMacros($t, [
992                 '$title' => L10n::t('Administration'),
993                 '$page' => L10n::t('Summary'),
994                 '$queues' => $queues,
995                 '$users' => [L10n::t('Registered users'), $users],
996                 '$accounts' => $accounts,
997                 '$pending' => [L10n::t('Pending registrations'), $pending],
998                 '$version' => [L10n::t('Version'), FRIENDICA_VERSION],
999                 '$baseurl' => System::baseUrl(),
1000                 '$platform' => FRIENDICA_PLATFORM,
1001                 '$codename' => FRIENDICA_CODENAME,
1002                 '$build' => Config::get('system', 'build'),
1003                 '$addons' => [L10n::t('Active addons'), Addon::getEnabledList()],
1004                 '$serversettings' => $server_settings,
1005                 '$showwarning' => $showwarning,
1006                 '$warningtext' => $warningtext
1007         ]);
1008 }
1009
1010 /**
1011  * @brief Process send data from Admin Site Page
1012  *
1013  * @param App $a
1014  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1015  */
1016 function admin_page_site_post(App $a)
1017 {
1018         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/site', 'admin_site');
1019
1020         if (!empty($_POST['republish_directory'])) {
1021                 Worker::add(PRIORITY_LOW, 'Directory');
1022                 return;
1023         }
1024
1025         if (empty($_POST['page_site'])) {
1026                 return;
1027         }
1028
1029         // relocate
1030         if (!empty($_POST['relocate']) && !empty($_POST['relocate_url']) && $_POST['relocate_url'] != "") {
1031                 $new_url = $_POST['relocate_url'];
1032                 $new_url = rtrim($new_url, "/");
1033
1034                 $parsed = @parse_url($new_url);
1035                 if (!is_array($parsed) || empty($parsed['host']) || empty($parsed['scheme'])) {
1036                         notice(L10n::t("Can not parse base url. Must have at least <scheme>://<domain>"));
1037                         $a->internalRedirect('admin/site');
1038                 }
1039
1040                 /* steps:
1041                  * replace all "baseurl" to "new_url" in config, profile, term, items and contacts
1042                  * send relocate for every local user
1043                  * */
1044
1045                 $old_url = $a->getBaseURL(true);
1046
1047                 // Generate host names for relocation the addresses in the format user@address.tld
1048                 $new_host = str_replace("http://", "@", Strings::normaliseLink($new_url));
1049                 $old_host = str_replace("http://", "@", Strings::normaliseLink($old_url));
1050
1051                 function update_table(App $a, $table_name, $fields, $old_url, $new_url)
1052                 {
1053                         $dbold = DBA::escape($old_url);
1054                         $dbnew = DBA::escape($new_url);
1055
1056                         $upd = [];
1057                         foreach ($fields as $f) {
1058                                 $upd[] = "`$f` = REPLACE(`$f`, '$dbold', '$dbnew')";
1059                         }
1060
1061                         $upds = implode(", ", $upd);
1062
1063                         $r = q("UPDATE %s SET %s;", $table_name, $upds);
1064
1065                         if (!DBA::isResult($r)) {
1066                                 notice("Failed updating '$table_name': " . DBA::errorMessage());
1067                                 $a->internalRedirect('admin/site');
1068                         }
1069                 }
1070
1071                 // update tables
1072                 // update profile links in the format "http://server.tld"
1073                 update_table($a, "profile", ['photo', 'thumb'], $old_url, $new_url);
1074                 update_table($a, "term", ['url'], $old_url, $new_url);
1075                 update_table($a, "contact", ['photo', 'thumb', 'micro', 'url', 'nurl', 'alias', 'request', 'notify', 'poll', 'confirm', 'poco', 'avatar'], $old_url, $new_url);
1076                 update_table($a, "gcontact", ['url', 'nurl', 'photo', 'server_url', 'notify', 'alias'], $old_url, $new_url);
1077                 update_table($a, "item", ['owner-link', 'author-link', 'body', 'plink', 'tag'], $old_url, $new_url);
1078
1079                 // update profile addresses in the format "user@server.tld"
1080                 update_table($a, "contact", ['addr'], $old_host, $new_host);
1081                 update_table($a, "gcontact", ['connect', 'addr'], $old_host, $new_host);
1082
1083                 // update config
1084                 Config::set('system', 'hostname', parse_url($new_url, PHP_URL_HOST));
1085                 Config::set('system', 'url', $new_url);
1086                 $a->setBaseURL($new_url);
1087
1088                 // send relocate
1089                 $users = q("SELECT `uid` FROM `user` WHERE `account_removed` = 0 AND `account_expired` = 0");
1090
1091                 foreach ($users as $user) {
1092                         Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $user['uid']);
1093                 }
1094
1095                 info("Relocation started. Could take a while to complete.");
1096
1097                 $a->internalRedirect('admin/site');
1098         }
1099         // end relocate
1100
1101         $sitename         = (!empty($_POST['sitename'])         ? Strings::escapeTags(trim($_POST['sitename']))      : '');
1102         $hostname         = (!empty($_POST['hostname'])         ? Strings::escapeTags(trim($_POST['hostname']))      : '');
1103         $sender_email     = (!empty($_POST['sender_email'])     ? Strings::escapeTags(trim($_POST['sender_email']))  : '');
1104         $banner           = (!empty($_POST['banner'])           ? trim($_POST['banner'])                             : false);
1105         $shortcut_icon    = (!empty($_POST['shortcut_icon'])    ? Strings::escapeTags(trim($_POST['shortcut_icon'])) : '');
1106         $touch_icon       = (!empty($_POST['touch_icon'])       ? Strings::escapeTags(trim($_POST['touch_icon']))    : '');
1107         $info             = (!empty($_POST['info'])             ? trim($_POST['info'])                               : false);
1108         $language         = (!empty($_POST['language'])         ? Strings::escapeTags(trim($_POST['language']))      : '');
1109         $theme            = (!empty($_POST['theme'])            ? Strings::escapeTags(trim($_POST['theme']))         : '');
1110         $theme_mobile     = (!empty($_POST['theme_mobile'])     ? Strings::escapeTags(trim($_POST['theme_mobile']))  : '');
1111         $maximagesize     = (!empty($_POST['maximagesize'])     ? intval(trim($_POST['maximagesize']))               : 0);
1112         $maximagelength   = (!empty($_POST['maximagelength'])   ? intval(trim($_POST['maximagelength']))             : MAX_IMAGE_LENGTH);
1113         $jpegimagequality = (!empty($_POST['jpegimagequality']) ? intval(trim($_POST['jpegimagequality']))           : JPEG_QUALITY);
1114
1115         $register_policy        = (!empty($_POST['register_policy'])         ? intval(trim($_POST['register_policy']))             : 0);
1116         $daily_registrations    = (!empty($_POST['max_daily_registrations']) ? intval(trim($_POST['max_daily_registrations']))     : 0);
1117         $abandon_days           = (!empty($_POST['abandon_days'])            ? intval(trim($_POST['abandon_days']))                : 0);
1118
1119         $register_text          = (!empty($_POST['register_text'])           ? strip_tags(trim($_POST['register_text']))           : '');
1120
1121         $allowed_sites          = (!empty($_POST['allowed_sites'])           ? Strings::escapeTags(trim($_POST['allowed_sites']))  : '');
1122         $allowed_email          = (!empty($_POST['allowed_email'])           ? Strings::escapeTags(trim($_POST['allowed_email']))  : '');
1123         $forbidden_nicknames    = (!empty($_POST['forbidden_nicknames'])     ? strtolower(Strings::escapeTags(trim($_POST['forbidden_nicknames']))) : '');
1124         $no_oembed_rich_content = !empty($_POST['no_oembed_rich_content']);
1125         $allowed_oembed         = (!empty($_POST['allowed_oembed'])          ? Strings::escapeTags(trim($_POST['allowed_oembed'])) : '');
1126         $block_public           = !empty($_POST['block_public']);
1127         $force_publish          = !empty($_POST['publish_all']);
1128         $global_directory       = (!empty($_POST['directory'])               ? Strings::escapeTags(trim($_POST['directory']))      : '');
1129         $newuser_private        = !empty($_POST['newuser_private']);
1130         $enotify_no_content     = !empty($_POST['enotify_no_content']);
1131         $private_addons         = !empty($_POST['private_addons']);
1132         $disable_embedded       = !empty($_POST['disable_embedded']);
1133         $allow_users_remote_self = !empty($_POST['allow_users_remote_self']);
1134         $explicit_content       = !empty($_POST['explicit_content']);
1135
1136         $no_multi_reg           = !empty($_POST['no_multi_reg']);
1137         $no_openid              = !empty($_POST['no_openid']);
1138         $no_regfullname         = !empty($_POST['no_regfullname']);
1139         $community_page_style   = (!empty($_POST['community_page_style']) ? intval(trim($_POST['community_page_style'])) : 0);
1140         $max_author_posts_community_page = (!empty($_POST['max_author_posts_community_page']) ? intval(trim($_POST['max_author_posts_community_page'])) : 0);
1141
1142         $verifyssl              = !empty($_POST['verifyssl']);
1143         $proxyuser              = (!empty($_POST['proxyuser'])              ? Strings::escapeTags(trim($_POST['proxyuser'])) : '');
1144         $proxy                  = (!empty($_POST['proxy'])                  ? Strings::escapeTags(trim($_POST['proxy']))     : '');
1145         $timeout                = (!empty($_POST['timeout'])                ? intval(trim($_POST['timeout']))                : 60);
1146         $maxloadavg             = (!empty($_POST['maxloadavg'])             ? intval(trim($_POST['maxloadavg']))             : 50);
1147         $maxloadavg_frontend    = (!empty($_POST['maxloadavg_frontend'])    ? intval(trim($_POST['maxloadavg_frontend']))    : 50);
1148         $min_memory             = (!empty($_POST['min_memory'])             ? intval(trim($_POST['min_memory']))             : 0);
1149         $optimize_max_tablesize = (!empty($_POST['optimize_max_tablesize']) ? intval(trim($_POST['optimize_max_tablesize'])) : 100);
1150         $optimize_fragmentation = (!empty($_POST['optimize_fragmentation']) ? intval(trim($_POST['optimize_fragmentation'])) : 30);
1151         $poco_completion        = (!empty($_POST['poco_completion'])        ? intval(trim($_POST['poco_completion']))        : false);
1152         $poco_requery_days      = (!empty($_POST['poco_requery_days'])      ? intval(trim($_POST['poco_requery_days']))      : 7);
1153         $poco_discovery         = (!empty($_POST['poco_discovery'])         ? intval(trim($_POST['poco_discovery']))         : 0);
1154         $poco_discovery_since   = (!empty($_POST['poco_discovery_since'])   ? intval(trim($_POST['poco_discovery_since']))   : 30);
1155         $poco_local_search      = !empty($_POST['poco_local_search']);
1156         $nodeinfo               = !empty($_POST['nodeinfo']);
1157         $dfrn_only              = !empty($_POST['dfrn_only']);
1158         $ostatus_disabled       = !empty($_POST['ostatus_disabled']);
1159         $ostatus_full_threads   = !empty($_POST['ostatus_full_threads']);
1160         $diaspora_enabled       = !empty($_POST['diaspora_enabled']);
1161         $ssl_policy             = (!empty($_POST['ssl_policy'])             ? intval($_POST['ssl_policy'])                    : 0);
1162         $force_ssl              = !empty($_POST['force_ssl']);
1163         $hide_help              = !empty($_POST['hide_help']);
1164         $dbclean                = !empty($_POST['dbclean']);
1165         $dbclean_expire_days    = (!empty($_POST['dbclean_expire_days'])    ? intval($_POST['dbclean_expire_days'])           : 0);
1166         $dbclean_unclaimed      = (!empty($_POST['dbclean_unclaimed'])      ? intval($_POST['dbclean_unclaimed'])             : 0);
1167         $dbclean_expire_conv    = (!empty($_POST['dbclean_expire_conv'])    ? intval($_POST['dbclean_expire_conv'])           : 0);
1168         $suppress_tags          = !empty($_POST['suppress_tags']);
1169         $itemcache              = (!empty($_POST['itemcache'])              ? Strings::escapeTags(trim($_POST['itemcache']))  : '');
1170         $itemcache_duration     = (!empty($_POST['itemcache_duration'])     ? intval($_POST['itemcache_duration'])            : 0);
1171         $max_comments           = (!empty($_POST['max_comments'])           ? intval($_POST['max_comments'])                  : 0);
1172         $temppath               = (!empty($_POST['temppath'])               ? Strings::escapeTags(trim($_POST['temppath']))   : '');
1173         $basepath               = (!empty($_POST['basepath'])               ? Strings::escapeTags(trim($_POST['basepath']))   : '');
1174         $singleuser             = (!empty($_POST['singleuser'])             ? Strings::escapeTags(trim($_POST['singleuser'])) : '');
1175         $proxy_disabled         = !empty($_POST['proxy_disabled']);
1176         $only_tag_search        = !empty($_POST['only_tag_search']);
1177         $rino                   = (!empty($_POST['rino'])                   ? intval($_POST['rino'])                          : 0);
1178         $check_new_version_url  = (!empty($_POST['check_new_version_url'])  ? Strings::escapeTags(trim($_POST['check_new_version_url'])) : 'none');
1179
1180         $worker_queues    = (!empty($_POST['worker_queues'])                ? intval($_POST['worker_queues'])                 : 10);
1181         $worker_dont_fork = !empty($_POST['worker_dont_fork']);
1182         $worker_fastlane  = !empty($_POST['worker_fastlane']);
1183         $worker_frontend  = !empty($_POST['worker_frontend']);
1184
1185         $relay_directly    = !empty($_POST['relay_directly']);
1186         $relay_server      = (!empty($_POST['relay_server'])      ? Strings::escapeTags(trim($_POST['relay_server']))       : '');
1187         $relay_subscribe   = !empty($_POST['relay_subscribe']);
1188         $relay_scope       = (!empty($_POST['relay_scope'])       ? Strings::escapeTags(trim($_POST['relay_scope']))        : '');
1189         $relay_server_tags = (!empty($_POST['relay_server_tags']) ? Strings::escapeTags(trim($_POST['relay_server_tags']))  : '');
1190         $relay_user_tags   = !empty($_POST['relay_user_tags']);
1191         $active_panel      = (!empty($_POST['active_panel'])      ? "#" . Strings::escapeTags(trim($_POST['active_panel'])) : '');
1192
1193         /**
1194          * @var $storagebackend \Friendica\Model\Storage\IStorage
1195          */
1196         $storagebackend    = Strings::escapeTags(trim(defaults($_POST, 'storagebackend', '')));
1197         StorageManager::setBackend($storagebackend);
1198
1199         // save storage backend form
1200         if (!is_null($storagebackend) && $storagebackend != "") {
1201                 $storage_opts = $storagebackend::getOptions();
1202                 $storage_form_prefix=preg_replace('|[^a-zA-Z0-9]|' ,'', $storagebackend);
1203                 $storage_opts_data = [];
1204                 foreach($storage_opts as $name => $info) {
1205                         $fieldname = $storage_form_prefix . '_' . $name;
1206                         switch ($info[0]) { // type
1207                                 case 'checkbox':
1208                                 case 'yesno':
1209                                         $value = !empty($_POST[$fieldname]);
1210                                         break;
1211                                 default:
1212                                         $value = defaults($_POST, $fieldname, '');
1213                         }
1214                         $storage_opts_data[$name] = $value;
1215                 }
1216                 unset($name);
1217                 unset($info);
1218         
1219                 $storage_form_errors = $storagebackend::saveOptions($storage_opts_data);
1220                 if (count($storage_form_errors)) {
1221                         foreach($storage_form_errors as $name => $err) {
1222                                 notice('Storage backend, ' . $storage_opts[$name][1] . ': ' . $err);
1223                         }
1224                         $a->internalRedirect('admin/site' . $active_panel);
1225                 }
1226         }
1227
1228         
1229
1230         // Has the directory url changed? If yes, then resubmit the existing profiles there
1231         if ($global_directory != Config::get('system', 'directory') && ($global_directory != '')) {
1232                 Config::set('system', 'directory', $global_directory);
1233                 Worker::add(PRIORITY_LOW, 'Directory');
1234         }
1235
1236         if ($a->getURLPath() != "") {
1237                 $diaspora_enabled = false;
1238         }
1239         if ($ssl_policy != intval(Config::get('system', 'ssl_policy'))) {
1240                 if ($ssl_policy == SSL_POLICY_FULL) {
1241                         q("UPDATE `contact` SET
1242                                 `url`     = REPLACE(`url`    , 'http:' , 'https:'),
1243                                 `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
1244                                 `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:'),
1245                                 `micro`   = REPLACE(`micro`  , 'http:' , 'https:'),
1246                                 `request` = REPLACE(`request`, 'http:' , 'https:'),
1247                                 `notify`  = REPLACE(`notify` , 'http:' , 'https:'),
1248                                 `poll`    = REPLACE(`poll`   , 'http:' , 'https:'),
1249                                 `confirm` = REPLACE(`confirm`, 'http:' , 'https:'),
1250                                 `poco`    = REPLACE(`poco`   , 'http:' , 'https:')
1251                                 WHERE `self` = 1"
1252                         );
1253                         q("UPDATE `profile` SET
1254                                 `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
1255                                 `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:')
1256                                 WHERE 1 "
1257                         );
1258                 } elseif ($ssl_policy == SSL_POLICY_SELFSIGN) {
1259                         q("UPDATE `contact` SET
1260                                 `url`     = REPLACE(`url`    , 'https:' , 'http:'),
1261                                 `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
1262                                 `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:'),
1263                                 `micro`   = REPLACE(`micro`  , 'https:' , 'http:'),
1264                                 `request` = REPLACE(`request`, 'https:' , 'http:'),
1265                                 `notify`  = REPLACE(`notify` , 'https:' , 'http:'),
1266                                 `poll`    = REPLACE(`poll`   , 'https:' , 'http:'),
1267                                 `confirm` = REPLACE(`confirm`, 'https:' , 'http:'),
1268                                 `poco`    = REPLACE(`poco`   , 'https:' , 'http:')
1269                                 WHERE `self` = 1"
1270                         );
1271                         q("UPDATE `profile` SET
1272                                 `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
1273                                 `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:')
1274                                 WHERE 1 "
1275                         );
1276                 }
1277         }
1278         Config::set('system', 'ssl_policy'            , $ssl_policy);
1279         Config::set('system', 'maxloadavg'            , $maxloadavg);
1280         Config::set('system', 'maxloadavg_frontend'   , $maxloadavg_frontend);
1281         Config::set('system', 'min_memory'            , $min_memory);
1282         Config::set('system', 'optimize_max_tablesize', $optimize_max_tablesize);
1283         Config::set('system', 'optimize_fragmentation', $optimize_fragmentation);
1284         Config::set('system', 'poco_completion'       , $poco_completion);
1285         Config::set('system', 'poco_requery_days'     , $poco_requery_days);
1286         Config::set('system', 'poco_discovery'        , $poco_discovery);
1287         Config::set('system', 'poco_discovery_since'  , $poco_discovery_since);
1288         Config::set('system', 'poco_local_search'     , $poco_local_search);
1289         Config::set('system', 'nodeinfo'              , $nodeinfo);
1290         Config::set('config', 'sitename'              , $sitename);
1291         Config::set('config', 'hostname'              , $hostname);
1292         Config::set('config', 'sender_email'          , $sender_email);
1293         Config::set('system', 'suppress_tags'         , $suppress_tags);
1294         Config::set('system', 'shortcut_icon'         , $shortcut_icon);
1295         Config::set('system', 'touch_icon'            , $touch_icon);
1296
1297         if ($banner == "") {
1298                 Config::delete('system', 'banner');
1299         } else {
1300                 Config::set('system', 'banner', $banner);
1301         }
1302
1303         if (empty($info)) {
1304                 Config::delete('config', 'info');
1305         } else {
1306                 Config::set('config', 'info', $info);
1307         }
1308         Config::set('system', 'language', $language);
1309         Config::set('system', 'theme', $theme);
1310         Theme::install($theme);
1311
1312         if ($theme_mobile == '---') {
1313                 Config::delete('system', 'mobile-theme');
1314         } else {
1315                 Config::set('system', 'mobile-theme', $theme_mobile);
1316         }
1317         if ($singleuser == '---') {
1318                 Config::delete('system', 'singleuser');
1319         } else {
1320                 Config::set('system', 'singleuser', $singleuser);
1321         }
1322         Config::set('system', 'maximagesize'           , $maximagesize);
1323         Config::set('system', 'max_image_length'       , $maximagelength);
1324         Config::set('system', 'jpeg_quality'           , $jpegimagequality);
1325
1326         Config::set('config', 'register_policy'        , $register_policy);
1327         Config::set('system', 'max_daily_registrations', $daily_registrations);
1328         Config::set('system', 'account_abandon_days'   , $abandon_days);
1329         Config::set('config', 'register_text'          , $register_text);
1330         Config::set('system', 'allowed_sites'          , $allowed_sites);
1331         Config::set('system', 'allowed_email'          , $allowed_email);
1332         Config::set('system', 'forbidden_nicknames'    , $forbidden_nicknames);
1333         Config::set('system', 'no_oembed_rich_content' , $no_oembed_rich_content);
1334         Config::set('system', 'allowed_oembed'         , $allowed_oembed);
1335         Config::set('system', 'block_public'           , $block_public);
1336         Config::set('system', 'publish_all'            , $force_publish);
1337         Config::set('system', 'newuser_private'        , $newuser_private);
1338         Config::set('system', 'enotify_no_content'     , $enotify_no_content);
1339         Config::set('system', 'disable_embedded'       , $disable_embedded);
1340         Config::set('system', 'allow_users_remote_self', $allow_users_remote_self);
1341         Config::set('system', 'explicit_content'       , $explicit_content);
1342         Config::set('system', 'check_new_version_url'  , $check_new_version_url);
1343
1344         Config::set('system', 'block_extended_register', $no_multi_reg);
1345         Config::set('system', 'no_openid'              , $no_openid);
1346         Config::set('system', 'no_regfullname'         , $no_regfullname);
1347         Config::set('system', 'community_page_style'   , $community_page_style);
1348         Config::set('system', 'max_author_posts_community_page', $max_author_posts_community_page);
1349         Config::set('system', 'verifyssl'              , $verifyssl);
1350         Config::set('system', 'proxyuser'              , $proxyuser);
1351         Config::set('system', 'proxy'                  , $proxy);
1352         Config::set('system', 'curl_timeout'           , $timeout);
1353         Config::set('system', 'dfrn_only'              , $dfrn_only);
1354         Config::set('system', 'ostatus_disabled'       , $ostatus_disabled);
1355         Config::set('system', 'ostatus_full_threads'   , $ostatus_full_threads);
1356         Config::set('system', 'diaspora_enabled'       , $diaspora_enabled);
1357
1358         Config::set('config', 'private_addons'         , $private_addons);
1359
1360         Config::set('system', 'force_ssl'              , $force_ssl);
1361         Config::set('system', 'hide_help'              , $hide_help);
1362
1363         Config::set('system', 'dbclean'                , $dbclean);
1364         Config::set('system', 'dbclean-expire-days'    , $dbclean_expire_days);
1365         Config::set('system', 'dbclean_expire_conversation', $dbclean_expire_conv);
1366
1367         if ($dbclean_unclaimed == 0) {
1368                 $dbclean_unclaimed = $dbclean_expire_days;
1369         }
1370
1371         Config::set('system', 'dbclean-expire-unclaimed', $dbclean_unclaimed);
1372
1373         if ($itemcache != '') {
1374                 $itemcache = App::getRealPath($itemcache);
1375         }
1376
1377         Config::set('system', 'itemcache', $itemcache);
1378         Config::set('system', 'itemcache_duration', $itemcache_duration);
1379         Config::set('system', 'max_comments', $max_comments);
1380
1381         if ($temppath != '') {
1382                 $temppath = App::getRealPath($temppath);
1383         }
1384
1385         Config::set('system', 'temppath', $temppath);
1386
1387         if ($basepath != '') {
1388                 $basepath = App::getRealPath($basepath);
1389         }
1390
1391         Config::set('system', 'basepath'         , $basepath);
1392         Config::set('system', 'proxy_disabled'   , $proxy_disabled);
1393         Config::set('system', 'only_tag_search'  , $only_tag_search);
1394
1395         Config::set('system', 'worker_queues'    , $worker_queues);
1396         Config::set('system', 'worker_dont_fork' , $worker_dont_fork);
1397         Config::set('system', 'worker_fastlane'  , $worker_fastlane);
1398         Config::set('system', 'frontend_worker'  , $worker_frontend);
1399
1400         Config::set('system', 'relay_directly'   , $relay_directly);
1401         Config::set('system', 'relay_server'     , $relay_server);
1402         Config::set('system', 'relay_subscribe'  , $relay_subscribe);
1403         Config::set('system', 'relay_scope'      , $relay_scope);
1404         Config::set('system', 'relay_server_tags', $relay_server_tags);
1405         Config::set('system', 'relay_user_tags'  , $relay_user_tags);
1406
1407         Config::set('system', 'rino_encrypt'     , $rino);
1408
1409         info(L10n::t('Site settings updated.') . EOL);
1410
1411         $a->internalRedirect('admin/site' . $active_panel);
1412         return; // NOTREACHED
1413 }
1414
1415 /**
1416  * @brief Generate Admin Site subpage
1417  *
1418  * This function generates the main configuration page of the admin panel.
1419  *
1420  * @param  App $a
1421  * @return string
1422  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1423  */
1424 function admin_page_site(App $a)
1425 {
1426         /* Installed langs */
1427         $lang_choices = L10n::getAvailableLanguages();
1428
1429         if (strlen(Config::get('system', 'directory_submit_url')) &&
1430                 !strlen(Config::get('system', 'directory'))) {
1431                 Config::set('system', 'directory', dirname(Config::get('system', 'directory_submit_url')));
1432                 Config::delete('system', 'directory_submit_url');
1433         }
1434
1435         /* Installed themes */
1436         $theme_choices = [];
1437         $theme_choices_mobile = [];
1438         $theme_choices_mobile["---"] = L10n::t("No special theme for mobile devices");
1439         $files = glob('view/theme/*');
1440         if (is_array($files)) {
1441                 $allowed_theme_list = Config::get('system', 'allowed_themes');
1442
1443                 foreach ($files as $file) {
1444                         if (intval(file_exists($file . '/unsupported'))) {
1445                                 continue;
1446                         }
1447
1448                         $f = basename($file);
1449
1450                         // Only show allowed themes here
1451                         if (($allowed_theme_list != '') && !strstr($allowed_theme_list, $f)) {
1452                                 continue;
1453                         }
1454
1455                         $theme_name = ((file_exists($file . '/experimental')) ? sprintf("%s - \x28Experimental\x29", $f) : $f);
1456
1457                         if (file_exists($file . '/mobile')) {
1458                                 $theme_choices_mobile[$f] = $theme_name;
1459                         } else {
1460                                 $theme_choices[$f] = $theme_name;
1461                         }
1462                 }
1463         }
1464
1465         /* Community page style */
1466         $community_page_style_choices = [
1467                 CP_NO_INTERNAL_COMMUNITY => L10n::t("No community page for local users"),
1468                 CP_NO_COMMUNITY_PAGE => L10n::t("No community page"),
1469                 CP_USERS_ON_SERVER => L10n::t("Public postings from users of this site"),
1470                 CP_GLOBAL_COMMUNITY => L10n::t("Public postings from the federated network"),
1471                 CP_USERS_AND_GLOBAL => L10n::t("Public postings from local users and the federated network")
1472         ];
1473
1474         $poco_discovery_choices = [
1475                 "0" => L10n::t("Disabled"),
1476                 "1" => L10n::t("Users"),
1477                 "2" => L10n::t("Users, Global Contacts"),
1478                 "3" => L10n::t("Users, Global Contacts/fallback"),
1479         ];
1480
1481         $poco_discovery_since_choices = [
1482                 "30" => L10n::t("One month"),
1483                 "91" => L10n::t("Three months"),
1484                 "182" => L10n::t("Half a year"),
1485                 "365" => L10n::t("One year"),
1486         ];
1487
1488         /* get user names to make the install a personal install of X */
1489         $user_names = [];
1490         $user_names['---'] = L10n::t('Multi user instance');
1491         $users = q("SELECT `username`, `nickname` FROM `user`");
1492
1493         foreach ($users as $user) {
1494                 $user_names[$user['nickname']] = $user['username'];
1495         }
1496
1497         /* Banner */
1498         $banner = Config::get('system', 'banner');
1499
1500         if ($banner == false) {
1501                 $banner = '<a href="https://friendi.ca"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="https://friendi.ca">Friendica</a></span>';
1502         }
1503
1504         $info = Config::get('config', 'info');
1505
1506         // Automatically create temporary paths
1507         get_temppath();
1508         get_itemcachepath();
1509
1510         //echo "<pre>"; var_dump($lang_choices); die("</pre>");
1511
1512         /* Register policy */
1513         $register_choices = [
1514                 Module\Register::CLOSED => L10n::t("Closed"),
1515                 Module\Register::APPROVE => L10n::t("Requires approval"),
1516                 Module\Register::OPEN => L10n::t("Open")
1517         ];
1518
1519         $ssl_choices = [
1520                 SSL_POLICY_NONE => L10n::t("No SSL policy, links will track page SSL state"),
1521                 SSL_POLICY_FULL => L10n::t("Force all links to use SSL"),
1522                 SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
1523         ];
1524
1525         $check_git_version_choices = [
1526                 "none" => L10n::t("Don't check"),
1527                 "master" => L10n::t("check the stable version"),
1528                 "develop" => L10n::t("check the development version")
1529         ];
1530
1531         if (empty(Config::get('config', 'hostname'))) {
1532                 Config::set('config', 'hostname', $a->getHostName());
1533         }
1534         $diaspora_able = ($a->getURLPath() == "");
1535
1536         $optimize_max_tablesize = Config::get('system', 'optimize_max_tablesize', -1);
1537
1538         if ($optimize_max_tablesize <= 0) {
1539                 $optimize_max_tablesize = -1;
1540         }
1541
1542         /* storage backend */
1543         $storage_backends = StorageManager::listBackends();
1544         /**
1545          * @var $storage_current_backend \Friendica\Model\Storage\IStorage
1546          */
1547         $storage_current_backend = StorageManager::getBackend();
1548
1549         $storage_backends_choices = [
1550                 '' => L10n::t('None')
1551         ];
1552         foreach($storage_backends as $name=>$class) {
1553                 $storage_backends_choices[$class] = $name;
1554         }
1555         unset($storage_backends);
1556
1557         // build storage config form,
1558         $storage_form_prefix=preg_replace('|[^a-zA-Z0-9]|' ,'', $storage_current_backend);
1559         
1560         $storage_form = [];
1561         if (!is_null($storage_current_backend) && $storage_current_backend != "") {
1562                 foreach($storage_current_backend::getOptions() as $name => $info) {
1563                         $type = $info[0];
1564                         $info[0] = $storage_form_prefix . '_' . $name;
1565                         $info['type'] = $type;
1566                         $info['field'] = 'field_' . $type . '.tpl';
1567                         $storage_form[$name] = $info;
1568                 }
1569         }
1570
1571
1572         $t = Renderer::getMarkupTemplate('admin/site.tpl');
1573         return Renderer::replaceMacros($t, [
1574                 '$title'             => L10n::t('Administration'),
1575                 '$page'              => L10n::t('Site'),
1576                 '$submit'            => L10n::t('Save Settings'),
1577                 '$republish'         => L10n::t('Republish users to directory'),
1578                 '$registration'      => L10n::t('Registration'),
1579                 '$upload'            => L10n::t('File upload'),
1580                 '$corporate'         => L10n::t('Policies'),
1581                 '$advanced'          => L10n::t('Advanced'),
1582                 '$portable_contacts' => L10n::t('Auto Discovered Contact Directory'),
1583                 '$performance'       => L10n::t('Performance'),
1584                 '$worker_title'      => L10n::t('Worker'),
1585                 '$relay_title'       => L10n::t('Message Relay'),
1586                 '$relocate'          => L10n::t('Relocate Instance'),
1587                 '$relocate_warning'  => L10n::t('Warning! Advanced function. Could make this server unreachable.'),
1588                 '$baseurl'           => System::baseUrl(true),
1589
1590                 // name, label, value, help string, extra data...
1591                 '$sitename'         => ['sitename', L10n::t("Site name"), Config::get('config', 'sitename'), ''],
1592                 '$hostname'         => ['hostname', L10n::t("Host name"), Config::get('config', 'hostname'), ""],
1593                 '$sender_email'     => ['sender_email', L10n::t("Sender Email"), Config::get('config', 'sender_email'), L10n::t("The email address your server shall use to send notification emails from."), "", "", "email"],
1594                 '$banner'           => ['banner', L10n::t("Banner/Logo"), $banner, ""],
1595                 '$shortcut_icon'    => ['shortcut_icon', L10n::t("Shortcut icon"), Config::get('system', 'shortcut_icon'), L10n::t("Link to an icon that will be used for browsers.")],
1596                 '$touch_icon'       => ['touch_icon', L10n::t("Touch icon"), Config::get('system', 'touch_icon'), L10n::t("Link to an icon that will be used for tablets and mobiles.")],
1597                 '$info'             => ['info', L10n::t('Additional Info'), $info, L10n::t('For public servers: you can add additional information here that will be listed at %s/servers.', get_server())],
1598                 '$language'         => ['language', L10n::t("System language"), Config::get('system', 'language'), "", $lang_choices],
1599                 '$theme'            => ['theme', L10n::t("System theme"), Config::get('system', 'theme'), L10n::t("Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"), $theme_choices],
1600                 '$theme_mobile'     => ['theme_mobile', L10n::t("Mobile system theme"), Config::get('system', 'mobile-theme', '---'), L10n::t("Theme for mobile devices"), $theme_choices_mobile],
1601                 '$ssl_policy'       => ['ssl_policy', L10n::t("SSL link policy"), (string)intval(Config::get('system', 'ssl_policy')), L10n::t("Determines whether generated links should be forced to use SSL"), $ssl_choices],
1602                 '$force_ssl'        => ['force_ssl', L10n::t("Force SSL"), Config::get('system', 'force_ssl'), L10n::t("Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.")],
1603                 '$hide_help'        => ['hide_help', L10n::t("Hide help entry from navigation menu"), Config::get('system', 'hide_help'), L10n::t("Hides the menu entry for the Help pages from the navigation menu. You can still access it calling /help directly.")],
1604                 '$singleuser'       => ['singleuser', L10n::t("Single user instance"), Config::get('system', 'singleuser', '---'), L10n::t("Make this instance multi-user or single-user for the named user"), $user_names],
1605
1606                 '$storagebackend'   => ['storagebackend', L10n::t("File storage backend"), $storage_current_backend, L10n::t('Backend used to store uploaded files data'), $storage_backends_choices],
1607                 '$storageform'      => $storage_form,
1608                 '$maximagesize'     => ['maximagesize', L10n::t("Maximum image size"), Config::get('system', 'maximagesize'), L10n::t("Maximum size in bytes of uploaded images. Default is 0, which means no limits.")],
1609                 '$maximagelength'   => ['maximagelength', L10n::t("Maximum image length"), Config::get('system', 'max_image_length'), L10n::t("Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits.")],
1610                 '$jpegimagequality' => ['jpegimagequality', L10n::t("JPEG image quality"), Config::get('system', 'jpeg_quality'), L10n::t("Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality.")],
1611
1612                 '$register_policy'        => ['register_policy', L10n::t("Register policy"), Config::get('config', 'register_policy'), "", $register_choices],
1613                 '$daily_registrations'    => ['max_daily_registrations', L10n::t("Maximum Daily Registrations"), Config::get('system', 'max_daily_registrations'), L10n::t("If registration is permitted above, this sets the maximum number of new user registrations to accept per day.  If register is set to closed, this setting has no effect.")],
1614                 '$register_text'          => ['register_text', L10n::t("Register text"), Config::get('config', 'register_text'), L10n::t("Will be displayed prominently on the registration page. You can use BBCode here.")],
1615                 '$forbidden_nicknames'    => ['forbidden_nicknames', L10n::t('Forbidden Nicknames'), Config::get('system', 'forbidden_nicknames'), L10n::t('Comma separated list of nicknames that are forbidden from registration. Preset is a list of role names according RFC 2142.')],
1616                 '$abandon_days'           => ['abandon_days', L10n::t('Accounts abandoned after x days'), Config::get('system', 'account_abandon_days'), L10n::t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')],
1617                 '$allowed_sites'          => ['allowed_sites', L10n::t("Allowed friend domains"), Config::get('system', 'allowed_sites'), L10n::t("Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains")],
1618                 '$allowed_email'          => ['allowed_email', L10n::t("Allowed email domains"), Config::get('system', 'allowed_email'), L10n::t("Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains")],
1619                 '$no_oembed_rich_content' => ['no_oembed_rich_content', L10n::t("No OEmbed rich content"), Config::get('system', 'no_oembed_rich_content'), L10n::t("Don't show the rich content \x28e.g. embedded PDF\x29, except from the domains listed below.")],
1620                 '$allowed_oembed'         => ['allowed_oembed', L10n::t("Allowed OEmbed domains"), Config::get('system', 'allowed_oembed'), L10n::t("Comma separated list of domains which oembed content is allowed to be displayed. Wildcards are accepted.")],
1621                 '$block_public'           => ['block_public', L10n::t("Block public"), Config::get('system', 'block_public'), L10n::t("Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.")],
1622                 '$force_publish'          => ['publish_all', L10n::t("Force publish"), Config::get('system', 'publish_all'), L10n::t("Check to force all profiles on this site to be listed in the site directory.") . '<strong>' . L10n::t('Enabling this may violate privacy laws like the GDPR') . '</strong>'],
1623                 '$global_directory'       => ['directory', L10n::t("Global directory URL"), Config::get('system', 'directory', 'https://dir.friendica.social'), L10n::t("URL to the global directory. If this is not set, the global directory is completely unavailable to the application.")],
1624                 '$newuser_private'        => ['newuser_private', L10n::t("Private posts by default for new users"), Config::get('system', 'newuser_private'), L10n::t("Set default post permissions for all new members to the default privacy group rather than public.")],
1625                 '$enotify_no_content'     => ['enotify_no_content', L10n::t("Don't include post content in email notifications"), Config::get('system', 'enotify_no_content'), L10n::t("Don't include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.")],
1626                 '$private_addons'         => ['private_addons', L10n::t("Disallow public access to addons listed in the apps menu."), Config::get('config', 'private_addons'), L10n::t("Checking this box will restrict addons listed in the apps menu to members only.")],
1627                 '$disable_embedded'       => ['disable_embedded', L10n::t("Don't embed private images in posts"), Config::get('system', 'disable_embedded'), L10n::t("Don't replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.")],
1628                 '$explicit_content'       => ['explicit_content', L10n::t('Explicit Content'), Config::get('system', 'explicit_content', false), L10n::t('Set this to announce that your node is used mostly for explicit content that might not be suited for minors. This information will be published in the node information and might be used, e.g. by the global directory, to filter your node from listings of nodes to join. Additionally a note about this will be shown at the user registration page.')],
1629                 '$allow_users_remote_self'=> ['allow_users_remote_self', L10n::t('Allow Users to set remote_self'), Config::get('system', 'allow_users_remote_self'), L10n::t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')],
1630                 '$no_multi_reg'           => ['no_multi_reg', L10n::t("Block multiple registrations"), Config::get('system', 'block_extended_register'), L10n::t("Disallow users to register additional accounts for use as pages.")],
1631                 '$no_openid'              => ['no_openid', L10n::t("Disable OpenID"), Config::get('system', 'no_openid'), L10n::t("Disable OpenID support for registration and logins.")],
1632                 '$no_regfullname'         => ['no_regfullname', L10n::t("No Fullname check"), Config::get('system', 'no_regfullname'), L10n::t("Allow users to register without a space between the first name and the last name in their full name.")],
1633                 '$community_page_style'   => ['community_page_style', L10n::t("Community pages for visitors"), Config::get('system', 'community_page_style'), L10n::t("Which community pages should be available for visitors. Local users always see both pages."), $community_page_style_choices],
1634                 '$max_author_posts_community_page' => ['max_author_posts_community_page', L10n::t("Posts per user on community page"), Config::get('system', 'max_author_posts_community_page'), L10n::t("The maximum number of posts per user on the community page. \x28Not valid for 'Global Community'\x29")],
1635                 '$ostatus_disabled'       => ['ostatus_disabled', L10n::t("Disable OStatus support"), Config::get('system', 'ostatus_disabled'), L10n::t("Disable built-in OStatus (StatusNet, GNU Social etc.) compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.")],
1636                 '$ostatus_full_threads'   => ['ostatus_full_threads', L10n::t("Only import OStatus/ActivityPub threads from our contacts"), Config::get('system', 'ostatus_full_threads'), L10n::t("Normally we import every content from our OStatus and ActivityPub contacts. With this option we only store threads that are started by a contact that is known on our system.")],
1637                 '$ostatus_not_able'       => L10n::t("OStatus support can only be enabled if threading is enabled."),
1638                 '$diaspora_able'          => $diaspora_able,
1639                 '$diaspora_not_able'      => L10n::t("Diaspora support can't be enabled because Friendica was installed into a sub directory."),
1640                 '$diaspora_enabled'       => ['diaspora_enabled', L10n::t("Enable Diaspora support"), Config::get('system', 'diaspora_enabled', $diaspora_able), L10n::t("Provide built-in Diaspora network compatibility.")],
1641                 '$dfrn_only'              => ['dfrn_only', L10n::t('Only allow Friendica contacts'), Config::get('system', 'dfrn_only'), L10n::t("All contacts must use Friendica protocols. All other built-in communication protocols disabled.")],
1642                 '$verifyssl'              => ['verifyssl', L10n::t("Verify SSL"), Config::get('system', 'verifyssl'), L10n::t("If you wish, you can turn on strict certificate checking. This will mean you cannot connect \x28at all\x29 to self-signed SSL sites.")],
1643                 '$proxyuser'              => ['proxyuser', L10n::t("Proxy user"), Config::get('system', 'proxyuser'), ""],
1644                 '$proxy'                  => ['proxy', L10n::t("Proxy URL"), Config::get('system', 'proxy'), ""],
1645                 '$timeout'                => ['timeout', L10n::t("Network timeout"), Config::get('system', 'curl_timeout', 60), L10n::t("Value is in seconds. Set to 0 for unlimited \x28not recommended\x29.")],
1646                 '$maxloadavg'             => ['maxloadavg', L10n::t("Maximum Load Average"), Config::get('system', 'maxloadavg', 50), L10n::t("Maximum system load before delivery and poll processes are deferred - default 50.")],
1647                 '$maxloadavg_frontend'    => ['maxloadavg_frontend', L10n::t("Maximum Load Average \x28Frontend\x29"), Config::get('system', 'maxloadavg_frontend', 50), L10n::t("Maximum system load before the frontend quits service - default 50.")],
1648                 '$min_memory'             => ['min_memory', L10n::t("Minimal Memory"), Config::get('system', 'min_memory', 0), L10n::t("Minimal free memory in MB for the worker. Needs access to /proc/meminfo - default 0 \x28deactivated\x29.")],
1649                 '$optimize_max_tablesize' => ['optimize_max_tablesize', L10n::t("Maximum table size for optimization"), $optimize_max_tablesize, L10n::t("Maximum table size \x28in MB\x29 for the automatic optimization. Enter -1 to disable it.")],
1650                 '$optimize_fragmentation' => ['optimize_fragmentation', L10n::t("Minimum level of fragmentation"), Config::get('system', 'optimize_fragmentation', 30), L10n::t("Minimum fragmenation level to start the automatic optimization - default value is 30%.")],
1651
1652                 '$poco_completion'        => ['poco_completion', L10n::t("Periodical check of global contacts"), Config::get('system', 'poco_completion'), L10n::t("If enabled, the global contacts are checked periodically for missing or outdated data and the vitality of the contacts and servers.")],
1653                 '$poco_requery_days'      => ['poco_requery_days', L10n::t("Days between requery"), Config::get('system', 'poco_requery_days'), L10n::t("Number of days after which a server is requeried for his contacts.")],
1654                 '$poco_discovery'         => ['poco_discovery', L10n::t("Discover contacts from other servers"), (string)intval(Config::get('system', 'poco_discovery')), L10n::t("Periodically query other servers for contacts. You can choose between 'users': the users on the remote system, 'Global Contacts': active contacts that are known on the system. The fallback is meant for Redmatrix servers and older friendica servers, where global contacts weren't available. The fallback increases the server load, so the recommened setting is 'Users, Global Contacts'."), $poco_discovery_choices],
1655                 '$poco_discovery_since'   => ['poco_discovery_since', L10n::t("Timeframe for fetching global contacts"), (string)intval(Config::get('system', 'poco_discovery_since')), L10n::t("When the discovery is activated, this value defines the timeframe for the activity of the global contacts that are fetched from other servers."), $poco_discovery_since_choices],
1656                 '$poco_local_search'      => ['poco_local_search', L10n::t("Search the local directory"), Config::get('system', 'poco_local_search'), L10n::t("Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated.")],
1657
1658                 '$nodeinfo'               => ['nodeinfo', L10n::t("Publish server information"), Config::get('system', 'nodeinfo'), L10n::t("If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See <a href='http://the-federation.info/'>the-federation.info</a> for details.")],
1659
1660                 '$check_new_version_url'  => ['check_new_version_url', L10n::t("Check upstream version"), Config::get('system', 'check_new_version_url'), L10n::t("Enables checking for new Friendica versions at github. If there is a new version, you will be informed in the admin panel overview."), $check_git_version_choices],
1661                 '$suppress_tags'          => ['suppress_tags', L10n::t("Suppress Tags"), Config::get('system', 'suppress_tags'), L10n::t("Suppress showing a list of hashtags at the end of the posting.")],
1662                 '$dbclean'                => ['dbclean', L10n::t("Clean database"), Config::get('system', 'dbclean', false), L10n::t("Remove old remote items, orphaned database records and old content from some other helper tables.")],
1663                 '$dbclean_expire_days'    => ['dbclean_expire_days', L10n::t("Lifespan of remote items"), Config::get('system', 'dbclean-expire-days', 0), L10n::t("When the database cleanup is enabled, this defines the days after which remote items will be deleted. Own items, and marked or filed items are always kept. 0 disables this behaviour.")],
1664                 '$dbclean_unclaimed'      => ['dbclean_unclaimed', L10n::t("Lifespan of unclaimed items"), Config::get('system', 'dbclean-expire-unclaimed', 90), L10n::t("When the database cleanup is enabled, this defines the days after which unclaimed remote items (mostly content from the relay) will be deleted. Default value is 90 days. Defaults to the general lifespan value of remote items if set to 0.")],
1665                 '$dbclean_expire_conv'    => ['dbclean_expire_conv', L10n::t("Lifespan of raw conversation data"), Config::get('system', 'dbclean_expire_conversation', 90), L10n::t("The conversation data is used for ActivityPub and OStatus, as well as for debug purposes. It should be safe to remove it after 14 days, default is 90 days.")],
1666                 '$itemcache'              => ['itemcache', L10n::t("Path to item cache"), Config::get('system', 'itemcache'), L10n::t("The item caches buffers generated bbcode and external images.")],
1667                 '$itemcache_duration'     => ['itemcache_duration', L10n::t("Cache duration in seconds"), Config::get('system', 'itemcache_duration'), L10n::t("How long should the cache files be hold? Default value is 86400 seconds \x28One day\x29. To disable the item cache, set the value to -1.")],
1668                 '$max_comments'           => ['max_comments', L10n::t("Maximum numbers of comments per post"), Config::get('system', 'max_comments'), L10n::t("How much comments should be shown for each post? Default value is 100.")],
1669                 '$temppath'               => ['temppath', L10n::t("Temp path"), Config::get('system', 'temppath'), L10n::t("If you have a restricted system where the webserver can't access the system temp path, enter another path here.")],
1670                 '$basepath'               => ['basepath', L10n::t("Base path to installation"), Config::get('system', 'basepath'), L10n::t("If the system cannot detect the correct path to your installation, enter the correct path here. This setting should only be set if you are using a restricted system and symbolic links to your webroot.")],
1671                 '$proxy_disabled'         => ['proxy_disabled', L10n::t("Disable picture proxy"), Config::get('system', 'proxy_disabled'), L10n::t("The picture proxy increases performance and privacy. It shouldn't be used on systems with very low bandwidth.")],
1672                 '$only_tag_search'        => ['only_tag_search', L10n::t("Only search in tags"), Config::get('system', 'only_tag_search'), L10n::t("On large systems the text search can slow down the system extremely.")],
1673
1674                 '$relocate_url'           => ['relocate_url', L10n::t("New base url"), System::baseUrl(), L10n::t("Change base url for this server. Sends relocate message to all Friendica and Diaspora* contacts of all users.")],
1675
1676                 '$rino'                   => ['rino', L10n::t("RINO Encryption"), intval(Config::get('system', 'rino_encrypt')), L10n::t("Encryption layer between nodes."), [0 => L10n::t("Disabled"), 1 => L10n::t("Enabled")]],
1677
1678                 '$worker_queues'          => ['worker_queues', L10n::t("Maximum number of parallel workers"), Config::get('system', 'worker_queues'), L10n::t("On shared hosters set this to %d. On larger systems, values of %d are great. Default value is %d.", 5, 20, 10)],
1679                 '$worker_dont_fork'       => ['worker_dont_fork', L10n::t("Don't use 'proc_open' with the worker"), Config::get('system', 'worker_dont_fork'), L10n::t("Enable this if your system doesn't allow the use of 'proc_open'. This can happen on shared hosters. If this is enabled you should increase the frequency of worker calls in your crontab.")],
1680                 '$worker_fastlane'        => ['worker_fastlane', L10n::t("Enable fastlane"), Config::get('system', 'worker_fastlane'), L10n::t("When enabed, the fastlane mechanism starts an additional worker if processes with higher priority are blocked by processes of lower priority.")],
1681                 '$worker_frontend'        => ['worker_frontend', L10n::t('Enable frontend worker'), Config::get('system', 'frontend_worker'), L10n::t('When enabled the Worker process is triggered when backend access is performed \x28e.g. messages being delivered\x29. On smaller sites you might want to call %s/worker on a regular basis via an external cron job. You should only enable this option if you cannot utilize cron/scheduled jobs on your server.', System::baseUrl())],
1682
1683                 '$relay_subscribe'        => ['relay_subscribe', L10n::t("Subscribe to relay"), Config::get('system', 'relay_subscribe'), L10n::t("Enables the receiving of public posts from the relay. They will be included in the search, subscribed tags and on the global community page.")],
1684                 '$relay_server'           => ['relay_server', L10n::t("Relay server"), Config::get('system', 'relay_server', 'https://relay.diasp.org'), L10n::t("Address of the relay server where public posts should be send to. For example https://relay.diasp.org")],
1685                 '$relay_directly'         => ['relay_directly', L10n::t("Direct relay transfer"), Config::get('system', 'relay_directly'), L10n::t("Enables the direct transfer to other servers without using the relay servers")],
1686                 '$relay_scope'            => ['relay_scope', L10n::t("Relay scope"), Config::get('system', 'relay_scope'), L10n::t("Can be 'all' or 'tags'. 'all' means that every public post should be received. 'tags' means that only posts with selected tags should be received."), ['' => L10n::t('Disabled'), 'all' => L10n::t('all'), 'tags' => L10n::t('tags')]],
1687                 '$relay_server_tags'      => ['relay_server_tags', L10n::t("Server tags"), Config::get('system', 'relay_server_tags'), L10n::t("Comma separated list of tags for the 'tags' subscription.")],
1688                 '$relay_user_tags'        => ['relay_user_tags', L10n::t("Allow user tags"), Config::get('system', 'relay_user_tags', true), L10n::t("If enabled, the tags from the saved searches will used for the 'tags' subscription in addition to the 'relay_server_tags'.")],
1689
1690                 '$form_security_token'    => BaseModule::getFormSecurityToken("admin_site"),
1691                 '$relocate_button'        => L10n::t('Start Relocation'),
1692         ]);
1693 }
1694
1695 /**
1696  * @brief Generates admin panel subpage for DB syncronization
1697  *
1698  * This page checks if the database of friendica is in sync with the specs.
1699  * Should this not be the case, it attemps to sync the structure and notifies
1700  * the admin if the automatic process was failing.
1701  *
1702  * The returned string holds the HTML code of the page.
1703  *
1704  * @param App $a
1705  * @return string
1706  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1707  */
1708 function admin_page_dbsync(App $a)
1709 {
1710         $o = '';
1711
1712         if ($a->argc > 3 && intval($a->argv[3]) && $a->argv[2] === 'mark') {
1713                 Config::set('database', 'update_' . intval($a->argv[3]), 'success');
1714                 $curr = Config::get('system', 'build');
1715                 if (intval($curr) == intval($a->argv[3])) {
1716                         Config::set('system', 'build', intval($curr) + 1);
1717                 }
1718                 info(L10n::t('Update has been marked successful') . EOL);
1719                 $a->internalRedirect('admin/dbsync');
1720         }
1721
1722         if (($a->argc > 2) && (intval($a->argv[2]) || ($a->argv[2] === 'check'))) {
1723                 $retval = DBStructure::update(false, true);
1724                 if ($retval === '') {
1725                         $o .= L10n::t("Database structure update %s was successfully applied.", DB_UPDATE_VERSION) . "<br />";
1726                         Config::set('database', 'last_successful_update', DB_UPDATE_VERSION);
1727                         Config::set('database', 'last_successful_update_time', time());
1728                 } else {
1729                         $o .= L10n::t("Executing of database structure update %s failed with error: %s", DB_UPDATE_VERSION, $retval) . "<br />";
1730                 }
1731                 if ($a->argv[2] === 'check') {
1732                         return $o;
1733                 }
1734         }
1735
1736         if ($a->argc > 2 && intval($a->argv[2])) {
1737                 require_once 'update.php';
1738
1739                 $func = 'update_' . intval($a->argv[2]);
1740
1741                 if (function_exists($func)) {
1742                         $retval = $func();
1743
1744                         if ($retval === Update::FAILED) {
1745                                 $o .= L10n::t("Executing %s failed with error: %s", $func, $retval);
1746                         } elseif ($retval === Update::SUCCESS) {
1747                                 $o .= L10n::t('Update %s was successfully applied.', $func);
1748                                 Config::set('database', $func, 'success');
1749                         } else {
1750                                 $o .= L10n::t('Update %s did not return a status. Unknown if it succeeded.', $func);
1751                         }
1752                 } else {
1753                         $o .= L10n::t('There was no additional update function %s that needed to be called.', $func) . "<br />";
1754                         Config::set('database', $func, 'success');
1755                 }
1756
1757                 return $o;
1758         }
1759
1760         $failed = [];
1761         $r = q("SELECT `k`, `v` FROM `config` WHERE `cat` = 'database' ");
1762
1763         if (DBA::isResult($r)) {
1764                 foreach ($r as $rr) {
1765                         $upd = intval(substr($rr['k'], 7));
1766                         if ($upd < 1139 || $rr['v'] === 'success') {
1767                                 continue;
1768                         }
1769                         $failed[] = $upd;
1770                 }
1771         }
1772
1773         if (!count($failed)) {
1774                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure_check.tpl'), [
1775                         '$base' => System::baseUrl(true),
1776                         '$banner' => L10n::t('No failed updates.'),
1777                         '$check' => L10n::t('Check database structure'),
1778                 ]);
1779         } else {
1780                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('failed_updates.tpl'), [
1781                         '$base' => System::baseUrl(true),
1782                         '$banner' => L10n::t('Failed Updates'),
1783                         '$desc' => L10n::t('This does not include updates prior to 1139, which did not return a status.'),
1784                         '$mark' => L10n::t("Mark success \x28if update was manually applied\x29"),
1785                         '$apply' => L10n::t('Attempt to execute this update step automatically'),
1786                         '$failed' => $failed
1787                 ]);
1788         }
1789
1790         return $o;
1791 }
1792
1793 /**
1794  * @brief Process data send by Users admin page
1795  *
1796  * @param App $a
1797  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1798  */
1799 function admin_page_users_post(App $a)
1800 {
1801         $pending     = defaults($_POST, 'pending'          , []);
1802         $users       = defaults($_POST, 'user'             , []);
1803         $nu_name     = defaults($_POST, 'new_user_name'    , '');
1804         $nu_nickname = defaults($_POST, 'new_user_nickname', '');
1805         $nu_email    = defaults($_POST, 'new_user_email'   , '');
1806         $nu_language = Config::get('system', 'language');
1807
1808         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users');
1809
1810         if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) {
1811                 try {
1812                         $result = User::create([
1813                                 'username' => $nu_name,
1814                                 'email' => $nu_email,
1815                                 'nickname' => $nu_nickname,
1816                                 'verified' => 1,
1817                                 'language' => $nu_language
1818                         ]);
1819                 } catch (Exception $ex) {
1820                         notice($ex->getMessage());
1821                         return;
1822                 }
1823
1824                 $user = $result['user'];
1825                 $preamble = Strings::deindent(L10n::t('
1826                         Dear %1$s,
1827                                 the administrator of %2$s has set up an account for you.'));
1828                 $body = Strings::deindent(L10n::t('
1829                         The login details are as follows:
1830
1831                         Site Location:  %1$s
1832                         Login Name:             %2$s
1833                         Password:               %3$s
1834
1835                         You may change your password from your account "Settings" page after logging
1836                         in.
1837
1838                         Please take a few moments to review the other account settings on that page.
1839
1840                         You may also wish to add some basic information to your default profile
1841                         ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1842
1843                         We recommend setting your full name, adding a profile photo,
1844                         adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1845                         perhaps what country you live in; if you do not wish to be more specific
1846                         than that.
1847
1848                         We fully respect your right to privacy, and none of these items are necessary.
1849                         If you are new and do not know anybody here, they may help
1850                         you to make some new and interesting friends.
1851
1852                         If you ever want to delete your account, you can do so at %1$s/removeme
1853
1854                         Thank you and welcome to %4$s.'));
1855
1856                 $preamble = sprintf($preamble, $user['username'], Config::get('config', 'sitename'));
1857                 $body = sprintf($body, System::baseUrl(), $user['nickname'], $result['password'], Config::get('config', 'sitename'));
1858
1859                 notification([
1860                         'type'     => SYSTEM_EMAIL,
1861                         'language' => $user['language'],
1862                         'to_name'  => $user['username'],
1863                         'to_email' => $user['email'],
1864                         'uid'      => $user['uid'],
1865                         'subject'  => L10n::t('Registration details for %s', Config::get('config', 'sitename')),
1866                         'preamble' => $preamble,
1867                         'body'     => $body]);
1868         }
1869
1870         if (!empty($_POST['page_users_block'])) {
1871                 foreach ($users as $uid) {
1872                         q("UPDATE `user` SET `blocked` = 1-`blocked` WHERE `uid` = %s", intval($uid)
1873                         );
1874                 }
1875                 notice(L10n::tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)));
1876         }
1877         if (!empty($_POST['page_users_delete'])) {
1878                 foreach ($users as $uid) {
1879                         if (local_user() != $uid) {
1880                                 User::remove($uid);
1881                         } else {
1882                                 notice(L10n::t('You can\'t remove yourself'));
1883                         }
1884                 }
1885                 notice(L10n::tt("%s user deleted", "%s users deleted", count($users)));
1886         }
1887
1888         if (!empty($_POST['page_users_approve'])) {
1889                 require_once "mod/regmod.php";
1890                 foreach ($pending as $hash) {
1891                         user_allow($hash);
1892                 }
1893         }
1894         if (!empty($_POST['page_users_deny'])) {
1895                 require_once "mod/regmod.php";
1896                 foreach ($pending as $hash) {
1897                         user_deny($hash);
1898                 }
1899         }
1900         $a->internalRedirect('admin/users');
1901         return; // NOTREACHED
1902 }
1903
1904 /**
1905  * @brief Admin panel subpage for User management
1906  *
1907  * This function generates the admin panel page for user management of the
1908  * node. It offers functionality to add/block/delete users and offers some
1909  * statistics about the userbase.
1910  *
1911  * The returned string holds the HTML code of the page.
1912  *
1913  * @param App $a
1914  * @return string
1915  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1916  */
1917 function admin_page_users(App $a)
1918 {
1919         if ($a->argc > 2) {
1920                 $uid = $a->argv[3];
1921                 $user = DBA::selectFirst('user', ['username', 'blocked'], ['uid' => $uid]);
1922                 if (!DBA::isResult($user)) {
1923                         notice('User not found' . EOL);
1924                         $a->internalRedirect('admin/users');
1925                         return ''; // NOTREACHED
1926                 }
1927                 switch ($a->argv[2]) {
1928                         case "delete":
1929                                 if (local_user() != $uid) {
1930                                         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
1931                                         // delete user
1932                                         User::remove($uid);
1933
1934                                         notice(L10n::t("User '%s' deleted", $user['username']));
1935                                 } else {
1936                                         notice(L10n::t('You can\'t remove yourself'));
1937                                 }
1938                                 break;
1939                         case "block":
1940                                 BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
1941                                 q("UPDATE `user` SET `blocked` = %d WHERE `uid` = %s",
1942                                         intval(1 - $user['blocked']),
1943                                         intval($uid)
1944                                 );
1945                                 notice(sprintf(($user['blocked'] ? L10n::t("User '%s' unblocked") : L10n::t("User '%s' blocked")), $user['username']) . EOL);
1946                                 break;
1947                 }
1948                 $a->internalRedirect('admin/users');
1949                 return ''; // NOTREACHED
1950         }
1951
1952         /* get pending */
1953         $pending = Register::getPending();
1954
1955         $pager = new Pager($a->query_string, 100);
1956
1957         /* ordering */
1958         $valid_orders = [
1959                 'contact.name',
1960                 'user.email',
1961                 'user.register_date',
1962                 'user.login_date',
1963                 'lastitem_date',
1964                 'user.page-flags'
1965         ];
1966
1967         $order = "contact.name";
1968         $order_direction = "+";
1969         if (!empty($_GET['o'])) {
1970                 $new_order = $_GET['o'];
1971                 if ($new_order[0] === "-") {
1972                         $order_direction = "-";
1973                         $new_order = substr($new_order, 1);
1974                 }
1975
1976                 if (in_array($new_order, $valid_orders)) {
1977                         $order = $new_order;
1978                 }
1979         }
1980         $sql_order = "`" . str_replace('.', '`.`', $order) . "`";
1981         $sql_order_direction = ($order_direction === "+") ? "ASC" : "DESC";
1982
1983         $users = q("SELECT `user`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`account_expired`, `contact`.`last-item` AS `lastitem_date`
1984                                 FROM `user`
1985                                 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
1986                                 WHERE `user`.`verified`
1987                                 ORDER BY $sql_order $sql_order_direction LIMIT %d, %d", $pager->getStart(), $pager->getItemsPerPage()
1988         );
1989
1990         $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
1991         $_setup_users = function ($e) use ($adminlist) {
1992                 $page_types = [
1993                         User::PAGE_FLAGS_NORMAL    => L10n::t('Normal Account Page'),
1994                         User::PAGE_FLAGS_SOAPBOX   => L10n::t('Soapbox Page'),
1995                         User::PAGE_FLAGS_COMMUNITY => L10n::t('Public Forum'),
1996                         User::PAGE_FLAGS_FREELOVE  => L10n::t('Automatic Friend Page'),
1997                         User::PAGE_FLAGS_PRVGROUP  => L10n::t('Private Forum')
1998                 ];
1999                 $account_types = [
2000                         User::ACCOUNT_TYPE_PERSON       => L10n::t('Personal Page'),
2001                         User::ACCOUNT_TYPE_ORGANISATION => L10n::t('Organisation Page'),
2002                         User::ACCOUNT_TYPE_NEWS         => L10n::t('News Page'),
2003                         User::ACCOUNT_TYPE_COMMUNITY    => L10n::t('Community Forum'),
2004                         User::ACCOUNT_TYPE_RELAY        => L10n::t('Relay'),
2005                 ];
2006
2007                 $e['page_flags_raw'] = $e['page-flags'];
2008                 $e['page-flags'] = $page_types[$e['page-flags']];
2009
2010                 $e['account_type_raw'] = ($e['page_flags_raw'] == 0) ? $e['account-type'] : -1;
2011                 $e['account-type'] = ($e['page_flags_raw'] == 0) ? $account_types[$e['account-type']] : "";
2012
2013                 $e['register_date'] = Temporal::getRelativeDate($e['register_date']);
2014                 $e['login_date'] = Temporal::getRelativeDate($e['login_date']);
2015                 $e['lastitem_date'] = Temporal::getRelativeDate($e['lastitem_date']);
2016                 $e['is_admin'] = in_array($e['email'], $adminlist);
2017                 $e['is_deletable'] = (intval($e['uid']) != local_user());
2018                 $e['deleted'] = ($e['account_removed'] ? Temporal::getRelativeDate($e['account_expires_on']) : False);
2019
2020                 return $e;
2021         };
2022
2023         $users = array_map($_setup_users, $users);
2024
2025
2026         // Get rid of dashes in key names, Smarty3 can't handle them
2027         // and extracting deleted users
2028
2029         $tmp_users = [];
2030         $deleted = [];
2031
2032         while (count($users)) {
2033                 $new_user = [];
2034                 foreach (array_pop($users) as $k => $v) {
2035                         $k = str_replace('-', '_', $k);
2036                         $new_user[$k] = $v;
2037                 }
2038                 if ($new_user['deleted']) {
2039                         array_push($deleted, $new_user);
2040                 } else {
2041                         array_push($tmp_users, $new_user);
2042                 }
2043         }
2044         //Reversing the two array, and moving $tmp_users to $users
2045         array_reverse($deleted);
2046         while (count($tmp_users)) {
2047                 array_push($users, array_pop($tmp_users));
2048         }
2049
2050         $th_users = array_map(null, [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Type')], $valid_orders);
2051
2052         $t = Renderer::getMarkupTemplate('admin/users.tpl');
2053         $o = Renderer::replaceMacros($t, [
2054                 // strings //
2055                 '$title' => L10n::t('Administration'),
2056                 '$page' => L10n::t('Users'),
2057                 '$submit' => L10n::t('Add User'),
2058                 '$select_all' => L10n::t('select all'),
2059                 '$h_pending' => L10n::t('User registrations waiting for confirm'),
2060                 '$h_deleted' => L10n::t('User waiting for permanent deletion'),
2061                 '$th_pending' => [L10n::t('Request date'), L10n::t('Name'), L10n::t('Email')],
2062                 '$no_pending' => L10n::t('No registrations.'),
2063                 '$pendingnotetext' => L10n::t('Note from the user'),
2064                 '$approve' => L10n::t('Approve'),
2065                 '$deny' => L10n::t('Deny'),
2066                 '$delete' => L10n::t('Delete'),
2067                 '$block' => L10n::t('Block'),
2068                 '$blocked' => L10n::t('User blocked'),
2069                 '$unblock' => L10n::t('Unblock'),
2070                 '$siteadmin' => L10n::t('Site admin'),
2071                 '$accountexpired' => L10n::t('Account expired'),
2072
2073                 '$h_users' => L10n::t('Users'),
2074                 '$h_newuser' => L10n::t('New User'),
2075                 '$th_deleted' => [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Permanent deletion')],
2076                 '$th_users' => $th_users,
2077                 '$order_users' => $order,
2078                 '$order_direction_users' => $order_direction,
2079
2080                 '$confirm_delete_multi' => L10n::t('Selected users will be deleted!\n\nEverything these users had posted on this site will be permanently deleted!\n\nAre you sure?'),
2081                 '$confirm_delete' => L10n::t('The user {0} will be deleted!\n\nEverything this user has posted on this site will be permanently deleted!\n\nAre you sure?'),
2082
2083                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_users"),
2084
2085                 // values //
2086                 '$baseurl' => $a->getBaseURL(true),
2087
2088                 '$pending' => $pending,
2089                 'deleted' => $deleted,
2090                 '$users' => $users,
2091                 '$newusername' => ['new_user_name', L10n::t("Name"), '', L10n::t("Name of the new user.")],
2092                 '$newusernickname' => ['new_user_nickname', L10n::t("Nickname"), '', L10n::t("Nickname of the new user.")],
2093                 '$newuseremail' => ['new_user_email', L10n::t("Email"), '', L10n::t("Email address of the new user."), '', '', 'email'],
2094         ]);
2095         $o .= $pager->renderFull(DBA::count('user'));
2096         return $o;
2097 }
2098
2099 /**
2100  * @brief Addons admin page
2101  *
2102  * This function generates the admin panel page for managing addons on the
2103  * friendica node. If an addon name is given a single page showing the details
2104  * for this addon is generated. If no name is given, a list of available
2105  * addons is shown.
2106  *
2107  * The template used for displaying the list of addons and the details of the
2108  * addon are the same as used for the templates.
2109  *
2110  * The returned string returned hulds the HTML code of the page.
2111  *
2112  * @param App   $a
2113  * @param array $addons_admin A list of admin addon names
2114  * @return string
2115  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2116  */
2117 function admin_page_addons(App $a, array $addons_admin)
2118 {
2119         /*
2120          * Single addon
2121          */
2122         if ($a->argc == 3) {
2123                 $addon = $a->argv[2];
2124                 if (!is_file("addon/$addon/$addon.php")) {
2125                         notice(L10n::t("Item not found."));
2126                         return '';
2127                 }
2128
2129                 if (defaults($_GET, 'a', '') == "t") {
2130                         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/addons', 'admin_themes', 't');
2131
2132                         // Toggle addon status
2133                         if (Addon::isEnabled($addon)) {
2134                                 Addon::uninstall($addon);
2135                                 info(L10n::t("Addon %s disabled.", $addon));
2136                         } else {
2137                                 Addon::install($addon);
2138                                 info(L10n::t("Addon %s enabled.", $addon));
2139                         }
2140
2141                         Addon::saveEnabledList();
2142                         $a->internalRedirect('admin/addons');
2143                         return ''; // NOTREACHED
2144                 }
2145
2146                 // display addon details
2147                 if (Addon::isEnabled($addon)) {
2148                         $status = "on";
2149                         $action = L10n::t("Disable");
2150                 } else {
2151                         $status = "off";
2152                         $action = L10n::t("Enable");
2153                 }
2154
2155                 $readme = null;
2156                 if (is_file("addon/$addon/README.md")) {
2157                         $readme = Markdown::convert(file_get_contents("addon/$addon/README.md"), false);
2158                 } elseif (is_file("addon/$addon/README")) {
2159                         $readme = "<pre>" . file_get_contents("addon/$addon/README") . "</pre>";
2160                 }
2161
2162                 $admin_form = "";
2163                 if (in_array($addon, $addons_admin)) {
2164                         require_once "addon/$addon/$addon.php";
2165                         $func = $addon . '_addon_admin';
2166                         $func($a, $admin_form);
2167                 }
2168
2169                 $t = Renderer::getMarkupTemplate('admin/addon_details.tpl');
2170
2171                 return Renderer::replaceMacros($t, [
2172                         '$title' => L10n::t('Administration'),
2173                         '$page' => L10n::t('Addons'),
2174                         '$toggle' => L10n::t('Toggle'),
2175                         '$settings' => L10n::t('Settings'),
2176                         '$baseurl' => $a->getBaseURL(true),
2177
2178                         '$addon' => $addon,
2179                         '$status' => $status,
2180                         '$action' => $action,
2181                         '$info' => Addon::getInfo($addon),
2182                         '$str_author' => L10n::t('Author: '),
2183                         '$str_maintainer' => L10n::t('Maintainer: '),
2184
2185                         '$admin_form' => $admin_form,
2186                         '$function' => 'addons',
2187                         '$screenshot' => '',
2188                         '$readme' => $readme,
2189
2190                         '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
2191                 ]);
2192         }
2193
2194         /*
2195          * List addons
2196          */
2197         if (!empty($_GET['a']) && $_GET['a'] == "r") {
2198                 BaseModule::checkFormSecurityTokenRedirectOnError($a->getBaseURL() . '/admin/addons', 'admin_themes', 't');
2199                 Addon::reload();
2200                 info("Addons reloaded");
2201                 $a->internalRedirect('admin/addons');
2202         }
2203
2204         $addons = [];
2205         $files = glob("addon/*/");
2206         if (is_array($files)) {
2207                 foreach ($files as $file) {
2208                         if (is_dir($file)) {
2209                                 list($tmp, $id) = array_map("trim", explode("/", $file));
2210                                 $info = Addon::getInfo($id);
2211                                 $show_addon = true;
2212
2213                                 // If the addon is unsupported, then only show it, when it is enabled
2214                                 if ((strtolower($info["status"]) == "unsupported") && !Addon::isEnabled($id)) {
2215                                         $show_addon = false;
2216                                 }
2217
2218                                 // Override the above szenario, when the admin really wants to see outdated stuff
2219                                 if (Config::get("system", "show_unsupported_addons")) {
2220                                         $show_addon = true;
2221                                 }
2222
2223                                 if ($show_addon) {
2224                                         $addons[] = [$id, (Addon::isEnabled($id) ? "on" : "off"), $info];
2225                                 }
2226                         }
2227                 }
2228         }
2229
2230         $t = Renderer::getMarkupTemplate('admin/addons.tpl');
2231         return Renderer::replaceMacros($t, [
2232                 '$title' => L10n::t('Administration'),
2233                 '$page' => L10n::t('Addons'),
2234                 '$submit' => L10n::t('Save Settings'),
2235                 '$reload' => L10n::t('Reload active addons'),
2236                 '$baseurl' => System::baseUrl(true),
2237                 '$function' => 'addons',
2238                 '$addons' => $addons,
2239                 '$pcount' => count($addons),
2240                 '$noplugshint' => L10n::t('There are currently no addons available on your node. You can find the official addon repository at %1$s and might find other interesting addons in the open addon registry at %2$s', 'https://github.com/friendica/friendica-addons', 'http://addons.friendi.ca'),
2241                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
2242         ]);
2243 }
2244
2245 /**
2246  * @param array  $themes
2247  * @param string $th
2248  * @param int    $result
2249  */
2250 function toggle_theme(&$themes, $th, &$result)
2251 {
2252         $count = count($themes);
2253         for ($x = 0; $x < $count; $x++) {
2254                 if ($themes[$x]['name'] === $th) {
2255                         if ($themes[$x]['allowed']) {
2256                                 $themes[$x]['allowed'] = 0;
2257                                 $result = 0;
2258                         } else {
2259                                 $themes[$x]['allowed'] = 1;
2260                                 $result = 1;
2261                         }
2262                 }
2263         }
2264 }
2265
2266 /**
2267  * @param array  $themes
2268  * @param string $th
2269  * @return int
2270  */
2271 function theme_status($themes, $th)
2272 {
2273         $count = count($themes);
2274         for ($x = 0; $x < $count; $x++) {
2275                 if ($themes[$x]['name'] === $th) {
2276                         if ($themes[$x]['allowed']) {
2277                                 return 1;
2278                         } else {
2279                                 return 0;
2280                         }
2281                 }
2282         }
2283         return 0;
2284 }
2285
2286 /**
2287  * @param array $themes
2288  * @return string
2289  */
2290 function rebuild_theme_table($themes)
2291 {
2292         $o = '';
2293         if (count($themes)) {
2294                 foreach ($themes as $th) {
2295                         if ($th['allowed']) {
2296                                 if (strlen($o)) {
2297                                         $o .= ',';
2298                                 }
2299                                 $o .= $th['name'];
2300                         }
2301                 }
2302         }
2303         return $o;
2304 }
2305
2306 /**
2307  * @brief Themes admin page
2308  *
2309  * This function generates the admin panel page to control the themes available
2310  * on the friendica node. If the name of a theme is given as parameter a page
2311  * with the details for the theme is shown. Otherwise a list of available
2312  * themes is generated.
2313  *
2314  * The template used for displaying the list of themes and the details of the
2315  * themes are the same as used for the addons.
2316  *
2317  * The returned string contains the HTML code of the admin panel page.
2318  *
2319  * @param App $a
2320  * @return string
2321  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2322  */
2323 function admin_page_themes(App $a)
2324 {
2325         $allowed_themes_str = Config::get('system', 'allowed_themes');
2326         $allowed_themes_raw = explode(',', $allowed_themes_str);
2327         $allowed_themes = [];
2328         if (count($allowed_themes_raw)) {
2329                 foreach ($allowed_themes_raw as $x) {
2330                         if (strlen(trim($x))) {
2331                                 $allowed_themes[] = trim($x);
2332                         }
2333                 }
2334         }
2335
2336         $themes = [];
2337         $files = glob('view/theme/*');
2338         if (is_array($files)) {
2339                 foreach ($files as $file) {
2340                         $f = basename($file);
2341
2342                         // Is there a style file?
2343                         $theme_files = glob('view/theme/' . $f . '/style.*');
2344
2345                         // If not then quit
2346                         if (count($theme_files) == 0) {
2347                                 continue;
2348                         }
2349
2350                         $is_experimental = intval(file_exists($file . '/experimental'));
2351                         $is_supported = 1 - (intval(file_exists($file . '/unsupported')));
2352                         $is_allowed = intval(in_array($f, $allowed_themes));
2353
2354                         if ($is_allowed || $is_supported || Config::get("system", "show_unsupported_themes")) {
2355                                 $themes[] = ['name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed];
2356                         }
2357                 }
2358         }
2359
2360         if (!count($themes)) {
2361                 notice(L10n::t('No themes found.'));
2362                 return '';
2363         }
2364
2365         /*
2366          * Single theme
2367          */
2368
2369         if ($a->argc == 3) {
2370                 $theme = $a->argv[2];
2371                 if (!is_dir("view/theme/$theme")) {
2372                         notice(L10n::t("Item not found."));
2373                         return '';
2374                 }
2375
2376                 if (!empty($_GET['a']) && $_GET['a'] == "t") {
2377                         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/themes', 'admin_themes', 't');
2378
2379                         // Toggle theme status
2380
2381                         toggle_theme($themes, $theme, $result);
2382                         $s = rebuild_theme_table($themes);
2383                         if ($result) {
2384                                 Theme::install($theme);
2385                                 info(sprintf('Theme %s enabled.', $theme));
2386                         } else {
2387                                 Theme::uninstall($theme);
2388                                 info(sprintf('Theme %s disabled.', $theme));
2389                         }
2390
2391                         Config::set('system', 'allowed_themes', $s);
2392                         $a->internalRedirect('admin/themes');
2393                         return ''; // NOTREACHED
2394                 }
2395
2396                 // display theme details
2397                 if (theme_status($themes, $theme)) {
2398                         $status = "on";
2399                         $action = L10n::t("Disable");
2400                 } else {
2401                         $status = "off";
2402                         $action = L10n::t("Enable");
2403                 }
2404
2405                 $readme = null;
2406
2407                 if (is_file("view/theme/$theme/README.md")) {
2408                         $readme = Markdown::convert(file_get_contents("view/theme/$theme/README.md"), false);
2409                 } elseif (is_file("view/theme/$theme/README")) {
2410                         $readme = "<pre>" . file_get_contents("view/theme/$theme/README") . "</pre>";
2411                 }
2412
2413                 $admin_form = '';
2414                 if (is_file("view/theme/$theme/config.php")) {
2415                         require_once "view/theme/$theme/config.php";
2416
2417                         if (function_exists('theme_admin')) {
2418                                 $admin_form = theme_admin($a);
2419                         }
2420                 }
2421
2422                 $screenshot = [Theme::getScreenshot($theme), L10n::t('Screenshot')];
2423                 if (!stristr($screenshot[0], $theme)) {
2424                         $screenshot = null;
2425                 }
2426
2427                 $t = Renderer::getMarkupTemplate('admin/addon_details.tpl');
2428                 return Renderer::replaceMacros($t, [
2429                         '$title' => L10n::t('Administration'),
2430                         '$page' => L10n::t('Themes'),
2431                         '$toggle' => L10n::t('Toggle'),
2432                         '$settings' => L10n::t('Settings'),
2433                         '$baseurl' => System::baseUrl(true),
2434                         '$addon' => $theme . (!empty($_GET['mode']) ? '?mode=' . $_GET['mode'] : ''),
2435                         '$status' => $status,
2436                         '$action' => $action,
2437                         '$info' => Theme::getInfo($theme),
2438                         '$function' => 'themes',
2439                         '$admin_form' => $admin_form,
2440                         '$str_author' => L10n::t('Author: '),
2441                         '$str_maintainer' => L10n::t('Maintainer: '),
2442                         '$screenshot' => $screenshot,
2443                         '$readme' => $readme,
2444
2445                         '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
2446                 ]);
2447         }
2448
2449         // reload active themes
2450         if (!empty($_GET['a']) && $_GET['a'] == "r") {
2451                 BaseModule::checkFormSecurityTokenRedirectOnError(System::baseUrl() . '/admin/themes', 'admin_themes', 't');
2452                 foreach ($themes as $th) {
2453                         if ($th['allowed']) {
2454                                 Theme::uninstall($th['name']);
2455                                 Theme::install($th['name']);
2456                         }
2457                 }
2458                 info("Themes reloaded");
2459                 $a->internalRedirect('admin/themes');
2460         }
2461
2462         /*
2463          * List themes
2464          */
2465
2466         $addons = [];
2467         foreach ($themes as $th) {
2468                 $addons[] = [$th['name'], (($th['allowed']) ? "on" : "off"), Theme::getInfo($th['name'])];
2469         }
2470
2471         $t = Renderer::getMarkupTemplate('admin/addons.tpl');
2472         return Renderer::replaceMacros($t, [
2473                 '$title'               => L10n::t('Administration'),
2474                 '$page'                => L10n::t('Themes'),
2475                 '$submit'              => L10n::t('Save Settings'),
2476                 '$reload'              => L10n::t('Reload active themes'),
2477                 '$baseurl'             => System::baseUrl(true),
2478                 '$function'            => 'themes',
2479                 '$addons'             => $addons,
2480                 '$pcount'              => count($themes),
2481                 '$noplugshint'         => L10n::t('No themes found on the system. They should be placed in %1$s', '<code>/view/themes</code>'),
2482                 '$experimental'        => L10n::t('[Experimental]'),
2483                 '$unsupported'         => L10n::t('[Unsupported]'),
2484                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
2485         ]);
2486 }
2487
2488 /**
2489  * @brief Prosesses data send by Logs admin page
2490  *
2491  * @param App $a
2492  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2493  */
2494 function admin_page_logs_post(App $a)
2495 {
2496         if (!empty($_POST['page_logs'])) {
2497                 BaseModule::checkFormSecurityTokenRedirectOnError('/admin/logs', 'admin_logs');
2498
2499                 $logfile   = (!empty($_POST['logfile']) ? Strings::escapeTags(trim($_POST['logfile'])) : '');
2500                 $debugging = !empty($_POST['debugging']);
2501                 $loglevel  = defaults($_POST, 'loglevel', LogLevel::ERROR);
2502
2503                 Config::set('system', 'logfile', $logfile);
2504                 Config::set('system', 'debugging', $debugging);
2505                 Config::set('system', 'loglevel', $loglevel);
2506         }
2507
2508         info(L10n::t("Log settings updated."));
2509         $a->internalRedirect('admin/logs');
2510         return; // NOTREACHED
2511 }
2512
2513 /**
2514  * @brief Generates admin panel subpage for configuration of the logs
2515  *
2516  * This function take the view/templates/admin_logs.tpl file and generates a
2517  * page where admin can configure the logging of friendica.
2518  *
2519  * Displaying the log is separated from the log config as the logfile can get
2520  * big depending on the settings and changing settings regarding the logs can
2521  * thus waste bandwidth.
2522  *
2523  * The string returned contains the content of the template file with replaced
2524  * macros.
2525  *
2526  * @param App $a
2527  * @return string
2528  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2529  */
2530 function admin_page_logs(App $a)
2531 {
2532         $log_choices = [
2533                 LogLevel::ERROR   => 'Error',
2534                 LogLevel::WARNING => 'Warning',
2535                 LogLevel::NOTICE  => 'Notice',
2536                 LogLevel::INFO    => 'Info',
2537                 LogLevel::DEBUG   => 'Debug',
2538         ];
2539
2540         if (ini_get('log_errors')) {
2541                 $phplogenabled = L10n::t('PHP log currently enabled.');
2542         } else {
2543                 $phplogenabled = L10n::t('PHP log currently disabled.');
2544         }
2545
2546         $t = Renderer::getMarkupTemplate('admin/logs.tpl');
2547
2548         return Renderer::replaceMacros($t, [
2549                 '$title' => L10n::t('Administration'),
2550                 '$page' => L10n::t('Logs'),
2551                 '$submit' => L10n::t('Save Settings'),
2552                 '$clear' => L10n::t('Clear'),
2553                 '$baseurl' => System::baseUrl(true),
2554                 '$logname' => Config::get('system', 'logfile'),
2555                 // name, label, value, help string, extra data...
2556                 '$debugging' => ['debugging', L10n::t("Enable Debugging"), Config::get('system', 'debugging'), ""],
2557                 '$logfile' => ['logfile', L10n::t("Log file"), Config::get('system', 'logfile'), L10n::t("Must be writable by web server. Relative to your Friendica top-level directory.")],
2558                 '$loglevel' => ['loglevel', L10n::t("Log level"), Config::get('system', 'loglevel'), "", $log_choices],
2559                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_logs"),
2560                 '$phpheader' => L10n::t("PHP logging"),
2561                 '$phphint' => L10n::t("To temporarily enable logging of PHP errors and warnings you can prepend the following to the index.php file of your installation. The filename set in the 'error_log' line is relative to the friendica top-level directory and must be writeable by the web server. The option '1' for 'log_errors' and 'display_errors' is to enable these options, set to '0' to disable them."),
2562                 '$phplogcode' => "error_reporting(E_ERROR | E_WARNING | E_PARSE);\nini_set('error_log','php.out');\nini_set('log_errors','1');\nini_set('display_errors', '1');",
2563                 '$phplogenabled' => $phplogenabled,
2564         ]);
2565 }
2566
2567 /**
2568  * @brief Generates admin panel subpage to view the Friendica log
2569  *
2570  * This function loads the template view/templates/admin_viewlogs.tpl to
2571  * display the systemlog content. The filename for the systemlog of friendica
2572  * is relative to the base directory and taken from the config entry 'logfile'
2573  * in the 'system' category.
2574  *
2575  * Displaying the log is separated from the log config as the logfile can get
2576  * big depending on the settings and changing settings regarding the logs can
2577  * thus waste bandwidth.
2578  *
2579  * The string returned contains the content of the template file with replaced
2580  * macros.
2581  *
2582  * @param App $a
2583  * @return string
2584  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2585  */
2586 function admin_page_viewlogs(App $a)
2587 {
2588         $t = Renderer::getMarkupTemplate('admin/viewlogs.tpl');
2589         $f = Config::get('system', 'logfile');
2590         $data = '';
2591
2592         if (!file_exists($f)) {
2593                 $data = L10n::t('Error trying to open <strong>%1$s</strong> log file.\r\n<br/>Check to see if file %1$s exist and is readable.', $f);
2594         } else {
2595                 $fp = fopen($f, 'r');
2596                 if (!$fp) {
2597                         $data = L10n::t('Couldn\'t open <strong>%1$s</strong> log file.\r\n<br/>Check to see if file %1$s is readable.', $f);
2598                 } else {
2599                         $fstat = fstat($fp);
2600                         $size = $fstat['size'];
2601                         if ($size != 0) {
2602                                 if ($size > 5000000 || $size < 0) {
2603                                         $size = 5000000;
2604                                 }
2605                                 $seek = fseek($fp, 0 - $size, SEEK_END);
2606                                 if ($seek === 0) {
2607                                         $data = Strings::escapeHtml(fread($fp, $size));
2608                                         while (!feof($fp)) {
2609                                                 $data .= Strings::escapeHtml(fread($fp, 4096));
2610                                         }
2611                                 }
2612                         }
2613                         fclose($fp);
2614                 }
2615         }
2616         return Renderer::replaceMacros($t, [
2617                 '$title' => L10n::t('Administration'),
2618                 '$page' => L10n::t('View Logs'),
2619                 '$data' => $data,
2620                 '$logname' => Config::get('system', 'logfile')
2621         ]);
2622 }
2623
2624 /**
2625  * @brief Prosesses data send by the features admin page
2626  *
2627  * @param App $a
2628  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2629  */
2630 function admin_page_features_post(App $a)
2631 {
2632         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features');
2633
2634         Logger::log('postvars: ' . print_r($_POST, true), Logger::DATA);
2635
2636         $features = Feature::get(false);
2637
2638         foreach ($features as $fname => $fdata) {
2639                 foreach (array_slice($fdata, 1) as $f) {
2640                         $feature = $f[0];
2641                         $feature_state = 'feature_' . $feature;
2642                         $featurelock = 'featurelock_' . $feature;
2643
2644                         if (!empty($_POST[$feature_state])) {
2645                                 $val = intval($_POST[$feature_state]);
2646                         } else {
2647                                 $val = 0;
2648                         }
2649                         Config::set('feature', $feature, $val);
2650
2651                         if (!empty($_POST[$featurelock])) {
2652                                 Config::set('feature_lock', $feature, $val);
2653                         } else {
2654                                 Config::delete('feature_lock', $feature);
2655                         }
2656                 }
2657         }
2658
2659         $a->internalRedirect('admin/features');
2660         return; // NOTREACHED
2661 }
2662
2663 /**
2664  * @brief Subpage for global additional feature management
2665  *
2666  * This functin generates the subpage 'Manage Additional Features'
2667  * for the admin panel. At this page the admin can set preferences
2668  * for the user settings of the 'additional features'. If needed this
2669  * preferences can be locked through the admin.
2670  *
2671  * The returned string contains the HTML code of the subpage 'Manage
2672  * Additional Features'
2673  *
2674  * @param App $a
2675  * @return string
2676  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2677  */
2678 function admin_page_features(App $a)
2679 {
2680         if (($a->argc > 1) && ($a->getArgumentValue(1) === 'features')) {
2681                 $arr = [];
2682                 $features = Feature::get(false);
2683
2684                 foreach ($features as $fname => $fdata) {
2685                         $arr[$fname] = [];
2686                         $arr[$fname][0] = $fdata[0];
2687                         foreach (array_slice($fdata, 1) as $f) {
2688                                 $set = Config::get('feature', $f[0], $f[3]);
2689                                 $arr[$fname][1][] = [
2690                                         ['feature_' . $f[0], $f[1], $set, $f[2], [L10n::t('Off'), L10n::t('On')]],
2691                                         ['featurelock_' . $f[0], L10n::t('Lock feature %s', $f[1]), (($f[4] !== false) ? "1" : ''), '', [L10n::t('Off'), L10n::t('On')]]
2692                                 ];
2693                         }
2694                 }
2695
2696                 $tpl = Renderer::getMarkupTemplate('admin/settings_features.tpl');
2697                 $o = Renderer::replaceMacros($tpl, [
2698                         '$form_security_token' => BaseModule::getFormSecurityToken("admin_manage_features"),
2699                         '$title' => L10n::t('Manage Additional Features'),
2700                         '$features' => $arr,
2701                         '$submit' => L10n::t('Save Settings'),
2702                 ]);
2703
2704                 return $o;
2705         }
2706 }
2707
2708 function admin_page_server_vital()
2709 {
2710         // Fetch the host-meta to check if this really is a vital server
2711         return Network::curl(System::baseUrl() . '/.well-known/host-meta')->isSuccess();
2712 }