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