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