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