]> git.mxchange.org Git - friendica.git/blob - mod/admin.php
a717943d6baf26b3f1ecd9cb3c0d9670a8e1a0d4
[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\StorageManager;
19 use Friendica\Core\System;
20 use Friendica\Core\Theme;
21 use Friendica\Core\Update;
22 use Friendica\Core\Worker;
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\Protocol\PortableContact;
33 use Friendica\Util\Arrays;
34 use Friendica\Util\BasePath;
35 use Friendica\Util\BaseURL;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\Temporal;
40 use Psr\Log\LogLevel;
41
42 /**
43  * Sets the current theme for theme settings pages.
44  *
45  * This needs to be done before the post() or content() methods are called.
46  *
47  * @param App $a
48  */
49 function admin_init(App $a)
50 {
51         if ($a->argc > 2 && $a->argv[1] == 'themes') {
52                 $theme = $a->argv[2];
53                 if (is_file("view/theme/$theme/config.php")) {
54                         $a->setCurrentTheme($theme);
55                 }
56         }
57 }
58
59 /**
60  * @brief Process send data from the admin panels subpages
61  *
62  * This function acts as relay for processing the data send from the subpages
63  * of the admin panel. Depending on the 1st parameter of the url (argv[1])
64  * specialized functions are called to process the data from the subpages.
65  *
66  * The function itself does not return anything, but the subsequently function
67  * return the HTML for the pages of the admin panel.
68  *
69  * @param App $a
70  * @throws ImagickException
71  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72  */
73 function admin_post(App $a)
74 {
75         if (!is_site_admin()) {
76                 return;
77         }
78
79         // do not allow a page manager to access the admin panel at all.
80
81         if (!empty($_SESSION['submanage'])) {
82                 return;
83         }
84
85         $return_path = 'admin';
86         if ($a->argc > 1) {
87                 switch ($a->argv[1]) {
88                         case 'site':
89                                 admin_page_site_post($a);
90                                 break;
91                         case 'users':
92                                 admin_page_users_post($a);
93                                 break;
94                         case 'addons':
95                                 if ($a->argc > 2 &&
96                                         is_file("addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php")) {
97                                         include_once "addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php";
98                                         if (function_exists($a->argv[2] . '_addon_admin_post')) {
99                                                 $func = $a->argv[2] . '_addon_admin_post';
100                                                 $func($a);
101                                         }
102                                 }
103                                 $return_path = 'admin/addons/' . $a->argv[2];
104                                 break;
105                         case 'themes':
106                                 if ($a->argc < 2) {
107                                         if ($a->isAjax()) {
108                                                 return;
109                                         }
110                                         $a->internalRedirect('admin/');
111                                         return;
112                                 }
113
114                                 $theme = $a->argv[2];
115                                 if (is_file("view/theme/$theme/config.php")) {
116                                         require_once "view/theme/$theme/config.php";
117
118                                         if (function_exists('theme_admin_post')) {
119                                                 theme_admin_post($a);
120                                         }
121                                 }
122
123                                 info(L10n::t('Theme settings updated.'));
124                                 if ($a->isAjax()) {
125                                         return;
126                                 }
127                                 $return_path = 'admin/themes/' . $theme . (!empty($_GET['mode']) ? '?mode=' . $_GET['mode'] : '');
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                         'deferred'     => ['admin/deferred/'    , L10n::t('Inspect Deferred Workers'), 'deferred'],
207                         'workerqueue'  => ['admin/workerqueue/' , L10n::t('Inspect worker Queue')    , 'workerqueue']]],
208                 'tools' => [L10n::t('Tools'), [
209                         'contactblock' => ['admin/contactblock/', L10n::t('Contact Blocklist')       , 'contactblock'],
210                         'blocklist'    => ['admin/blocklist/'   , L10n::t('Server Blocklist')        , 'blocklist'],
211                         'deleteitem'   => ['admin/deleteitem/'  , L10n::t('Delete Item')             , 'deleteitem'],]],
212                 'logs' => [L10n::t('Logs'), [
213                         'logsconfig' => ['admin/logs/', L10n::t('Logs'), 'logs'],
214                         'logsview' => ['admin/viewlogs/', L10n::t('View Logs'), 'viewlogs']
215                 ]],
216                 'diagnostics' => [L10n::t('Diagnostics'), [
217                         'phpinfo' => ['phpinfo/', L10n::t('PHP Info'), 'phpinfo'],
218                         'probe' => ['probe/', L10n::t('probe address'), 'probe'],
219                         'webfinger' =>['webfinger/', L10n::t('check webfinger'), 'webfinger']
220                 ]]
221         ];
222
223         /* get addons admin page */
224
225         $r = q("SELECT `name` FROM `addon` WHERE `plugin_admin` = 1 ORDER BY `name`");
226         $aside_tools['addons_admin'] = [];
227         $addons_admin = [];
228         foreach ($r as $h) {
229                 $addon = $h['name'];
230                 $aside_tools['addons_admin'][] = ["admin/addons/" . $addon, $addon, "addon"];
231                 // temp addons with admin
232                 $addons_admin[] = $addon;
233         }
234
235         $t = Renderer::getMarkupTemplate('admin/aside.tpl');
236         $a->page['aside'] .= Renderer::replaceMacros($t, [
237                 '$admin' => $aside_tools,
238                 '$subpages' => $aside_sub,
239                 '$admtxt' => L10n::t('Admin'),
240                 '$plugadmtxt' => L10n::t('Addon Features'),
241                 '$h_pending' => L10n::t('User registrations waiting for confirmation'),
242                 '$admurl' => "admin/"
243         ]);
244
245         // Page content
246         $o = '';
247         // urls
248         if ($a->argc > 1) {
249                 switch ($a->argv[1]) {
250                         case 'site':
251                                 $o = admin_page_site($a);
252                                 break;
253                         case 'users':
254                                 $o = admin_page_users($a);
255                                 break;
256                         case 'addons':
257                                 $o = admin_page_addons($a, $addons_admin);
258                                 break;
259                         case 'themes':
260                                 $o = admin_page_themes($a);
261                                 break;
262                         case 'features':
263                                 $o = admin_page_features($a);
264                                 break;
265                         case 'logs':
266                                 $o = admin_page_logs($a);
267                                 break;
268                         case 'viewlogs':
269                                 $o = admin_page_viewlogs($a);
270                                 break;
271                         case 'dbsync':
272                                 $o = admin_page_dbsync($a);
273                                 break;
274                         case 'deferred':
275                                 $o = admin_page_workerqueue($a, true);
276                                 break;
277                         case 'workerqueue':
278                                 $o = admin_page_workerqueue($a, false);
279                                 break;
280                         case 'contactblock':
281                                 $o = admin_page_contactblock($a);
282                                 break;
283                         case 'blocklist':
284                                 $o = admin_page_blocklist($a);
285                                 break;
286                         case 'deleteitem':
287                                 $o = admin_page_deleteitem($a);
288                                 break;
289                         default:
290                                 notice(L10n::t("Item not found."));
291                 }
292         }
293
294         if ($a->isAjax()) {
295                 echo $o;
296                 exit();
297         } else {
298                 return $o;
299         }
300 }
301
302 /**
303  * @brief Subpage to modify the server wide block list via the admin panel.
304  *
305  * This function generates the subpage of the admin panel to allow the
306  * modification of the node wide block/black list to block entire
307  * remote servers from communication with this node. The page allows
308  * adding, removing and editing of entries from the blocklist.
309  *
310  * @param App $a
311  * @return string
312  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
313  */
314 function admin_page_blocklist(App $a)
315 {
316         $blocklist = Config::get('system', 'blocklist');
317         $blocklistform = [];
318         if (is_array($blocklist)) {
319                 foreach ($blocklist as $id => $b) {
320                         $blocklistform[] = [
321                                 'domain' => ["domain[$id]", L10n::t('Blocked domain'), $b['domain'], '', L10n::t('The blocked domain'), 'required', '', ''],
322                                 'reason' => ["reason[$id]", L10n::t("Reason for the block"), $b['reason'], L10n::t('The reason why you blocked this domain.') . '(' . $b['domain'] . ')', 'required', '', ''],
323                                 'delete' => ["delete[$id]", L10n::t("Delete domain") . ' (' . $b['domain'] . ')', false, L10n::t("Check to delete this entry from the blocklist")]
324                         ];
325                 }
326         }
327         $t = Renderer::getMarkupTemplate('admin/blocklist.tpl');
328         return Renderer::replaceMacros($t, [
329                 '$title' => L10n::t('Administration'),
330                 '$page' => L10n::t('Server Blocklist'),
331                 '$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.'),
332                 '$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.'),
333                 '$addtitle' => L10n::t('Add new entry to block list'),
334                 '$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', '', ''],
335                 '$newreason' => ['newentry_reason', L10n::t('Block reason'), '', L10n::t('The reason why you blocked this domain.'), 'required', '', ''],
336                 '$submit' => L10n::t('Add Entry'),
337                 '$savechanges' => L10n::t('Save changes to the blocklist'),
338                 '$currenttitle' => L10n::t('Current Entries in the Blocklist'),
339                 '$thurl' => L10n::t('Blocked domain'),
340                 '$threason' => L10n::t('Reason for the block'),
341                 '$delentry' => L10n::t('Delete entry from blocklist'),
342                 '$entries' => $blocklistform,
343                 '$baseurl' => System::baseUrl(true),
344                 '$confirm_delete' => L10n::t('Delete entry from blocklist?'),
345                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_blocklist")
346         ]);
347 }
348
349 /**
350  * @brief Process send data from Admin Blocklist Page
351  *
352  * @param App $a
353  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
354  */
355 function admin_page_blocklist_post(App $a)
356 {
357         if (empty($_POST['page_blocklist_save']) && empty($_POST['page_blocklist_edit'])) {
358                 return;
359         }
360
361         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/blocklist', 'admin_blocklist');
362
363         if (!empty($_POST['page_blocklist_save'])) {
364                 //  Add new item to blocklist
365                 $blocklist = Config::get('system', 'blocklist');
366                 $blocklist[] = [
367                         'domain' => Strings::escapeTags(trim($_POST['newentry_domain'])),
368                         'reason' => Strings::escapeTags(trim($_POST['newentry_reason']))
369                 ];
370                 Config::set('system', 'blocklist', $blocklist);
371                 info(L10n::t('Server added to blocklist.') . EOL);
372         } else {
373                 // Edit the entries from blocklist
374                 $blocklist = [];
375                 foreach ($_POST['domain'] as $id => $domain) {
376                         // Trimming whitespaces as well as any lingering slashes
377                         $domain = Strings::escapeTags(trim($domain, "\x00..\x1F/"));
378                         $reason = Strings::escapeTags(trim($_POST['reason'][$id]));
379                         if (empty($_POST['delete'][$id])) {
380                                 $blocklist[] = [
381                                         'domain' => $domain,
382                                         'reason' => $reason
383                                 ];
384                         }
385                 }
386                 Config::set('system', 'blocklist', $blocklist);
387                 info(L10n::t('Site blocklist updated.') . EOL);
388         }
389         $a->internalRedirect('admin/blocklist');
390
391         return; // NOTREACHED
392 }
393
394 /**
395  * @brief Process data send by the contact block admin page
396  *
397  * @param App $a
398  * @throws ImagickException
399  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
400  */
401 function admin_page_contactblock_post(App $a)
402 {
403         $contact_url = defaults($_POST, 'contact_url', '');
404         $contacts    = defaults($_POST, 'contacts', []);
405
406         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/contactblock', 'admin_contactblock');
407
408         if (!empty($_POST['page_contactblock_block'])) {
409                 $contact_id = Contact::getIdForURL($contact_url);
410                 if ($contact_id) {
411                         Contact::block($contact_id);
412                         notice(L10n::t('The contact has been blocked from the node'));
413                 } else {
414                         notice(L10n::t("Could not find any contact entry for this URL \x28%s\x29", $contact_url));
415                 }
416         }
417         if (!empty($_POST['page_contactblock_unblock'])) {
418                 foreach ($contacts as $uid) {
419                         Contact::unblock($uid);
420                 }
421                 notice(L10n::tt("%s contact unblocked", "%s contacts unblocked", count($contacts)));
422         }
423         $a->internalRedirect('admin/contactblock');
424         return; // NOTREACHED
425 }
426
427 /**
428  * @brief Admin panel for server-wide contact block
429  *
430  * @param App $a
431  * @return string
432  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433  */
434 function admin_page_contactblock(App $a)
435 {
436         $condition = ['uid' => 0, 'blocked' => true];
437
438         $total = DBA::count('contact', $condition);
439
440         $pager = new Pager($a->query_string, 30);
441
442         $statement = DBA::select('contact', [], $condition, ['limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
443
444         $contacts = DBA::toArray($statement);
445
446         $t = Renderer::getMarkupTemplate('admin/contactblock.tpl');
447         $o = Renderer::replaceMacros($t, [
448                 // strings //
449                 '$title'       => L10n::t('Administration'),
450                 '$page'        => L10n::t('Remote Contact Blocklist'),
451                 '$description' => L10n::t('This page allows you to prevent any message from a remote contact to reach your node.'),
452                 '$submit'      => L10n::t('Block Remote Contact'),
453                 '$select_all'  => L10n::t('select all'),
454                 '$select_none' => L10n::t('select none'),
455                 '$block'       => L10n::t('Block'),
456                 '$unblock'     => L10n::t('Unblock'),
457                 '$no_data'     => L10n::t('No remote contact is blocked from this node.'),
458
459                 '$h_contacts'  => L10n::t('Blocked Remote Contacts'),
460                 '$h_newblock'  => L10n::t('Block New Remote Contact'),
461                 '$th_contacts' => [L10n::t('Photo'), L10n::t('Name'), L10n::t('Address'), L10n::t('Profile URL')],
462
463                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_contactblock"),
464
465                 // values //
466                 '$baseurl'    => System::baseUrl(true),
467
468                 '$contacts'   => $contacts,
469                 '$total_contacts' => L10n::tt('%s total blocked contact', '%s total blocked contacts', $total),
470                 '$paginate'   => $pager->renderFull($total),
471                 '$contacturl' => ['contact_url', L10n::t("Profile URL"), '', L10n::t("URL of the remote contact to block.")],
472         ]);
473         return $o;
474 }
475
476 /**
477  * @brief Subpage where the admin can delete an item from their node given the GUID
478  *
479  * This subpage of the admin panel offers the nodes admin to delete an item from
480  * the node, given the GUID or the display URL such as http://example.com/display/123456.
481  * The item will then be marked as deleted in the database and processed accordingly.
482  *
483  * @param App $a
484  * @return string
485  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
486  */
487 function admin_page_deleteitem(App $a)
488 {
489         $t = Renderer::getMarkupTemplate('admin/deleteitem.tpl');
490
491         return Renderer::replaceMacros($t, [
492                 '$title' => L10n::t('Administration'),
493                 '$page' => L10n::t('Delete Item'),
494                 '$submit' => L10n::t('Delete this Item'),
495                 '$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.'),
496                 '$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.'),
497                 '$deleteitemguid' => ['deleteitemguid', L10n::t("GUID"), '', L10n::t("The GUID of the item you want to delete."), 'required', 'autofocus'],
498                 '$baseurl' => System::baseUrl(),
499                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_deleteitem")
500         ]);
501 }
502
503 /**
504  * @brief Process send data from Admin Delete Item Page
505  *
506  * The GUID passed through the form should be only the GUID. But we also parse
507  * URLs like the full /display URL to make the process more easy for the admin.
508  *
509  * @param App $a
510  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
511  */
512 function admin_page_deleteitem_post(App $a)
513 {
514         if (empty($_POST['page_deleteitem_submit'])) {
515                 return;
516         }
517
518         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/deleteitem/', 'admin_deleteitem');
519
520         if (!empty($_POST['page_deleteitem_submit'])) {
521                 $guid = trim(Strings::escapeTags($_POST['deleteitemguid']));
522                 // The GUID should not include a "/", so if there is one, we got an URL
523                 // and the last part of it is most likely the GUID.
524                 if (strpos($guid, '/')) {
525                         $guid = substr($guid, strrpos($guid, '/') + 1);
526                 }
527                 // Now that we have the GUID, drop those items, which will also delete the
528                 // associated threads.
529                 Item::delete(['guid' => $guid]);
530         }
531
532         info(L10n::t('Item marked for deletion.') . EOL);
533         $a->internalRedirect('admin/deleteitem');
534         return; // NOTREACHED
535 }
536
537 /**
538  * @brief Admin Inspect Worker Queue Page
539  *
540  * Generates a page for the admin to have a look into the current queue of
541  * worker jobs. Shown are the parameters for the job and its priority.
542  *
543  * The returned string holds the content of the page.
544  *
545  * @param App $a
546  * @param     $deferred
547  * @return string
548  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
549  */
550 function admin_page_workerqueue(App $a, $deferred)
551 {
552         // get jobs from the workerqueue table
553         if ($deferred) {
554                 $condition = ["NOT `done` AND `next_try` > ?", DateTimeFormat::utcNow()];
555                 $sub_title = L10n::t('Inspect Deferred Worker Queue');
556                 $info = L10n::t("This page lists the deferred worker jobs. This are jobs that couldn't be executed at the first time.");
557         } else {
558                 $condition = ["NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
559                 $sub_title = L10n::t('Inspect Worker Queue');
560                 $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.');
561         }
562
563         $entries = DBA::select('workerqueue', ['id', 'parameter', 'created', 'priority'], $condition, ['order' => ['priority']]);
564
565         $r = [];
566         while ($entry = DBA::fetch($entries)) {
567                 // fix GH-5469. ref: src/Core/Worker.php:217
568                 $entry['parameter'] = Arrays::recursiveImplode(json_decode($entry['parameter'], true), ': ');
569                 $entry['created'] = DateTimeFormat::local($entry['created']);
570                 $r[] = $entry;
571         }
572         DBA::close($entries);
573
574         $t = Renderer::getMarkupTemplate('admin/workerqueue.tpl');
575         return Renderer::replaceMacros($t, [
576                 '$title' => L10n::t('Administration'),
577                 '$page' => $sub_title,
578                 '$count' => count($r),
579                 '$id_header' => L10n::t('ID'),
580                 '$param_header' => L10n::t('Job Parameters'),
581                 '$created_header' => L10n::t('Created'),
582                 '$prio_header' => L10n::t('Priority'),
583                 '$info' => $info,
584                 '$entries' => $r,
585         ]);
586 }
587
588 /**
589  * @brief Process send data from Admin Site Page
590  *
591  * @param App $a
592  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
593  */
594 function admin_page_site_post(App $a)
595 {
596         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/site', 'admin_site');
597
598         if (!empty($_POST['republish_directory'])) {
599                 Worker::add(PRIORITY_LOW, 'Directory');
600                 return;
601         }
602
603         if (empty($_POST['page_site'])) {
604                 return;
605         }
606
607         // relocate
608         if (!empty($_POST['relocate']) && !empty($_POST['relocate_url']) && $_POST['relocate_url'] != "") {
609                 $new_url = $_POST['relocate_url'];
610                 $new_url = rtrim($new_url, "/");
611
612                 $parsed = @parse_url($new_url);
613                 if (!is_array($parsed) || empty($parsed['host']) || empty($parsed['scheme'])) {
614                         notice(L10n::t("Can not parse base url. Must have at least <scheme>://<domain>"));
615                         $a->internalRedirect('admin/site');
616                 }
617
618                 /* steps:
619                  * replace all "baseurl" to "new_url" in config, profile, term, items and contacts
620                  * send relocate for every local user
621                  * */
622
623                 $old_url = $a->getBaseURL(true);
624
625                 // Generate host names for relocation the addresses in the format user@address.tld
626                 $new_host = str_replace("http://", "@", Strings::normaliseLink($new_url));
627                 $old_host = str_replace("http://", "@", Strings::normaliseLink($old_url));
628
629                 function update_table(App $a, $table_name, $fields, $old_url, $new_url)
630                 {
631                         $dbold = DBA::escape($old_url);
632                         $dbnew = DBA::escape($new_url);
633
634                         $upd = [];
635                         foreach ($fields as $f) {
636                                 $upd[] = "`$f` = REPLACE(`$f`, '$dbold', '$dbnew')";
637                         }
638
639                         $upds = implode(", ", $upd);
640
641                         $r = q("UPDATE %s SET %s;", $table_name, $upds);
642
643                         if (!DBA::isResult($r)) {
644                                 notice("Failed updating '$table_name': " . DBA::errorMessage());
645                                 $a->internalRedirect('admin/site');
646                         }
647                 }
648
649                 // update tables
650                 // update profile links in the format "http://server.tld"
651                 update_table($a, "profile", ['photo', 'thumb'], $old_url, $new_url);
652                 update_table($a, "term", ['url'], $old_url, $new_url);
653                 update_table($a, "contact", ['photo', 'thumb', 'micro', 'url', 'nurl', 'alias', 'request', 'notify', 'poll', 'confirm', 'poco', 'avatar'], $old_url, $new_url);
654                 update_table($a, "gcontact", ['url', 'nurl', 'photo', 'server_url', 'notify', 'alias'], $old_url, $new_url);
655                 update_table($a, "item", ['owner-link', 'author-link', 'body', 'plink', 'tag'], $old_url, $new_url);
656
657                 // update profile addresses in the format "user@server.tld"
658                 update_table($a, "contact", ['addr'], $old_host, $new_host);
659                 update_table($a, "gcontact", ['connect', 'addr'], $old_host, $new_host);
660
661                 // update config
662                 Config::set('system', 'url', $new_url);
663                 $a->setBaseURL($new_url);
664
665                 // send relocate
666                 $users = q("SELECT `uid` FROM `user` WHERE `account_removed` = 0 AND `account_expired` = 0");
667
668                 foreach ($users as $user) {
669                         Worker::add(PRIORITY_HIGH, 'Notifier', 'relocate', $user['uid']);
670                 }
671
672                 info("Relocation started. Could take a while to complete.");
673
674                 $a->internalRedirect('admin/site');
675         }
676         // end relocate
677
678         $sitename         = (!empty($_POST['sitename'])         ? Strings::escapeTags(trim($_POST['sitename']))      : '');
679         $sender_email     = (!empty($_POST['sender_email'])     ? Strings::escapeTags(trim($_POST['sender_email']))  : '');
680         $banner           = (!empty($_POST['banner'])           ? trim($_POST['banner'])                             : false);
681         $shortcut_icon    = (!empty($_POST['shortcut_icon'])    ? Strings::escapeTags(trim($_POST['shortcut_icon'])) : '');
682         $touch_icon       = (!empty($_POST['touch_icon'])       ? Strings::escapeTags(trim($_POST['touch_icon']))    : '');
683         $additional_info  = (!empty($_POST['additional_info'])  ? trim($_POST['additional_info'])                    : '');
684         $language         = (!empty($_POST['language'])         ? Strings::escapeTags(trim($_POST['language']))      : '');
685         $theme            = (!empty($_POST['theme'])            ? Strings::escapeTags(trim($_POST['theme']))         : '');
686         $theme_mobile     = (!empty($_POST['theme_mobile'])     ? Strings::escapeTags(trim($_POST['theme_mobile']))  : '');
687         $maximagesize     = (!empty($_POST['maximagesize'])     ? intval(trim($_POST['maximagesize']))               : 0);
688         $maximagelength   = (!empty($_POST['maximagelength'])   ? intval(trim($_POST['maximagelength']))             : MAX_IMAGE_LENGTH);
689         $jpegimagequality = (!empty($_POST['jpegimagequality']) ? intval(trim($_POST['jpegimagequality']))           : JPEG_QUALITY);
690
691         $register_policy        = (!empty($_POST['register_policy'])         ? intval(trim($_POST['register_policy']))             : 0);
692         $daily_registrations    = (!empty($_POST['max_daily_registrations']) ? intval(trim($_POST['max_daily_registrations']))     : 0);
693         $abandon_days           = (!empty($_POST['abandon_days'])            ? intval(trim($_POST['abandon_days']))                : 0);
694
695         $register_text          = (!empty($_POST['register_text'])           ? strip_tags(trim($_POST['register_text']))           : '');
696
697         $allowed_sites          = (!empty($_POST['allowed_sites'])           ? Strings::escapeTags(trim($_POST['allowed_sites']))  : '');
698         $allowed_email          = (!empty($_POST['allowed_email'])           ? Strings::escapeTags(trim($_POST['allowed_email']))  : '');
699         $forbidden_nicknames    = (!empty($_POST['forbidden_nicknames'])     ? strtolower(Strings::escapeTags(trim($_POST['forbidden_nicknames']))) : '');
700         $no_oembed_rich_content = !empty($_POST['no_oembed_rich_content']);
701         $allowed_oembed         = (!empty($_POST['allowed_oembed'])          ? Strings::escapeTags(trim($_POST['allowed_oembed'])) : '');
702         $block_public           = !empty($_POST['block_public']);
703         $force_publish          = !empty($_POST['publish_all']);
704         $global_directory       = (!empty($_POST['directory'])               ? Strings::escapeTags(trim($_POST['directory']))      : '');
705         $newuser_private        = !empty($_POST['newuser_private']);
706         $enotify_no_content     = !empty($_POST['enotify_no_content']);
707         $private_addons         = !empty($_POST['private_addons']);
708         $disable_embedded       = !empty($_POST['disable_embedded']);
709         $allow_users_remote_self = !empty($_POST['allow_users_remote_self']);
710         $explicit_content       = !empty($_POST['explicit_content']);
711
712         $no_multi_reg           = !empty($_POST['no_multi_reg']);
713         $no_openid              = !empty($_POST['no_openid']);
714         $no_regfullname         = !empty($_POST['no_regfullname']);
715         $community_page_style   = (!empty($_POST['community_page_style']) ? intval(trim($_POST['community_page_style'])) : 0);
716         $max_author_posts_community_page = (!empty($_POST['max_author_posts_community_page']) ? intval(trim($_POST['max_author_posts_community_page'])) : 0);
717
718         $verifyssl              = !empty($_POST['verifyssl']);
719         $proxyuser              = (!empty($_POST['proxyuser'])              ? Strings::escapeTags(trim($_POST['proxyuser'])) : '');
720         $proxy                  = (!empty($_POST['proxy'])                  ? Strings::escapeTags(trim($_POST['proxy']))     : '');
721         $timeout                = (!empty($_POST['timeout'])                ? intval(trim($_POST['timeout']))                : 60);
722         $maxloadavg             = (!empty($_POST['maxloadavg'])             ? intval(trim($_POST['maxloadavg']))             : 20);
723         $maxloadavg_frontend    = (!empty($_POST['maxloadavg_frontend'])    ? intval(trim($_POST['maxloadavg_frontend']))    : 50);
724         $min_memory             = (!empty($_POST['min_memory'])             ? intval(trim($_POST['min_memory']))             : 0);
725         $optimize_max_tablesize = (!empty($_POST['optimize_max_tablesize']) ? intval(trim($_POST['optimize_max_tablesize'])) : 100);
726         $optimize_fragmentation = (!empty($_POST['optimize_fragmentation']) ? intval(trim($_POST['optimize_fragmentation'])) : 30);
727         $poco_completion        = (!empty($_POST['poco_completion'])        ? intval(trim($_POST['poco_completion']))        : false);
728         $poco_requery_days      = (!empty($_POST['poco_requery_days'])      ? intval(trim($_POST['poco_requery_days']))      : 7);
729         $poco_discovery         = (!empty($_POST['poco_discovery'])         ? intval(trim($_POST['poco_discovery']))         : PortableContact::DISABLED);
730         $poco_discovery_since   = (!empty($_POST['poco_discovery_since'])   ? intval(trim($_POST['poco_discovery_since']))   : 30);
731         $poco_local_search      = !empty($_POST['poco_local_search']);
732         $nodeinfo               = !empty($_POST['nodeinfo']);
733         $dfrn_only              = !empty($_POST['dfrn_only']);
734         $ostatus_disabled       = !empty($_POST['ostatus_disabled']);
735         $ostatus_full_threads   = !empty($_POST['ostatus_full_threads']);
736         $diaspora_enabled       = !empty($_POST['diaspora_enabled']);
737         $ssl_policy             = (!empty($_POST['ssl_policy'])             ? intval($_POST['ssl_policy'])                    : 0);
738         $force_ssl              = !empty($_POST['force_ssl']);
739         $hide_help              = !empty($_POST['hide_help']);
740         $dbclean                = !empty($_POST['dbclean']);
741         $dbclean_expire_days    = (!empty($_POST['dbclean_expire_days'])    ? intval($_POST['dbclean_expire_days'])           : 0);
742         $dbclean_unclaimed      = (!empty($_POST['dbclean_unclaimed'])      ? intval($_POST['dbclean_unclaimed'])             : 0);
743         $dbclean_expire_conv    = (!empty($_POST['dbclean_expire_conv'])    ? intval($_POST['dbclean_expire_conv'])           : 0);
744         $suppress_tags          = !empty($_POST['suppress_tags']);
745         $itemcache              = (!empty($_POST['itemcache'])              ? Strings::escapeTags(trim($_POST['itemcache']))  : '');
746         $itemcache_duration     = (!empty($_POST['itemcache_duration'])     ? intval($_POST['itemcache_duration'])            : 0);
747         $max_comments           = (!empty($_POST['max_comments'])           ? intval($_POST['max_comments'])                  : 0);
748         $temppath               = (!empty($_POST['temppath'])               ? Strings::escapeTags(trim($_POST['temppath']))   : '');
749         $singleuser             = (!empty($_POST['singleuser'])             ? Strings::escapeTags(trim($_POST['singleuser'])) : '');
750         $proxy_disabled         = !empty($_POST['proxy_disabled']);
751         $only_tag_search        = !empty($_POST['only_tag_search']);
752         $rino                   = (!empty($_POST['rino'])                   ? intval($_POST['rino'])                          : 0);
753         $check_new_version_url  = (!empty($_POST['check_new_version_url'])  ? Strings::escapeTags(trim($_POST['check_new_version_url'])) : 'none');
754
755         $worker_queues    = (!empty($_POST['worker_queues'])                ? intval($_POST['worker_queues'])                 : 10);
756         $worker_dont_fork = !empty($_POST['worker_dont_fork']);
757         $worker_fastlane  = !empty($_POST['worker_fastlane']);
758         $worker_frontend  = !empty($_POST['worker_frontend']);
759
760         $relay_directly    = !empty($_POST['relay_directly']);
761         $relay_server      = (!empty($_POST['relay_server'])      ? Strings::escapeTags(trim($_POST['relay_server']))       : '');
762         $relay_subscribe   = !empty($_POST['relay_subscribe']);
763         $relay_scope       = (!empty($_POST['relay_scope'])       ? Strings::escapeTags(trim($_POST['relay_scope']))        : '');
764         $relay_server_tags = (!empty($_POST['relay_server_tags']) ? Strings::escapeTags(trim($_POST['relay_server_tags']))  : '');
765         $relay_user_tags   = !empty($_POST['relay_user_tags']);
766         $active_panel      = (!empty($_POST['active_panel'])      ? "#" . Strings::escapeTags(trim($_POST['active_panel'])) : '');
767
768         /**
769          * @var $storagebackend \Friendica\Model\Storage\IStorage
770          */
771         $storagebackend    = Strings::escapeTags(trim(defaults($_POST, 'storagebackend', '')));
772
773         // save storage backend form
774         if (!is_null($storagebackend) && $storagebackend != "") {
775                 if (StorageManager::setBackend($storagebackend)) {
776                         $storage_opts = $storagebackend::getOptions();
777                         $storage_form_prefix = preg_replace('|[^a-zA-Z0-9]|', '', $storagebackend);
778                         $storage_opts_data = [];
779                         foreach ($storage_opts as $name => $info) {
780                                 $fieldname = $storage_form_prefix . '_' . $name;
781                                 switch ($info[0]) { // type
782                                         case 'checkbox':
783                                         case 'yesno':
784                                                 $value = !empty($_POST[$fieldname]);
785                                                 break;
786                                         default:
787                                                 $value = defaults($_POST, $fieldname, '');
788                                 }
789                                 $storage_opts_data[$name] = $value;
790                         }
791                         unset($name);
792                         unset($info);
793
794                         $storage_form_errors = $storagebackend::saveOptions($storage_opts_data);
795                         if (count($storage_form_errors)) {
796                                 foreach ($storage_form_errors as $name => $err) {
797                                         notice('Storage backend, ' . $storage_opts[$name][1] . ': ' . $err);
798                                 }
799                                 $a->internalRedirect('admin/site' . $active_panel);
800                         }
801                 } else {
802                         info(L10n::t('Invalid storage backend setting value.'));
803                 }
804         }
805
806
807
808         // Has the directory url changed? If yes, then resubmit the existing profiles there
809         if ($global_directory != Config::get('system', 'directory') && ($global_directory != '')) {
810                 Config::set('system', 'directory', $global_directory);
811                 Worker::add(PRIORITY_LOW, 'Directory');
812         }
813
814         if ($a->getURLPath() != "") {
815                 $diaspora_enabled = false;
816         }
817         if ($ssl_policy != intval(Config::get('system', 'ssl_policy'))) {
818                 if ($ssl_policy == BaseURL::SSL_POLICY_FULL) {
819                         q("UPDATE `contact` SET
820                                 `url`     = REPLACE(`url`    , 'http:' , 'https:'),
821                                 `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
822                                 `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:'),
823                                 `micro`   = REPLACE(`micro`  , 'http:' , 'https:'),
824                                 `request` = REPLACE(`request`, 'http:' , 'https:'),
825                                 `notify`  = REPLACE(`notify` , 'http:' , 'https:'),
826                                 `poll`    = REPLACE(`poll`   , 'http:' , 'https:'),
827                                 `confirm` = REPLACE(`confirm`, 'http:' , 'https:'),
828                                 `poco`    = REPLACE(`poco`   , 'http:' , 'https:')
829                                 WHERE `self` = 1"
830                         );
831                         q("UPDATE `profile` SET
832                                 `photo`   = REPLACE(`photo`  , 'http:' , 'https:'),
833                                 `thumb`   = REPLACE(`thumb`  , 'http:' , 'https:')
834                                 WHERE 1 "
835                         );
836                 } elseif ($ssl_policy == BaseURL::SSL_POLICY_SELFSIGN) {
837                         q("UPDATE `contact` SET
838                                 `url`     = REPLACE(`url`    , 'https:' , 'http:'),
839                                 `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
840                                 `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:'),
841                                 `micro`   = REPLACE(`micro`  , 'https:' , 'http:'),
842                                 `request` = REPLACE(`request`, 'https:' , 'http:'),
843                                 `notify`  = REPLACE(`notify` , 'https:' , 'http:'),
844                                 `poll`    = REPLACE(`poll`   , 'https:' , 'http:'),
845                                 `confirm` = REPLACE(`confirm`, 'https:' , 'http:'),
846                                 `poco`    = REPLACE(`poco`   , 'https:' , 'http:')
847                                 WHERE `self` = 1"
848                         );
849                         q("UPDATE `profile` SET
850                                 `photo`   = REPLACE(`photo`  , 'https:' , 'http:'),
851                                 `thumb`   = REPLACE(`thumb`  , 'https:' , 'http:')
852                                 WHERE 1 "
853                         );
854                 }
855         }
856         Config::set('system', 'ssl_policy'            , $ssl_policy);
857         Config::set('system', 'maxloadavg'            , $maxloadavg);
858         Config::set('system', 'maxloadavg_frontend'   , $maxloadavg_frontend);
859         Config::set('system', 'min_memory'            , $min_memory);
860         Config::set('system', 'optimize_max_tablesize', $optimize_max_tablesize);
861         Config::set('system', 'optimize_fragmentation', $optimize_fragmentation);
862         Config::set('system', 'poco_completion'       , $poco_completion);
863         Config::set('system', 'poco_requery_days'     , $poco_requery_days);
864         Config::set('system', 'poco_discovery'        , $poco_discovery);
865         Config::set('system', 'poco_discovery_since'  , $poco_discovery_since);
866         Config::set('system', 'poco_local_search'     , $poco_local_search);
867         Config::set('system', 'nodeinfo'              , $nodeinfo);
868         Config::set('config', 'sitename'              , $sitename);
869         Config::set('config', 'sender_email'          , $sender_email);
870         Config::set('system', 'suppress_tags'         , $suppress_tags);
871         Config::set('system', 'shortcut_icon'         , $shortcut_icon);
872         Config::set('system', 'touch_icon'            , $touch_icon);
873
874         if ($banner == "") {
875                 Config::delete('system', 'banner');
876         } else {
877                 Config::set('system', 'banner', $banner);
878         }
879
880         if (empty($additional_info)) {
881                 Config::delete('config', 'info');
882         } else {
883                 Config::set('config', 'info', $additional_info);
884         }
885         Config::set('system', 'language', $language);
886         Config::set('system', 'theme', $theme);
887         Theme::install($theme);
888
889         if ($theme_mobile == '---') {
890                 Config::delete('system', 'mobile-theme');
891         } else {
892                 Config::set('system', 'mobile-theme', $theme_mobile);
893         }
894         if ($singleuser == '---') {
895                 Config::delete('system', 'singleuser');
896         } else {
897                 Config::set('system', 'singleuser', $singleuser);
898         }
899         Config::set('system', 'maximagesize'           , $maximagesize);
900         Config::set('system', 'max_image_length'       , $maximagelength);
901         Config::set('system', 'jpeg_quality'           , $jpegimagequality);
902
903         Config::set('config', 'register_policy'        , $register_policy);
904         Config::set('system', 'max_daily_registrations', $daily_registrations);
905         Config::set('system', 'account_abandon_days'   , $abandon_days);
906         Config::set('config', 'register_text'          , $register_text);
907         Config::set('system', 'allowed_sites'          , $allowed_sites);
908         Config::set('system', 'allowed_email'          , $allowed_email);
909         Config::set('system', 'forbidden_nicknames'    , $forbidden_nicknames);
910         Config::set('system', 'no_oembed_rich_content' , $no_oembed_rich_content);
911         Config::set('system', 'allowed_oembed'         , $allowed_oembed);
912         Config::set('system', 'block_public'           , $block_public);
913         Config::set('system', 'publish_all'            , $force_publish);
914         Config::set('system', 'newuser_private'        , $newuser_private);
915         Config::set('system', 'enotify_no_content'     , $enotify_no_content);
916         Config::set('system', 'disable_embedded'       , $disable_embedded);
917         Config::set('system', 'allow_users_remote_self', $allow_users_remote_self);
918         Config::set('system', 'explicit_content'       , $explicit_content);
919         Config::set('system', 'check_new_version_url'  , $check_new_version_url);
920
921         Config::set('system', 'block_extended_register', $no_multi_reg);
922         Config::set('system', 'no_openid'              , $no_openid);
923         Config::set('system', 'no_regfullname'         , $no_regfullname);
924         Config::set('system', 'community_page_style'   , $community_page_style);
925         Config::set('system', 'max_author_posts_community_page', $max_author_posts_community_page);
926         Config::set('system', 'verifyssl'              , $verifyssl);
927         Config::set('system', 'proxyuser'              , $proxyuser);
928         Config::set('system', 'proxy'                  , $proxy);
929         Config::set('system', 'curl_timeout'           , $timeout);
930         Config::set('system', 'dfrn_only'              , $dfrn_only);
931         Config::set('system', 'ostatus_disabled'       , $ostatus_disabled);
932         Config::set('system', 'ostatus_full_threads'   , $ostatus_full_threads);
933         Config::set('system', 'diaspora_enabled'       , $diaspora_enabled);
934
935         Config::set('config', 'private_addons'         , $private_addons);
936
937         Config::set('system', 'force_ssl'              , $force_ssl);
938         Config::set('system', 'hide_help'              , $hide_help);
939
940         Config::set('system', 'dbclean'                , $dbclean);
941         Config::set('system', 'dbclean-expire-days'    , $dbclean_expire_days);
942         Config::set('system', 'dbclean_expire_conversation', $dbclean_expire_conv);
943
944         if ($dbclean_unclaimed == 0) {
945                 $dbclean_unclaimed = $dbclean_expire_days;
946         }
947
948         Config::set('system', 'dbclean-expire-unclaimed', $dbclean_unclaimed);
949
950         if ($itemcache != '') {
951                 $itemcache = BasePath::getRealPath($itemcache);
952         }
953
954         Config::set('system', 'itemcache', $itemcache);
955         Config::set('system', 'itemcache_duration', $itemcache_duration);
956         Config::set('system', 'max_comments', $max_comments);
957
958         if ($temppath != '') {
959                 $temppath = BasePath::getRealPath($temppath);
960         }
961
962         Config::set('system', 'temppath', $temppath);
963
964         Config::set('system', 'proxy_disabled'   , $proxy_disabled);
965         Config::set('system', 'only_tag_search'  , $only_tag_search);
966
967         Config::set('system', 'worker_queues'    , $worker_queues);
968         Config::set('system', 'worker_dont_fork' , $worker_dont_fork);
969         Config::set('system', 'worker_fastlane'  , $worker_fastlane);
970         Config::set('system', 'frontend_worker'  , $worker_frontend);
971
972         Config::set('system', 'relay_directly'   , $relay_directly);
973         Config::set('system', 'relay_server'     , $relay_server);
974         Config::set('system', 'relay_subscribe'  , $relay_subscribe);
975         Config::set('system', 'relay_scope'      , $relay_scope);
976         Config::set('system', 'relay_server_tags', $relay_server_tags);
977         Config::set('system', 'relay_user_tags'  , $relay_user_tags);
978
979         Config::set('system', 'rino_encrypt'     , $rino);
980
981         info(L10n::t('Site settings updated.') . EOL);
982
983         $a->internalRedirect('admin/site' . $active_panel);
984         return; // NOTREACHED
985 }
986
987 /**
988  * @brief Generate Admin Site subpage
989  *
990  * This function generates the main configuration page of the admin panel.
991  *
992  * @param  App $a
993  * @return string
994  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995  */
996 function admin_page_site(App $a)
997 {
998         /* Installed langs */
999         $lang_choices = L10n::getAvailableLanguages();
1000
1001         if (strlen(Config::get('system', 'directory_submit_url')) &&
1002                 !strlen(Config::get('system', 'directory'))) {
1003                 Config::set('system', 'directory', dirname(Config::get('system', 'directory_submit_url')));
1004                 Config::delete('system', 'directory_submit_url');
1005         }
1006
1007         /* Installed themes */
1008         $theme_choices = [];
1009         $theme_choices_mobile = [];
1010         $theme_choices_mobile["---"] = L10n::t("No special theme for mobile devices");
1011         $files = glob('view/theme/*');
1012         if (is_array($files)) {
1013                 $allowed_theme_list = Config::get('system', 'allowed_themes');
1014
1015                 foreach ($files as $file) {
1016                         if (intval(file_exists($file . '/unsupported'))) {
1017                                 continue;
1018                         }
1019
1020                         $f = basename($file);
1021
1022                         // Only show allowed themes here
1023                         if (($allowed_theme_list != '') && !strstr($allowed_theme_list, $f)) {
1024                                 continue;
1025                         }
1026
1027                         $theme_name = ((file_exists($file . '/experimental')) ? sprintf("%s - \x28Experimental\x29", $f) : $f);
1028
1029                         if (file_exists($file . '/mobile')) {
1030                                 $theme_choices_mobile[$f] = $theme_name;
1031                         } else {
1032                                 $theme_choices[$f] = $theme_name;
1033                         }
1034                 }
1035         }
1036
1037         /* Community page style */
1038         $community_page_style_choices = [
1039                 CP_NO_INTERNAL_COMMUNITY => L10n::t("No community page for local users"),
1040                 CP_NO_COMMUNITY_PAGE => L10n::t("No community page"),
1041                 CP_USERS_ON_SERVER => L10n::t("Public postings from users of this site"),
1042                 CP_GLOBAL_COMMUNITY => L10n::t("Public postings from the federated network"),
1043                 CP_USERS_AND_GLOBAL => L10n::t("Public postings from local users and the federated network")
1044         ];
1045
1046         $poco_discovery_choices = [
1047                 PortableContact::DISABLED => L10n::t("Disabled"),
1048                 PortableContact::USERS => L10n::t("Users"),
1049                 PortableContact::USERS_GCONTACTS => L10n::t("Users, Global Contacts"),
1050                 PortableContact::USERS_GCONTACTS_FALLBACK => L10n::t("Users, Global Contacts/fallback"),
1051         ];
1052
1053         $poco_discovery_since_choices = [
1054                 "30" => L10n::t("One month"),
1055                 "91" => L10n::t("Three months"),
1056                 "182" => L10n::t("Half a year"),
1057                 "365" => L10n::t("One year"),
1058         ];
1059
1060         /* get user names to make the install a personal install of X */
1061         $user_names = [];
1062         $user_names['---'] = L10n::t('Multi user instance');
1063         $users = q("SELECT `username`, `nickname` FROM `user`");
1064
1065         foreach ($users as $user) {
1066                 $user_names[$user['nickname']] = $user['username'];
1067         }
1068
1069         /* Banner */
1070         $banner = Config::get('system', 'banner');
1071
1072         if ($banner == false) {
1073                 $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>';
1074         }
1075
1076         $additional_info = Config::get('config', 'info');
1077
1078         // Automatically create temporary paths
1079         get_temppath();
1080         get_itemcachepath();
1081
1082         //echo "<pre>"; var_dump($lang_choices); die("</pre>");
1083
1084         /* Register policy */
1085         $register_choices = [
1086                 Module\Register::CLOSED => L10n::t("Closed"),
1087                 Module\Register::APPROVE => L10n::t("Requires approval"),
1088                 Module\Register::OPEN => L10n::t("Open")
1089         ];
1090
1091         $ssl_choices = [
1092                 BaseURL::SSL_POLICY_NONE => L10n::t("No SSL policy, links will track page SSL state"),
1093                 BaseURL::SSL_POLICY_FULL => L10n::t("Force all links to use SSL"),
1094                 BaseURL::SSL_POLICY_SELFSIGN => L10n::t("Self-signed certificate, use SSL for local links only \x28discouraged\x29")
1095         ];
1096
1097         $check_git_version_choices = [
1098                 "none" => L10n::t("Don't check"),
1099                 "master" => L10n::t("check the stable version"),
1100                 "develop" => L10n::t("check the development version")
1101         ];
1102
1103         $diaspora_able = ($a->getURLPath() == "");
1104
1105         $optimize_max_tablesize = Config::get('system', 'optimize_max_tablesize', -1);
1106
1107         if ($optimize_max_tablesize <= 0) {
1108                 $optimize_max_tablesize = -1;
1109         }
1110
1111         /* storage backend */
1112         $storage_backends = StorageManager::listBackends();
1113         /**
1114          * @var $storage_current_backend \Friendica\Model\Storage\IStorage
1115          */
1116         $storage_current_backend = StorageManager::getBackend();
1117
1118         $storage_backends_choices = [];
1119
1120         // show legacy option only if it is the current backend:
1121         // once changed can't be selected anymore
1122         if ($storage_current_backend == '') {
1123                 $storage_backends_choices[''] = L10n::t('Database (legacy)');
1124         };
1125
1126         foreach ($storage_backends as $name => $class) {
1127                 $storage_backends_choices[$class] = $name;
1128         }
1129         unset($storage_backends);
1130
1131         // build storage config form,
1132         $storage_form_prefix=preg_replace('|[^a-zA-Z0-9]|' ,'', $storage_current_backend);
1133
1134         $storage_form = [];
1135         if (!is_null($storage_current_backend) && $storage_current_backend != "") {
1136                 foreach ($storage_current_backend::getOptions() as $name => $info) {
1137                         $type = $info[0];
1138                         $info[0] = $storage_form_prefix . '_' . $name;
1139                         $info['type'] = $type;
1140                         $info['field'] = 'field_' . $type . '.tpl';
1141                         $storage_form[$name] = $info;
1142                 }
1143         }
1144
1145
1146         $t = Renderer::getMarkupTemplate('admin/site.tpl');
1147         return Renderer::replaceMacros($t, [
1148                 '$title'             => L10n::t('Administration'),
1149                 '$page'              => L10n::t('Site'),
1150                 '$submit'            => L10n::t('Save Settings'),
1151                 '$republish'         => L10n::t('Republish users to directory'),
1152                 '$registration'      => L10n::t('Registration'),
1153                 '$upload'            => L10n::t('File upload'),
1154                 '$corporate'         => L10n::t('Policies'),
1155                 '$advanced'          => L10n::t('Advanced'),
1156                 '$portable_contacts' => L10n::t('Auto Discovered Contact Directory'),
1157                 '$performance'       => L10n::t('Performance'),
1158                 '$worker_title'      => L10n::t('Worker'),
1159                 '$relay_title'       => L10n::t('Message Relay'),
1160                 '$relocate'          => L10n::t('Relocate Instance'),
1161                 '$relocate_warning'  => L10n::t('Warning! Advanced function. Could make this server unreachable.'),
1162                 '$baseurl'           => System::baseUrl(true),
1163
1164                 // name, label, value, help string, extra data...
1165                 '$sitename'         => ['sitename', L10n::t("Site name"), Config::get('config', 'sitename'), ''],
1166                 '$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"],
1167                 '$banner'           => ['banner', L10n::t("Banner/Logo"), $banner, ""],
1168                 '$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.")],
1169                 '$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.")],
1170                 '$additional_info'  => ['additional_info', L10n::t('Additional Info'), $additional_info, L10n::t('For public servers: you can add additional information here that will be listed at %s/servers.', get_server())],
1171                 '$language'         => ['language', L10n::t("System language"), Config::get('system', 'language'), "", $lang_choices],
1172                 '$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],
1173                 '$theme_mobile'     => ['theme_mobile', L10n::t("Mobile system theme"), Config::get('system', 'mobile-theme', '---'), L10n::t("Theme for mobile devices"), $theme_choices_mobile],
1174                 '$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],
1175                 '$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.")],
1176                 '$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.")],
1177                 '$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],
1178
1179                 '$storagebackend'   => ['storagebackend', L10n::t("File storage backend"), $storage_current_backend, L10n::t('The backend used to store uploaded data. If you change the storage backend, you can manually move the existing files. If you do not do so, the files uploaded before the change will still be available at the old backend. Please see <a href="/help/Settings#1_2_3_1">the settings documentation</a> for more information about the choices and the moving procedure.'), $storage_backends_choices],
1180                 '$storageform'      => $storage_form,
1181                 '$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.")],
1182                 '$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.")],
1183                 '$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.")],
1184
1185                 '$register_policy'        => ['register_policy', L10n::t("Register policy"), Config::get('config', 'register_policy'), "", $register_choices],
1186                 '$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.")],
1187                 '$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.")],
1188                 '$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.')],
1189                 '$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.')],
1190                 '$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")],
1191                 '$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")],
1192                 '$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.")],
1193                 '$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.")],
1194                 '$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.")],
1195                 '$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>'],
1196                 '$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.")],
1197                 '$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.")],
1198                 '$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.")],
1199                 '$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.")],
1200                 '$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.")],
1201                 '$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.')],
1202                 '$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.')],
1203                 '$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.")],
1204                 '$no_openid'              => ['no_openid', L10n::t("Disable OpenID"), Config::get('system', 'no_openid'), L10n::t("Disable OpenID support for registration and logins.")],
1205                 '$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.")],
1206                 '$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],
1207                 '$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")],
1208                 '$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.")],
1209                 '$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.")],
1210                 '$ostatus_not_able'       => L10n::t("OStatus support can only be enabled if threading is enabled."),
1211                 '$diaspora_able'          => $diaspora_able,
1212                 '$diaspora_not_able'      => L10n::t("Diaspora support can't be enabled because Friendica was installed into a sub directory."),
1213                 '$diaspora_enabled'       => ['diaspora_enabled', L10n::t("Enable Diaspora support"), Config::get('system', 'diaspora_enabled', $diaspora_able), L10n::t("Provide built-in Diaspora network compatibility.")],
1214                 '$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.")],
1215                 '$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.")],
1216                 '$proxyuser'              => ['proxyuser', L10n::t("Proxy user"), Config::get('system', 'proxyuser'), ""],
1217                 '$proxy'                  => ['proxy', L10n::t("Proxy URL"), Config::get('system', 'proxy'), ""],
1218                 '$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.")],
1219                 '$maxloadavg'             => ['maxloadavg', L10n::t("Maximum Load Average"), Config::get('system', 'maxloadavg', 20), L10n::t("Maximum system load before delivery and poll processes are deferred - default %d.", 20)],
1220                 '$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.")],
1221                 '$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.")],
1222                 '$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.")],
1223                 '$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%.")],
1224
1225                 '$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.")],
1226                 '$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.")],
1227                 '$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 recommended setting is 'Users, Global Contacts'."), $poco_discovery_choices],
1228                 '$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],
1229                 '$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.")],
1230
1231                 '$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.")],
1232
1233                 '$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],
1234                 '$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.")],
1235                 '$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.")],
1236                 '$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.")],
1237                 '$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.")],
1238                 '$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.")],
1239                 '$itemcache'              => ['itemcache', L10n::t("Path to item cache"), Config::get('system', 'itemcache'), L10n::t("The item caches buffers generated bbcode and external images.")],
1240                 '$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.")],
1241                 '$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.")],
1242                 '$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.")],
1243                 '$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.")],
1244                 '$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.")],
1245
1246                 '$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.")],
1247
1248                 '$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")]],
1249
1250                 '$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)],
1251                 '$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.")],
1252                 '$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.")],
1253                 '$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())],
1254
1255                 '$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.")],
1256                 '$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")],
1257                 '$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")],
1258                 '$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')]],
1259                 '$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.")],
1260                 '$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'.")],
1261
1262                 '$form_security_token'    => BaseModule::getFormSecurityToken("admin_site"),
1263                 '$relocate_button'        => L10n::t('Start Relocation'),
1264         ]);
1265 }
1266
1267 /**
1268  * @brief Generates admin panel subpage for DB syncronization
1269  *
1270  * This page checks if the database of friendica is in sync with the specs.
1271  * Should this not be the case, it attemps to sync the structure and notifies
1272  * the admin if the automatic process was failing.
1273  *
1274  * The returned string holds the HTML code of the page.
1275  *
1276  * @param App $a
1277  * @return string
1278  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1279  */
1280 function admin_page_dbsync(App $a)
1281 {
1282         $o = '';
1283
1284         if ($a->argc > 3 && intval($a->argv[3]) && $a->argv[2] === 'mark') {
1285                 Config::set('database', 'update_' . intval($a->argv[3]), 'success');
1286                 $curr = Config::get('system', 'build');
1287                 if (intval($curr) == intval($a->argv[3])) {
1288                         Config::set('system', 'build', intval($curr) + 1);
1289                 }
1290                 info(L10n::t('Update has been marked successful') . EOL);
1291                 $a->internalRedirect('admin/dbsync');
1292         }
1293
1294         if (($a->argc > 2) && (intval($a->argv[2]) || ($a->argv[2] === 'check'))) {
1295                 $retval = DBStructure::update($a->getBasePath(), false, true);
1296                 if ($retval === '') {
1297                         $o .= L10n::t("Database structure update %s was successfully applied.", DB_UPDATE_VERSION) . "<br />";
1298                         Config::set('database', 'last_successful_update', DB_UPDATE_VERSION);
1299                         Config::set('database', 'last_successful_update_time', time());
1300                 } else {
1301                         $o .= L10n::t("Executing of database structure update %s failed with error: %s", DB_UPDATE_VERSION, $retval) . "<br />";
1302                 }
1303                 if ($a->argv[2] === 'check') {
1304                         return $o;
1305                 }
1306         }
1307
1308         if ($a->argc > 2 && intval($a->argv[2])) {
1309                 require_once 'update.php';
1310
1311                 $func = 'update_' . intval($a->argv[2]);
1312
1313                 if (function_exists($func)) {
1314                         $retval = $func();
1315
1316                         if ($retval === Update::FAILED) {
1317                                 $o .= L10n::t("Executing %s failed with error: %s", $func, $retval);
1318                         } elseif ($retval === Update::SUCCESS) {
1319                                 $o .= L10n::t('Update %s was successfully applied.', $func);
1320                                 Config::set('database', $func, 'success');
1321                         } else {
1322                                 $o .= L10n::t('Update %s did not return a status. Unknown if it succeeded.', $func);
1323                         }
1324                 } else {
1325                         $o .= L10n::t('There was no additional update function %s that needed to be called.', $func) . "<br />";
1326                         Config::set('database', $func, 'success');
1327                 }
1328
1329                 return $o;
1330         }
1331
1332         $failed = [];
1333         $r = q("SELECT `k`, `v` FROM `config` WHERE `cat` = 'database' ");
1334
1335         if (DBA::isResult($r)) {
1336                 foreach ($r as $rr) {
1337                         $upd = intval(substr($rr['k'], 7));
1338                         if ($upd < 1139 || $rr['v'] === 'success') {
1339                                 continue;
1340                         }
1341                         $failed[] = $upd;
1342                 }
1343         }
1344
1345         if (!count($failed)) {
1346                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure_check.tpl'), [
1347                         '$base' => System::baseUrl(true),
1348                         '$banner' => L10n::t('No failed updates.'),
1349                         '$check' => L10n::t('Check database structure'),
1350                 ]);
1351         } else {
1352                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('failed_updates.tpl'), [
1353                         '$base' => System::baseUrl(true),
1354                         '$banner' => L10n::t('Failed Updates'),
1355                         '$desc' => L10n::t('This does not include updates prior to 1139, which did not return a status.'),
1356                         '$mark' => L10n::t("Mark success \x28if update was manually applied\x29"),
1357                         '$apply' => L10n::t('Attempt to execute this update step automatically'),
1358                         '$failed' => $failed
1359                 ]);
1360         }
1361
1362         return $o;
1363 }
1364
1365 /**
1366  * @brief Process data send by Users admin page
1367  *
1368  * @param App $a
1369  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1370  */
1371 function admin_page_users_post(App $a)
1372 {
1373         $pending     = defaults($_POST, 'pending'          , []);
1374         $users       = defaults($_POST, 'user'             , []);
1375         $nu_name     = defaults($_POST, 'new_user_name'    , '');
1376         $nu_nickname = defaults($_POST, 'new_user_nickname', '');
1377         $nu_email    = defaults($_POST, 'new_user_email'   , '');
1378         $nu_language = Config::get('system', 'language');
1379
1380         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users');
1381
1382         if (!($nu_name === "") && !($nu_email === "") && !($nu_nickname === "")) {
1383                 try {
1384                         $result = User::create([
1385                                 'username' => $nu_name,
1386                                 'email' => $nu_email,
1387                                 'nickname' => $nu_nickname,
1388                                 'verified' => 1,
1389                                 'language' => $nu_language
1390                         ]);
1391                 } catch (Exception $ex) {
1392                         notice($ex->getMessage());
1393                         return;
1394                 }
1395
1396                 $user = $result['user'];
1397                 $preamble = Strings::deindent(L10n::t('
1398                         Dear %1$s,
1399                                 the administrator of %2$s has set up an account for you.'));
1400                 $body = Strings::deindent(L10n::t('
1401                         The login details are as follows:
1402
1403                         Site Location:  %1$s
1404                         Login Name:             %2$s
1405                         Password:               %3$s
1406
1407                         You may change your password from your account "Settings" page after logging
1408                         in.
1409
1410                         Please take a few moments to review the other account settings on that page.
1411
1412                         You may also wish to add some basic information to your default profile
1413                         ' . "\x28" . 'on the "Profiles" page' . "\x29" . ' so that other people can easily find you.
1414
1415                         We recommend setting your full name, adding a profile photo,
1416                         adding some profile "keywords" ' . "\x28" . 'very useful in making new friends' . "\x29" . ' - and
1417                         perhaps what country you live in; if you do not wish to be more specific
1418                         than that.
1419
1420                         We fully respect your right to privacy, and none of these items are necessary.
1421                         If you are new and do not know anybody here, they may help
1422                         you to make some new and interesting friends.
1423
1424                         If you ever want to delete your account, you can do so at %1$s/removeme
1425
1426                         Thank you and welcome to %4$s.'));
1427
1428                 $preamble = sprintf($preamble, $user['username'], Config::get('config', 'sitename'));
1429                 $body = sprintf($body, System::baseUrl(), $user['nickname'], $result['password'], Config::get('config', 'sitename'));
1430
1431                 notification([
1432                         'type'     => SYSTEM_EMAIL,
1433                         'language' => $user['language'],
1434                         'to_name'  => $user['username'],
1435                         'to_email' => $user['email'],
1436                         'uid'      => $user['uid'],
1437                         'subject'  => L10n::t('Registration details for %s', Config::get('config', 'sitename')),
1438                         'preamble' => $preamble,
1439                         'body'     => $body]);
1440         }
1441
1442         if (!empty($_POST['page_users_block'])) {
1443                 foreach ($users as $uid) {
1444                         q("UPDATE `user` SET `blocked` = 1-`blocked` WHERE `uid` = %s", intval($uid)
1445                         );
1446                 }
1447                 notice(L10n::tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)));
1448         }
1449         if (!empty($_POST['page_users_delete'])) {
1450                 foreach ($users as $uid) {
1451                         if (local_user() != $uid) {
1452                                 User::remove($uid);
1453                         } else {
1454                                 notice(L10n::t('You can\'t remove yourself'));
1455                         }
1456                 }
1457                 notice(L10n::tt("%s user deleted", "%s users deleted", count($users)));
1458         }
1459
1460         if (!empty($_POST['page_users_approve'])) {
1461                 require_once "mod/regmod.php";
1462                 foreach ($pending as $hash) {
1463                         user_allow($hash);
1464                 }
1465         }
1466         if (!empty($_POST['page_users_deny'])) {
1467                 require_once "mod/regmod.php";
1468                 foreach ($pending as $hash) {
1469                         user_deny($hash);
1470                 }
1471         }
1472         $a->internalRedirect('admin/users');
1473         return; // NOTREACHED
1474 }
1475
1476 /**
1477  * @brief Admin panel subpage for User management
1478  *
1479  * This function generates the admin panel page for user management of the
1480  * node. It offers functionality to add/block/delete users and offers some
1481  * statistics about the userbase.
1482  *
1483  * The returned string holds the HTML code of the page.
1484  *
1485  * @param App $a
1486  * @return string
1487  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1488  */
1489 function admin_page_users(App $a)
1490 {
1491         if ($a->argc > 2) {
1492                 $uid = $a->argv[3];
1493                 $user = DBA::selectFirst('user', ['username', 'blocked'], ['uid' => $uid]);
1494                 if (!DBA::isResult($user)) {
1495                         notice('User not found' . EOL);
1496                         $a->internalRedirect('admin/users');
1497                         return ''; // NOTREACHED
1498                 }
1499                 switch ($a->argv[2]) {
1500                         case "delete":
1501                                 if (local_user() != $uid) {
1502                                         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
1503                                         // delete user
1504                                         User::remove($uid);
1505
1506                                         notice(L10n::t("User '%s' deleted", $user['username']));
1507                                 } else {
1508                                         notice(L10n::t('You can\'t remove yourself'));
1509                                 }
1510                                 break;
1511                         case "block":
1512                                 BaseModule::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't');
1513                                 q("UPDATE `user` SET `blocked` = %d WHERE `uid` = %s",
1514                                         intval(1 - $user['blocked']),
1515                                         intval($uid)
1516                                 );
1517                                 notice(sprintf(($user['blocked'] ? L10n::t("User '%s' unblocked") : L10n::t("User '%s' blocked")), $user['username']) . EOL);
1518                                 break;
1519                 }
1520                 $a->internalRedirect('admin/users');
1521                 return ''; // NOTREACHED
1522         }
1523
1524         /* get pending */
1525         $pending = Register::getPending();
1526
1527         $pager = new Pager($a->query_string, 100);
1528
1529         /* ordering */
1530         $valid_orders = [
1531                 'contact.name',
1532                 'user.email',
1533                 'user.register_date',
1534                 'user.login_date',
1535                 'lastitem_date',
1536                 'user.page-flags'
1537         ];
1538
1539         $order = "contact.name";
1540         $order_direction = "+";
1541         if (!empty($_GET['o'])) {
1542                 $new_order = $_GET['o'];
1543                 if ($new_order[0] === "-") {
1544                         $order_direction = "-";
1545                         $new_order = substr($new_order, 1);
1546                 }
1547
1548                 if (in_array($new_order, $valid_orders)) {
1549                         $order = $new_order;
1550                 }
1551         }
1552         $sql_order = "`" . str_replace('.', '`.`', $order) . "`";
1553         $sql_order_direction = ($order_direction === "+") ? "ASC" : "DESC";
1554
1555         $users = q("SELECT `user`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`account_expired`, `contact`.`last-item` AS `lastitem_date`
1556                                 FROM `user`
1557                                 INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`
1558                                 WHERE `user`.`verified`
1559                                 ORDER BY $sql_order $sql_order_direction LIMIT %d, %d", $pager->getStart(), $pager->getItemsPerPage()
1560         );
1561
1562         $adminlist = explode(",", str_replace(" ", "", Config::get('config', 'admin_email')));
1563         $_setup_users = function ($e) use ($adminlist) {
1564                 $page_types = [
1565                         User::PAGE_FLAGS_NORMAL    => L10n::t('Normal Account Page'),
1566                         User::PAGE_FLAGS_SOAPBOX   => L10n::t('Soapbox Page'),
1567                         User::PAGE_FLAGS_COMMUNITY => L10n::t('Public Forum'),
1568                         User::PAGE_FLAGS_FREELOVE  => L10n::t('Automatic Friend Page'),
1569                         User::PAGE_FLAGS_PRVGROUP  => L10n::t('Private Forum')
1570                 ];
1571                 $account_types = [
1572                         User::ACCOUNT_TYPE_PERSON       => L10n::t('Personal Page'),
1573                         User::ACCOUNT_TYPE_ORGANISATION => L10n::t('Organisation Page'),
1574                         User::ACCOUNT_TYPE_NEWS         => L10n::t('News Page'),
1575                         User::ACCOUNT_TYPE_COMMUNITY    => L10n::t('Community Forum'),
1576                         User::ACCOUNT_TYPE_RELAY        => L10n::t('Relay'),
1577                 ];
1578
1579                 $e['page_flags_raw'] = $e['page-flags'];
1580                 $e['page-flags'] = $page_types[$e['page-flags']];
1581
1582                 $e['account_type_raw'] = ($e['page_flags_raw'] == 0) ? $e['account-type'] : -1;
1583                 $e['account-type'] = ($e['page_flags_raw'] == 0) ? $account_types[$e['account-type']] : "";
1584
1585                 $e['register_date'] = Temporal::getRelativeDate($e['register_date']);
1586                 $e['login_date'] = Temporal::getRelativeDate($e['login_date']);
1587                 $e['lastitem_date'] = Temporal::getRelativeDate($e['lastitem_date']);
1588                 $e['is_admin'] = in_array($e['email'], $adminlist);
1589                 $e['is_deletable'] = (intval($e['uid']) != local_user());
1590                 $e['deleted'] = ($e['account_removed'] ? Temporal::getRelativeDate($e['account_expires_on']) : False);
1591
1592                 return $e;
1593         };
1594
1595         $users = array_map($_setup_users, $users);
1596
1597
1598         // Get rid of dashes in key names, Smarty3 can't handle them
1599         // and extracting deleted users
1600
1601         $tmp_users = [];
1602         $deleted = [];
1603
1604         while (count($users)) {
1605                 $new_user = [];
1606                 foreach (array_pop($users) as $k => $v) {
1607                         $k = str_replace('-', '_', $k);
1608                         $new_user[$k] = $v;
1609                 }
1610                 if ($new_user['deleted']) {
1611                         array_push($deleted, $new_user);
1612                 } else {
1613                         array_push($tmp_users, $new_user);
1614                 }
1615         }
1616         //Reversing the two array, and moving $tmp_users to $users
1617         array_reverse($deleted);
1618         while (count($tmp_users)) {
1619                 array_push($users, array_pop($tmp_users));
1620         }
1621
1622         $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);
1623
1624         $t = Renderer::getMarkupTemplate('admin/users.tpl');
1625         $o = Renderer::replaceMacros($t, [
1626                 // strings //
1627                 '$title' => L10n::t('Administration'),
1628                 '$page' => L10n::t('Users'),
1629                 '$submit' => L10n::t('Add User'),
1630                 '$select_all' => L10n::t('select all'),
1631                 '$h_pending' => L10n::t('User registrations waiting for confirm'),
1632                 '$h_deleted' => L10n::t('User waiting for permanent deletion'),
1633                 '$th_pending' => [L10n::t('Request date'), L10n::t('Name'), L10n::t('Email')],
1634                 '$no_pending' => L10n::t('No registrations.'),
1635                 '$pendingnotetext' => L10n::t('Note from the user'),
1636                 '$approve' => L10n::t('Approve'),
1637                 '$deny' => L10n::t('Deny'),
1638                 '$delete' => L10n::t('Delete'),
1639                 '$block' => L10n::t('Block'),
1640                 '$blocked' => L10n::t('User blocked'),
1641                 '$unblock' => L10n::t('Unblock'),
1642                 '$siteadmin' => L10n::t('Site admin'),
1643                 '$accountexpired' => L10n::t('Account expired'),
1644
1645                 '$h_users' => L10n::t('Users'),
1646                 '$h_newuser' => L10n::t('New User'),
1647                 '$th_deleted' => [L10n::t('Name'), L10n::t('Email'), L10n::t('Register date'), L10n::t('Last login'), L10n::t('Last item'), L10n::t('Permanent deletion')],
1648                 '$th_users' => $th_users,
1649                 '$order_users' => $order,
1650                 '$order_direction_users' => $order_direction,
1651
1652                 '$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?'),
1653                 '$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?'),
1654
1655                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_users"),
1656
1657                 // values //
1658                 '$baseurl' => $a->getBaseURL(true),
1659
1660                 '$pending' => $pending,
1661                 'deleted' => $deleted,
1662                 '$users' => $users,
1663                 '$newusername' => ['new_user_name', L10n::t("Name"), '', L10n::t("Name of the new user.")],
1664                 '$newusernickname' => ['new_user_nickname', L10n::t("Nickname"), '', L10n::t("Nickname of the new user.")],
1665                 '$newuseremail' => ['new_user_email', L10n::t("Email"), '', L10n::t("Email address of the new user."), '', '', 'email'],
1666         ]);
1667         $o .= $pager->renderFull(DBA::count('user'));
1668         return $o;
1669 }
1670
1671 /**
1672  * @brief Addons admin page
1673  *
1674  * This function generates the admin panel page for managing addons on the
1675  * friendica node. If an addon name is given a single page showing the details
1676  * for this addon is generated. If no name is given, a list of available
1677  * addons is shown.
1678  *
1679  * The template used for displaying the list of addons and the details of the
1680  * addon are the same as used for the templates.
1681  *
1682  * The returned string returned hulds the HTML code of the page.
1683  *
1684  * @param App   $a
1685  * @param array $addons_admin A list of admin addon names
1686  * @return string
1687  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1688  */
1689 function admin_page_addons(App $a, array $addons_admin)
1690 {
1691         /*
1692          * Single addon
1693          */
1694         if ($a->argc == 3) {
1695                 $addon = $a->argv[2];
1696                 if (!is_file("addon/$addon/$addon.php")) {
1697                         notice(L10n::t("Item not found."));
1698                         return '';
1699                 }
1700
1701                 if (defaults($_GET, 'a', '') == "t") {
1702                         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/addons', 'admin_themes', 't');
1703
1704                         // Toggle addon status
1705                         if (Addon::isEnabled($addon)) {
1706                                 Addon::uninstall($addon);
1707                                 info(L10n::t("Addon %s disabled.", $addon));
1708                         } else {
1709                                 Addon::install($addon);
1710                                 info(L10n::t("Addon %s enabled.", $addon));
1711                         }
1712
1713                         Addon::saveEnabledList();
1714                         $a->internalRedirect('admin/addons');
1715                         return ''; // NOTREACHED
1716                 }
1717
1718                 // display addon details
1719                 if (Addon::isEnabled($addon)) {
1720                         $status = "on";
1721                         $action = L10n::t("Disable");
1722                 } else {
1723                         $status = "off";
1724                         $action = L10n::t("Enable");
1725                 }
1726
1727                 $readme = null;
1728                 if (is_file("addon/$addon/README.md")) {
1729                         $readme = Markdown::convert(file_get_contents("addon/$addon/README.md"), false);
1730                 } elseif (is_file("addon/$addon/README")) {
1731                         $readme = "<pre>" . file_get_contents("addon/$addon/README") . "</pre>";
1732                 }
1733
1734                 $admin_form = "";
1735                 if (in_array($addon, $addons_admin)) {
1736                         require_once "addon/$addon/$addon.php";
1737                         $func = $addon . '_addon_admin';
1738                         $func($a, $admin_form);
1739                 }
1740
1741                 $t = Renderer::getMarkupTemplate('admin/addon_details.tpl');
1742
1743                 return Renderer::replaceMacros($t, [
1744                         '$title' => L10n::t('Administration'),
1745                         '$page' => L10n::t('Addons'),
1746                         '$toggle' => L10n::t('Toggle'),
1747                         '$settings' => L10n::t('Settings'),
1748                         '$baseurl' => $a->getBaseURL(true),
1749
1750                         '$addon' => $addon,
1751                         '$status' => $status,
1752                         '$action' => $action,
1753                         '$info' => Addon::getInfo($addon),
1754                         '$str_author' => L10n::t('Author: '),
1755                         '$str_maintainer' => L10n::t('Maintainer: '),
1756
1757                         '$admin_form' => $admin_form,
1758                         '$function' => 'addons',
1759                         '$screenshot' => '',
1760                         '$readme' => $readme,
1761
1762                         '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
1763                 ]);
1764         }
1765
1766         /*
1767          * List addons
1768          */
1769         if (!empty($_GET['a']) && $_GET['a'] == "r") {
1770                 BaseModule::checkFormSecurityTokenRedirectOnError($a->getBaseURL() . '/admin/addons', 'admin_themes', 't');
1771                 Addon::reload();
1772                 info("Addons reloaded");
1773                 $a->internalRedirect('admin/addons');
1774         }
1775
1776         $addons = [];
1777         $files = glob("addon/*/");
1778         if (is_array($files)) {
1779                 foreach ($files as $file) {
1780                         if (is_dir($file)) {
1781                                 list($tmp, $id) = array_map("trim", explode("/", $file));
1782                                 $info = Addon::getInfo($id);
1783                                 $show_addon = true;
1784
1785                                 // If the addon is unsupported, then only show it, when it is enabled
1786                                 if ((strtolower($info["status"]) == "unsupported") && !Addon::isEnabled($id)) {
1787                                         $show_addon = false;
1788                                 }
1789
1790                                 // Override the above szenario, when the admin really wants to see outdated stuff
1791                                 if (Config::get("system", "show_unsupported_addons")) {
1792                                         $show_addon = true;
1793                                 }
1794
1795                                 if ($show_addon) {
1796                                         $addons[] = [$id, (Addon::isEnabled($id) ? "on" : "off"), $info];
1797                                 }
1798                         }
1799                 }
1800         }
1801
1802         $t = Renderer::getMarkupTemplate('admin/addons.tpl');
1803         return Renderer::replaceMacros($t, [
1804                 '$title' => L10n::t('Administration'),
1805                 '$page' => L10n::t('Addons'),
1806                 '$submit' => L10n::t('Save Settings'),
1807                 '$reload' => L10n::t('Reload active addons'),
1808                 '$baseurl' => System::baseUrl(true),
1809                 '$function' => 'addons',
1810                 '$addons' => $addons,
1811                 '$pcount' => count($addons),
1812                 '$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'),
1813                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
1814         ]);
1815 }
1816
1817 /**
1818  * @param array  $themes
1819  * @param string $th
1820  * @param int    $result
1821  */
1822 function toggle_theme(&$themes, $th, &$result)
1823 {
1824         $count = count($themes);
1825         for ($x = 0; $x < $count; $x++) {
1826                 if ($themes[$x]['name'] === $th) {
1827                         if ($themes[$x]['allowed']) {
1828                                 $themes[$x]['allowed'] = 0;
1829                                 $result = 0;
1830                         } else {
1831                                 $themes[$x]['allowed'] = 1;
1832                                 $result = 1;
1833                         }
1834                 }
1835         }
1836 }
1837
1838 /**
1839  * @param array  $themes
1840  * @param string $th
1841  * @return int
1842  */
1843 function theme_status($themes, $th)
1844 {
1845         $count = count($themes);
1846         for ($x = 0; $x < $count; $x++) {
1847                 if ($themes[$x]['name'] === $th) {
1848                         if ($themes[$x]['allowed']) {
1849                                 return 1;
1850                         } else {
1851                                 return 0;
1852                         }
1853                 }
1854         }
1855         return 0;
1856 }
1857
1858 /**
1859  * @param array $themes
1860  * @return string
1861  */
1862 function rebuild_theme_table($themes)
1863 {
1864         $o = '';
1865         if (count($themes)) {
1866                 foreach ($themes as $th) {
1867                         if ($th['allowed']) {
1868                                 if (strlen($o)) {
1869                                         $o .= ',';
1870                                 }
1871                                 $o .= $th['name'];
1872                         }
1873                 }
1874         }
1875         return $o;
1876 }
1877
1878 /**
1879  * @brief Themes admin page
1880  *
1881  * This function generates the admin panel page to control the themes available
1882  * on the friendica node. If the name of a theme is given as parameter a page
1883  * with the details for the theme is shown. Otherwise a list of available
1884  * themes is generated.
1885  *
1886  * The template used for displaying the list of themes and the details of the
1887  * themes are the same as used for the addons.
1888  *
1889  * The returned string contains the HTML code of the admin panel page.
1890  *
1891  * @param App $a
1892  * @return string
1893  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1894  */
1895 function admin_page_themes(App $a)
1896 {
1897         $allowed_themes_str = Config::get('system', 'allowed_themes');
1898         $allowed_themes_raw = explode(',', $allowed_themes_str);
1899         $allowed_themes = [];
1900         if (count($allowed_themes_raw)) {
1901                 foreach ($allowed_themes_raw as $x) {
1902                         if (strlen(trim($x))) {
1903                                 $allowed_themes[] = trim($x);
1904                         }
1905                 }
1906         }
1907
1908         $themes = [];
1909         $files = glob('view/theme/*');
1910         if (is_array($files)) {
1911                 foreach ($files as $file) {
1912                         $f = basename($file);
1913
1914                         // Is there a style file?
1915                         $theme_files = glob('view/theme/' . $f . '/style.*');
1916
1917                         // If not then quit
1918                         if (count($theme_files) == 0) {
1919                                 continue;
1920                         }
1921
1922                         $is_experimental = intval(file_exists($file . '/experimental'));
1923                         $is_supported = 1 - (intval(file_exists($file . '/unsupported')));
1924                         $is_allowed = intval(in_array($f, $allowed_themes));
1925
1926                         if ($is_allowed || $is_supported || Config::get("system", "show_unsupported_themes")) {
1927                                 $themes[] = ['name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed];
1928                         }
1929                 }
1930         }
1931
1932         if (!count($themes)) {
1933                 notice(L10n::t('No themes found.'));
1934                 return '';
1935         }
1936
1937         /*
1938          * Single theme
1939          */
1940
1941         if ($a->argc == 3) {
1942                 $theme = $a->argv[2];
1943                 if (!is_dir("view/theme/$theme")) {
1944                         notice(L10n::t("Item not found."));
1945                         return '';
1946                 }
1947
1948                 if (!empty($_GET['a']) && $_GET['a'] == "t") {
1949                         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/themes', 'admin_themes', 't');
1950
1951                         // Toggle theme status
1952
1953                         toggle_theme($themes, $theme, $result);
1954                         $s = rebuild_theme_table($themes);
1955                         if ($result) {
1956                                 Theme::install($theme);
1957                                 info(sprintf('Theme %s enabled.', $theme));
1958                         } else {
1959                                 Theme::uninstall($theme);
1960                                 info(sprintf('Theme %s disabled.', $theme));
1961                         }
1962
1963                         Config::set('system', 'allowed_themes', $s);
1964                         $a->internalRedirect('admin/themes');
1965                         return ''; // NOTREACHED
1966                 }
1967
1968                 // display theme details
1969                 if (theme_status($themes, $theme)) {
1970                         $status = "on";
1971                         $action = L10n::t("Disable");
1972                 } else {
1973                         $status = "off";
1974                         $action = L10n::t("Enable");
1975                 }
1976
1977                 $readme = null;
1978
1979                 if (is_file("view/theme/$theme/README.md")) {
1980                         $readme = Markdown::convert(file_get_contents("view/theme/$theme/README.md"), false);
1981                 } elseif (is_file("view/theme/$theme/README")) {
1982                         $readme = "<pre>" . file_get_contents("view/theme/$theme/README") . "</pre>";
1983                 }
1984
1985                 $admin_form = '';
1986                 if (is_file("view/theme/$theme/config.php")) {
1987                         require_once "view/theme/$theme/config.php";
1988
1989                         if (function_exists('theme_admin')) {
1990                                 $admin_form = theme_admin($a);
1991                         }
1992                 }
1993
1994                 $screenshot = [Theme::getScreenshot($theme), L10n::t('Screenshot')];
1995                 if (!stristr($screenshot[0], $theme)) {
1996                         $screenshot = null;
1997                 }
1998
1999                 $t = Renderer::getMarkupTemplate('admin/addon_details.tpl');
2000                 return Renderer::replaceMacros($t, [
2001                         '$title' => L10n::t('Administration'),
2002                         '$page' => L10n::t('Themes'),
2003                         '$toggle' => L10n::t('Toggle'),
2004                         '$settings' => L10n::t('Settings'),
2005                         '$baseurl' => System::baseUrl(true),
2006                         '$addon' => $theme . (!empty($_GET['mode']) ? '?mode=' . $_GET['mode'] : ''),
2007                         '$status' => $status,
2008                         '$action' => $action,
2009                         '$info' => Theme::getInfo($theme),
2010                         '$function' => 'themes',
2011                         '$admin_form' => $admin_form,
2012                         '$str_author' => L10n::t('Author: '),
2013                         '$str_maintainer' => L10n::t('Maintainer: '),
2014                         '$screenshot' => $screenshot,
2015                         '$readme' => $readme,
2016
2017                         '$form_security_token' => BaseModule::getFormSecurityToken("admin_themes"),
2018                 ]);
2019         }
2020 }
2021
2022 /**
2023  * @brief Prosesses data send by Logs admin page
2024  *
2025  * @param App $a
2026  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2027  */
2028 function admin_page_logs_post(App $a)
2029 {
2030         if (!empty($_POST['page_logs'])) {
2031                 BaseModule::checkFormSecurityTokenRedirectOnError('/admin/logs', 'admin_logs');
2032
2033                 $logfile   = (!empty($_POST['logfile']) ? Strings::escapeTags(trim($_POST['logfile'])) : '');
2034                 $debugging = !empty($_POST['debugging']);
2035                 $loglevel  = defaults($_POST, 'loglevel', LogLevel::ERROR);
2036
2037                 Config::set('system', 'logfile', $logfile);
2038                 Config::set('system', 'debugging', $debugging);
2039                 Config::set('system', 'loglevel', $loglevel);
2040         }
2041
2042         info(L10n::t("Log settings updated."));
2043         $a->internalRedirect('admin/logs');
2044         return; // NOTREACHED
2045 }
2046
2047 /**
2048  * @brief Generates admin panel subpage for configuration of the logs
2049  *
2050  * This function take the view/templates/admin_logs.tpl file and generates a
2051  * page where admin can configure the logging of friendica.
2052  *
2053  * Displaying the log is separated from the log config as the logfile can get
2054  * big depending on the settings and changing settings regarding the logs can
2055  * thus waste bandwidth.
2056  *
2057  * The string returned contains the content of the template file with replaced
2058  * macros.
2059  *
2060  * @param App $a
2061  * @return string
2062  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2063  */
2064 function admin_page_logs(App $a)
2065 {
2066         $log_choices = [
2067                 LogLevel::ERROR   => 'Error',
2068                 LogLevel::WARNING => 'Warning',
2069                 LogLevel::NOTICE  => 'Notice',
2070                 LogLevel::INFO    => 'Info',
2071                 LogLevel::DEBUG   => 'Debug',
2072         ];
2073
2074         if (ini_get('log_errors')) {
2075                 $phplogenabled = L10n::t('PHP log currently enabled.');
2076         } else {
2077                 $phplogenabled = L10n::t('PHP log currently disabled.');
2078         }
2079
2080         $t = Renderer::getMarkupTemplate('admin/logs.tpl');
2081
2082         return Renderer::replaceMacros($t, [
2083                 '$title' => L10n::t('Administration'),
2084                 '$page' => L10n::t('Logs'),
2085                 '$submit' => L10n::t('Save Settings'),
2086                 '$clear' => L10n::t('Clear'),
2087                 '$baseurl' => System::baseUrl(true),
2088                 '$logname' => Config::get('system', 'logfile'),
2089                 // name, label, value, help string, extra data...
2090                 '$debugging' => ['debugging', L10n::t("Enable Debugging"), Config::get('system', 'debugging'), ""],
2091                 '$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.")],
2092                 '$loglevel' => ['loglevel', L10n::t("Log level"), Config::get('system', 'loglevel'), "", $log_choices],
2093                 '$form_security_token' => BaseModule::getFormSecurityToken("admin_logs"),
2094                 '$phpheader' => L10n::t("PHP logging"),
2095                 '$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."),
2096                 '$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');",
2097                 '$phplogenabled' => $phplogenabled,
2098         ]);
2099 }
2100
2101 /**
2102  * @brief Generates admin panel subpage to view the Friendica log
2103  *
2104  * This function loads the template view/templates/admin_viewlogs.tpl to
2105  * display the systemlog content. The filename for the systemlog of friendica
2106  * is relative to the base directory and taken from the config entry 'logfile'
2107  * in the 'system' category.
2108  *
2109  * Displaying the log is separated from the log config as the logfile can get
2110  * big depending on the settings and changing settings regarding the logs can
2111  * thus waste bandwidth.
2112  *
2113  * The string returned contains the content of the template file with replaced
2114  * macros.
2115  *
2116  * @param App $a
2117  * @return string
2118  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2119  */
2120 function admin_page_viewlogs(App $a)
2121 {
2122         $t = Renderer::getMarkupTemplate('admin/viewlogs.tpl');
2123         $f = Config::get('system', 'logfile');
2124         $data = '';
2125
2126         if (!file_exists($f)) {
2127                 $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);
2128         } else {
2129                 $fp = fopen($f, 'r');
2130                 if (!$fp) {
2131                         $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);
2132                 } else {
2133                         $fstat = fstat($fp);
2134                         $size = $fstat['size'];
2135                         if ($size != 0) {
2136                                 if ($size > 5000000 || $size < 0) {
2137                                         $size = 5000000;
2138                                 }
2139                                 $seek = fseek($fp, 0 - $size, SEEK_END);
2140                                 if ($seek === 0) {
2141                                         $data = Strings::escapeHtml(fread($fp, $size));
2142                                         while (!feof($fp)) {
2143                                                 $data .= Strings::escapeHtml(fread($fp, 4096));
2144                                         }
2145                                 }
2146                         }
2147                         fclose($fp);
2148                 }
2149         }
2150         return Renderer::replaceMacros($t, [
2151                 '$title' => L10n::t('Administration'),
2152                 '$page' => L10n::t('View Logs'),
2153                 '$data' => $data,
2154                 '$logname' => Config::get('system', 'logfile')
2155         ]);
2156 }
2157
2158 /**
2159  * @brief Prosesses data send by the features admin page
2160  *
2161  * @param App $a
2162  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2163  */
2164 function admin_page_features_post(App $a)
2165 {
2166         BaseModule::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features');
2167
2168         Logger::log('postvars: ' . print_r($_POST, true), Logger::DATA);
2169
2170         $features = Feature::get(false);
2171
2172         foreach ($features as $fname => $fdata) {
2173                 foreach (array_slice($fdata, 1) as $f) {
2174                         $feature = $f[0];
2175                         $feature_state = 'feature_' . $feature;
2176                         $featurelock = 'featurelock_' . $feature;
2177
2178                         if (!empty($_POST[$feature_state])) {
2179                                 $val = intval($_POST[$feature_state]);
2180                         } else {
2181                                 $val = 0;
2182                         }
2183                         Config::set('feature', $feature, $val);
2184
2185                         if (!empty($_POST[$featurelock])) {
2186                                 Config::set('feature_lock', $feature, $val);
2187                         } else {
2188                                 Config::delete('feature_lock', $feature);
2189                         }
2190                 }
2191         }
2192
2193         $a->internalRedirect('admin/features');
2194         return; // NOTREACHED
2195 }
2196
2197 /**
2198  * @brief Subpage for global additional feature management
2199  *
2200  * This functin generates the subpage 'Manage Additional Features'
2201  * for the admin panel. At this page the admin can set preferences
2202  * for the user settings of the 'additional features'. If needed this
2203  * preferences can be locked through the admin.
2204  *
2205  * The returned string contains the HTML code of the subpage 'Manage
2206  * Additional Features'
2207  *
2208  * @param App $a
2209  * @return string
2210  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2211  */
2212 function admin_page_features(App $a)
2213 {
2214         if (($a->argc > 1) && ($a->getArgumentValue(1) === 'features')) {
2215                 $arr = [];
2216                 $features = Feature::get(false);
2217
2218                 foreach ($features as $fname => $fdata) {
2219                         $arr[$fname] = [];
2220                         $arr[$fname][0] = $fdata[0];
2221                         foreach (array_slice($fdata, 1) as $f) {
2222                                 $set = Config::get('feature', $f[0], $f[3]);
2223                                 $arr[$fname][1][] = [
2224                                         ['feature_' . $f[0], $f[1], $set, $f[2], [L10n::t('Off'), L10n::t('On')]],
2225                                         ['featurelock_' . $f[0], L10n::t('Lock feature %s', $f[1]), (($f[4] !== false) ? "1" : ''), '', [L10n::t('Off'), L10n::t('On')]]
2226                                 ];
2227                         }
2228                 }
2229
2230                 $tpl = Renderer::getMarkupTemplate('admin/settings_features.tpl');
2231                 $o = Renderer::replaceMacros($tpl, [
2232                         '$form_security_token' => BaseModule::getFormSecurityToken("admin_manage_features"),
2233                         '$title' => L10n::t('Manage Additional Features'),
2234                         '$features' => $arr,
2235                         '$submit' => L10n::t('Save Settings'),
2236                 ]);
2237
2238                 return $o;
2239         }
2240 }
2241
2242 function admin_page_server_vital()
2243 {
2244         // Fetch the host-meta to check if this really is a vital server
2245         return Network::curl(System::baseUrl() . '/.well-known/host-meta')->isSuccess();
2246 }