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