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