]> git.mxchange.org Git - friendica.git/blob - mod/admin.php
better names for some variable to reflect their intention
[friendica.git] / mod / admin.php
1 <?php
2
3  /**
4   * Friendica admin
5   */
6 require_once("include/remoteupdate.php");
7 require_once("include/enotify.php");
8 require_once("include/text.php");
9
10
11 /**
12  * @param App $a
13  */
14 function admin_post(&$a){
15
16
17         if(!is_site_admin()) {
18                 return;
19         }
20
21         // do not allow a page manager to access the admin panel at all.
22
23         if(x($_SESSION,'submanage') && intval($_SESSION['submanage']))
24                 return;
25
26
27
28         // urls
29         if ($a->argc > 1){
30                 switch ($a->argv[1]){
31                         case 'site':
32                                 admin_page_site_post($a);
33                                 break;
34                         case 'users':
35                                 admin_page_users_post($a);
36                                 break;
37                         case 'plugins':
38                                 if ($a->argc > 2 &&
39                                         is_file("addon/".$a->argv[2]."/".$a->argv[2].".php")){
40                                                 @include_once("addon/".$a->argv[2]."/".$a->argv[2].".php");
41                                                 if(function_exists($a->argv[2].'_plugin_admin_post')) {
42                                                         $func = $a->argv[2].'_plugin_admin_post';
43                                                         $func($a);
44                                                 }
45                                 }
46                                 goaway($a->get_baseurl(true) . '/admin/plugins/' . $a->argv[2] );
47                                 return; // NOTREACHED
48                                 break;
49                         case 'themes':
50                                 if ($a->argc < 2) {
51                                         if(is_ajax()) return;
52                                         goaway($a->get_baseurl(true) . '/admin/' );
53                                         return;
54                                 }
55
56                                 $theme = $a->argv[2];
57                                 if (is_file("view/theme/$theme/config.php")){
58                                         function __call_theme_admin_post(&$a, $theme) {
59                                                 $orig_theme = $a->theme;
60                                                 $orig_page = $a->page;
61                                                 $orig_session_theme = $_SESSION['theme'];
62                                                 require_once("view/theme/$theme/theme.php");
63                                                 require_once("view/theme/$theme/config.php");
64                                                 $_SESSION['theme'] = $theme;
65
66
67                                                 $init = $theme."_init";
68                                                 if(function_exists($init)) $init($a);
69                                                 if(function_exists("theme_admin_post")){
70                                                         $admin_form = theme_admin_post($a);
71                                                 }
72
73                                                 $_SESSION['theme'] = $orig_session_theme;
74                                                 $a->theme = $orig_theme;
75                                                 $a->page = $orig_page;
76                                                 return $admin_form;
77                                         }
78                                         __call_theme_admin_post($a, $theme);
79                                 }
80                                 info(t('Theme settings updated.'));
81                                 if(is_ajax()) return;
82
83                                 goaway($a->get_baseurl(true) . '/admin/themes/' . $theme );
84                                 return;
85                                 break;
86                         case 'logs':
87                                 admin_page_logs_post($a);
88                                 break;
89                         case 'dbsync':
90                                 admin_page_dbsync_post($a);
91                                 break;
92                         case 'update':
93                                 admin_page_remoteupdate_post($a);
94                                 break;
95                 }
96         }
97
98         goaway($a->get_baseurl(true) . '/admin' );
99         return; // NOTREACHED
100 }
101
102 /**
103  * @param App $a
104  * @return string
105  */
106 function admin_content(&$a) {
107
108         if(!is_site_admin()) {
109                 return login(false);
110         }
111
112         if(x($_SESSION,'submanage') && intval($_SESSION['submanage']))
113                 return "";
114
115         // APC deactivated, since there are problems with PHP 5.5
116         //if (function_exists("apc_delete")) {
117         //      $toDelete = new APCIterator('user', APC_ITER_VALUE);
118         //      apc_delete($toDelete);
119         //}
120
121         /**
122          * Side bar links
123          */
124         $aside_tools = Array();
125         // array( url, name, extra css classes )
126         // not part of $aside to make the template more adjustable
127         $aside_sub = Array(
128                 'site'   =>     Array($a->get_baseurl(true)."/admin/site/", t("Site") , "site"),
129                 'users'  =>     Array($a->get_baseurl(true)."/admin/users/", t("Users") , "users"),
130                 'plugins'=>     Array($a->get_baseurl(true)."/admin/plugins/", t("Plugins") , "plugins"),
131                 'themes' =>     Array($a->get_baseurl(true)."/admin/themes/", t("Themes") , "themes"),
132                 'dbsync' =>     Array($a->get_baseurl(true)."/admin/dbsync/", t('DB updates'), "dbsync"),
133                 'queue'  =>     Array($a->get_baseurl(true)."/admin/queue/", t('Inspect Queue'), "queue"),
134                 'federation' => Array($a->get_baseurl(true)."/admin/federation/", t('Federation Statistics'), "federation"),
135                 //'update' =>   Array($a->get_baseurl(true)."/admin/update/", t("Software Update") , "update")
136         );
137
138         /* get plugins admin page */
139
140         $r = q("SELECT `name` FROM `addon` WHERE `plugin_admin`=1 ORDER BY `name`");
141         $aside_tools['plugins_admin']=Array();
142         foreach ($r as $h){
143                 $plugin =$h['name'];
144                 $aside['plugins_admin'][] = Array($a->get_baseurl(true)."/admin/plugins/".$plugin, $plugin, "plugin");
145                 // temp plugins with admin
146                 $a->plugins_admin[] = $plugin;
147         }
148
149         $aside_tools['logs'] = Array($a->get_baseurl(true)."/admin/logs/", t("Logs"), "logs");
150         $aside_tools['diagnostics_probe'] = Array($a->get_baseurl(true).'/probe/', t('probe address'), 'probe');
151         $aside_tools['diagnostics_webfinger'] = Array($a->get_baseurl(true).'/webfinger/', t('check webfinger'), 'webfinger');
152
153         $t = get_markup_template("admin_aside.tpl");
154         $a->page['aside'] .= replace_macros( $t, array(
155             '$admin' => $aside_tools,
156             '$subpages' => $aside_sub,
157                         '$admtxt' => t('Admin'),
158                         '$plugadmtxt' => t('Plugin Features'),
159                         '$logtxt' => t('Logs'),
160                         '$diagnosticstxt' => t('diagnostics'),
161                         '$h_pending' => t('User registrations waiting for confirmation'),
162                         '$admurl'=> $a->get_baseurl(true)."/admin/"
163         ));
164
165
166
167         /**
168          * Page content
169          */
170         $o = '';
171         // urls
172         if ($a->argc > 1){
173                 switch ($a->argv[1]){
174                         case 'site':
175                                 $o = admin_page_site($a);
176                                 break;
177                         case 'users':
178                                 $o = admin_page_users($a);
179                                 break;
180                         case 'plugins':
181                                 $o = admin_page_plugins($a);
182                                 break;
183                         case 'themes':
184                                 $o = admin_page_themes($a);
185                                 break;
186                         case 'logs':
187                                 $o = admin_page_logs($a);
188                                 break;
189                         case 'dbsync':
190                                 $o = admin_page_dbsync($a);
191                                 break;
192                         case 'update':
193                                 $o = admin_page_remoteupdate($a);
194                                 break;
195                         case 'queue':
196                                 $o = admin_page_queue($a);
197                                 break;
198                         case 'federation':
199                                 $o = admin_page_federation($a);
200                                 break;
201                         default:
202                                 notice( t("Item not found.") );
203                 }
204         } else {
205                 $o = admin_page_summary($a);
206         }
207
208         if(is_ajax()) {
209                 echo $o;
210                 killme();
211                 return '';
212         } else {
213                 return $o;
214         }
215 }
216
217 /**
218  * Admin Federation Stats Page; display some numbers from gserver
219  * @param App $a
220  * returning string
221  */
222 function admin_page_federation(&$a) {
223     // get counts on active friendica, diaspora, redmatrix, hubzilla, gnu
224     // social and statusnet nodes this node is knowing
225     //
226     // We are looking for the following platforms in the DB, "Red" should find
227     // all variants of that platform ID string as the q() function is stripping
228     // off one % two of them are needed in the query
229     $platforms = array('Diaspora', 'Friendica', '%%red%%', 'Hubzilla', 'GNU Social', 'StatusNet');
230     $counts = array();
231     foreach ($platforms as $p) {
232         // get a totaö count for the platform, the name and version of the
233         // highest version and the protocol tpe
234         $c = q('select count(*), platform, network, version from gserver where platform like "'.$p.'" and last_contact > last_failure order by version asc;');
235         // what versions for that platform do we know at all?
236         // again only the active nodes
237         $v = q('select count(*), version from gserver where last_contact > last_failure and platform like "'.$p.'" group by version order by version;');
238         // the 3rd array item is needed for the JavaScript graphs as JS does
239         // not like some characters in the names of variables...
240         $counts[$p]=array($c[0], $v, str_replace(array(' ','%'),'',$p));
241     }
242     // some helpful text
243     $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.');
244     $hint = t('The <em>Auto Discovered Contact Directory</em> feature is not enabled, it will improve the data displayed here.');
245     // load the template, replace the macros and return the page content
246     $t = get_markup_template("admin_federation.tpl");
247     return replace_macros($t, array(
248         '$title' => t('Administration'),
249         '$page' => t('Federation Statistics'),
250         '$intro' => $intro,
251         '$hint' => $hint,
252         '$autoactive' => get_config('system', 'poco_completion'),
253         '$counts' => $counts,
254         '$version' => FRIENDICA_VERSION,
255         '$legendtext' => t('Currently this node is aware of nodes from the following platforms:'),
256     ));
257 }
258 /**
259  * Admin Inspect Queue Page
260  * @param App $a
261  * return string
262  */
263 function admin_page_queue(&$a) {
264         // get content from the queue table
265         $r = q("SELECT c.name,c.nurl,q.id,q.network,q.created,q.last from queue as q, contact as c where c.id=q.cid order by q.cid, q.created;");
266
267         $t = get_markup_template("admin_queue.tpl");
268         return replace_macros($t, array(
269                 '$title' => t('Administration'),
270                 '$page' => t('Inspect Queue'),
271                 '$count' => sizeof($r),
272                 'id_header' => t('ID'),
273                 '$to_header' => t('Recipient Name'),
274                 '$url_header' => t('Recipient Profile'),
275                 '$network_header' => t('Network'),
276                 '$created_header' => t('Created'),
277                 '$last_header' => t('Last Tried'),
278                 '$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.'),
279                 '$entries' => $r,
280         ));
281 }
282 /**
283  * Admin Summary Page
284  * @param App $a
285  * @return string
286  */
287 function admin_page_summary(&$a) {
288         $r = q("SELECT `page-flags`, COUNT(uid) as `count` FROM `user` GROUP BY `page-flags`");
289         $accounts = Array(
290                 Array( t('Normal Account'), 0),
291                 Array( t('Soapbox Account'), 0),
292                 Array( t('Community/Celebrity Account'), 0),
293                 Array( t('Automatic Friend Account'), 0),
294                 Array( t('Blog Account'), 0),
295                 Array( t('Private Forum'), 0)
296         );
297
298         $users=0;
299         foreach ($r as $u){ $accounts[$u['page-flags']][1] = $u['count']; $users+= $u['count']; }
300
301         logger('accounts: ' . print_r($accounts,true),LOGGER_DATA);
302
303         $r = q("SELECT COUNT(id) as `count` FROM `register`");
304         $pending = $r[0]['count'];
305
306         $r = q("select count(*) as total from deliverq where 1");
307         $deliverq = (($r) ? $r[0]['total'] : 0);
308
309         $r = q("select count(*) as total from queue where 1");
310         $queue = (($r) ? $r[0]['total'] : 0);
311
312         // We can do better, but this is a quick queue status
313
314         $queues = array( 'label' => t('Message queues'), 'deliverq' => $deliverq, 'queue' => $queue );
315
316
317         $t = get_markup_template("admin_summary.tpl");
318         return replace_macros($t, array(
319                 '$title' => t('Administration'),
320                 '$page' => t('Summary'),
321                 '$queues' => $queues,
322                 '$users' => Array( t('Registered users'), $users),
323                 '$accounts' => $accounts,
324                 '$pending' => Array( t('Pending registrations'), $pending),
325                 '$version' => Array( t('Version'), FRIENDICA_VERSION),
326                 '$baseurl' => $a->get_baseurl(),
327                 '$platform' => FRIENDICA_PLATFORM,
328                 '$codename' => FRIENDICA_CODENAME,
329                 '$build' =>  get_config('system','build'),
330                 '$plugins' => Array( t('Active plugins'), $a->plugins )
331         ));
332 }
333
334
335 /**
336  * Admin Site Page
337  *  @param App $a
338  */
339 function admin_page_site_post(&$a){
340         if (!x($_POST,"page_site")){
341                 return;
342         }
343
344         check_form_security_token_redirectOnErr('/admin/site', 'admin_site');
345
346         // relocate
347         if (x($_POST,'relocate') && x($_POST,'relocate_url') && $_POST['relocate_url']!=""){
348                 $new_url = $_POST['relocate_url'];
349                 $new_url = rtrim($new_url,"/");
350
351                 $parsed = @parse_url($new_url);
352                 if (!$parsed || (!x($parsed,'host') || !x($parsed,'scheme'))) {
353                         notice(t("Can not parse base url. Must have at least <scheme>://<domain>"));
354                         goaway($a->get_baseurl(true) . '/admin/site' );
355                 }
356
357                 /* steps:
358                  * replace all "baseurl" to "new_url" in config, profile, term, items and contacts
359                  * send relocate for every local user
360                  * */
361
362                 $old_url = $a->get_baseurl(true);
363
364                 function update_table($table_name, $fields, $old_url, $new_url) {
365                         global $db, $a;
366
367                         $dbold = dbesc($old_url);
368                         $dbnew = dbesc($new_url);
369
370                         $upd = array();
371                         foreach ($fields as $f) {
372                                 $upd[] = "`$f` = REPLACE(`$f`, '$dbold', '$dbnew')";
373                         }
374
375                         $upds = implode(", ", $upd);
376
377
378
379                         $q = sprintf("UPDATE %s SET %s;", $table_name, $upds);
380                         $r = q($q);
381                         if (!$r) {
382                                 notice( "Failed updating '$table_name': " . $db->error );
383                                 goaway($a->get_baseurl(true) . '/admin/site' );
384                         }
385                 }
386
387                 // update tables
388                 update_table("profile", array('photo', 'thumb'), $old_url, $new_url);
389                 update_table("term", array('url'), $old_url, $new_url);
390                 update_table("contact", array('photo','thumb','micro','url','nurl','request','notify','poll','confirm','poco'), $old_url, $new_url);
391                 update_table("gcontact", array('photo','url','nurl','server_url'), $old_url, $new_url);
392                 update_table("item", array('owner-link','owner-avatar','author-name','author-link','author-avatar','body','plink','tag'), $old_url, $new_url);
393
394                 // update config
395                 $a->set_baseurl($new_url);
396                 set_config('system','url',$new_url);
397
398                 // send relocate
399                 $users = q("SELECT uid FROM user WHERE account_removed = 0 AND account_expired = 0");
400
401                 foreach ($users as $user) {
402                         proc_run('php', 'include/notifier.php', 'relocate', $user['uid']);
403                 }
404
405                 info("Relocation started. Could take a while to complete.");
406
407                 goaway($a->get_baseurl(true) . '/admin/site' );
408         }
409         // end relocate
410
411         $sitename               =       ((x($_POST,'sitename'))                 ? notags(trim($_POST['sitename']))              : '');
412         $hostname               =       ((x($_POST,'hostname'))                 ? notags(trim($_POST['hostname']))              : '');
413         $sender_email           =       ((x($_POST,'sender_email'))             ? notags(trim($_POST['sender_email']))          : '');
414         $banner                 =       ((x($_POST,'banner'))                   ? trim($_POST['banner'])                        : false);
415         $shortcut_icon          =       ((x($_POST,'shortcut_icon'))            ? notags(trim($_POST['shortcut_icon']))         : '');
416         $touch_icon             =       ((x($_POST,'touch_icon'))               ? notags(trim($_POST['touch_icon']))            : '');
417         $info                   =       ((x($_POST,'info'))                     ? trim($_POST['info'])                  : false);
418         $language               =       ((x($_POST,'language'))                 ? notags(trim($_POST['language']))              : '');
419         $theme                  =       ((x($_POST,'theme'))                    ? notags(trim($_POST['theme']))                 : '');
420         $theme_mobile           =       ((x($_POST,'theme_mobile'))             ? notags(trim($_POST['theme_mobile']))          : '');
421         $maximagesize           =       ((x($_POST,'maximagesize'))             ? intval(trim($_POST['maximagesize']))          :  0);
422         $maximagelength         =       ((x($_POST,'maximagelength'))           ? intval(trim($_POST['maximagelength']))        :  MAX_IMAGE_LENGTH);
423         $jpegimagequality       =       ((x($_POST,'jpegimagequality'))         ? intval(trim($_POST['jpegimagequality']))      :  JPEG_QUALITY);
424
425
426         $register_policy        =       ((x($_POST,'register_policy'))          ? intval(trim($_POST['register_policy']))       :  0);
427         $daily_registrations    =       ((x($_POST,'max_daily_registrations'))  ? intval(trim($_POST['max_daily_registrations']))       :0);
428         $abandon_days           =       ((x($_POST,'abandon_days'))             ? intval(trim($_POST['abandon_days']))          :  0);
429
430         $register_text          =       ((x($_POST,'register_text'))            ? notags(trim($_POST['register_text']))         : '');
431
432         $allowed_sites          =       ((x($_POST,'allowed_sites'))            ? notags(trim($_POST['allowed_sites']))         : '');
433         $allowed_email          =       ((x($_POST,'allowed_email'))            ? notags(trim($_POST['allowed_email']))         : '');
434         $block_public           =       ((x($_POST,'block_public'))             ? True                                          : False);
435         $force_publish          =       ((x($_POST,'publish_all'))              ? True                                          : False);
436         $global_directory       =       ((x($_POST,'directory'))                ? notags(trim($_POST['directory']))     : '');
437         $thread_allow           =       ((x($_POST,'thread_allow'))             ? True                                          : False);
438         $newuser_private                =       ((x($_POST,'newuser_private'))          ? True                                          : False);
439         $enotify_no_content             =       ((x($_POST,'enotify_no_content'))       ? True                                          : False);
440         $private_addons                 =       ((x($_POST,'private_addons'))           ? True                                          : False);
441         $disable_embedded               =       ((x($_POST,'disable_embedded'))         ? True                                          : False);
442         $allow_users_remote_self        =       ((x($_POST,'allow_users_remote_self'))          ? True                                          : False);
443
444         $no_multi_reg           =       ((x($_POST,'no_multi_reg'))             ? True                                          : False);
445         $no_openid              =       !((x($_POST,'no_openid'))               ? True                                          : False);
446         $no_regfullname         =       !((x($_POST,'no_regfullname'))          ? True                                          : False);
447         $no_utf                 =       !((x($_POST,'no_utf'))                  ? True                                          : False);
448         $community_page_style   =       ((x($_POST,'community_page_style'))     ? intval(trim($_POST['community_page_style']))  : 0);
449         $max_author_posts_community_page        =       ((x($_POST,'max_author_posts_community_page'))  ? intval(trim($_POST['max_author_posts_community_page']))       : 0);
450
451         $verifyssl              =       ((x($_POST,'verifyssl'))                ? True                                          : False);
452         $proxyuser              =       ((x($_POST,'proxyuser'))                ? notags(trim($_POST['proxyuser']))             : '');
453         $proxy                  =       ((x($_POST,'proxy'))                    ? notags(trim($_POST['proxy']))                 : '');
454         $timeout                =       ((x($_POST,'timeout'))                  ? intval(trim($_POST['timeout']))               : 60);
455         $delivery_interval      =       ((x($_POST,'delivery_interval'))        ? intval(trim($_POST['delivery_interval']))     : 0);
456         $poll_interval          =       ((x($_POST,'poll_interval'))            ? intval(trim($_POST['poll_interval']))         : 0);
457         $maxloadavg             =       ((x($_POST,'maxloadavg'))               ? intval(trim($_POST['maxloadavg']))            : 50);
458         $maxloadavg_frontend    =       ((x($_POST,'maxloadavg_frontend'))      ? intval(trim($_POST['maxloadavg_frontend']))   : 50);
459         $optimize_max_tablesize =       ((x($_POST,'optimize_max_tablesize'))   ? intval(trim($_POST['optimize_max_tablesize'])): 100);
460         $optimize_fragmentation =       ((x($_POST,'optimize_fragmentation'))   ? intval(trim($_POST['optimize_fragmentation'])): 30);
461         $poco_completion        =       ((x($_POST,'poco_completion'))          ? intval(trim($_POST['poco_completion']))       : false);
462         $poco_requery_days      =       ((x($_POST,'poco_requery_days'))        ? intval(trim($_POST['poco_requery_days']))     : 7);
463         $poco_discovery         =       ((x($_POST,'poco_discovery'))           ? intval(trim($_POST['poco_discovery']))        : 0);
464         $poco_discovery_since   =       ((x($_POST,'poco_discovery_since'))     ? intval(trim($_POST['poco_discovery_since']))  : 30);
465         $poco_local_search      =       ((x($_POST,'poco_local_search'))        ? intval(trim($_POST['poco_local_search']))     : false);
466         $nodeinfo               =       ((x($_POST,'nodeinfo'))                 ? intval(trim($_POST['nodeinfo']))              : false);
467         $dfrn_only              =       ((x($_POST,'dfrn_only'))                ? True                                          : False);
468         $ostatus_disabled       =       !((x($_POST,'ostatus_disabled'))        ? True                                          : False);
469         $ostatus_poll_interval  =       ((x($_POST,'ostatus_poll_interval'))    ? intval(trim($_POST['ostatus_poll_interval'])) :  0);
470         $diaspora_enabled       =       ((x($_POST,'diaspora_enabled'))         ? True                                          : False);
471         $ssl_policy             =       ((x($_POST,'ssl_policy'))               ? intval($_POST['ssl_policy'])                  : 0);
472         $force_ssl              =       ((x($_POST,'force_ssl'))                ? True                                          : False);
473         $old_share              =       ((x($_POST,'old_share'))                ? True                                          : False);
474         $hide_help              =       ((x($_POST,'hide_help'))                ? True                                          : False);
475         $suppress_language      =       ((x($_POST,'suppress_language'))        ? True                                          : False);
476         $suppress_tags          =       ((x($_POST,'suppress_tags'))            ? True                                          : False);
477         $use_fulltext_engine    =       ((x($_POST,'use_fulltext_engine'))      ? True                                          : False);
478         $itemcache              =       ((x($_POST,'itemcache'))                ? notags(trim($_POST['itemcache']))             : '');
479         $itemcache_duration     =       ((x($_POST,'itemcache_duration'))       ? intval($_POST['itemcache_duration'])          : 0);
480         $max_comments           =       ((x($_POST,'max_comments'))             ? intval($_POST['max_comments'])                : 0);
481         $lockpath               =       ((x($_POST,'lockpath'))                 ? notags(trim($_POST['lockpath']))              : '');
482         $temppath               =       ((x($_POST,'temppath'))                 ? notags(trim($_POST['temppath']))              : '');
483         $basepath               =       ((x($_POST,'basepath'))                 ? notags(trim($_POST['basepath']))              : '');
484         $singleuser             =       ((x($_POST,'singleuser'))               ? notags(trim($_POST['singleuser']))            : '');
485         $proxy_disabled         =       ((x($_POST,'proxy_disabled'))           ? True                                          : False);
486         $old_pager              =       ((x($_POST,'old_pager'))                ? True                                          : False);
487         $only_tag_search        =       ((x($_POST,'only_tag_search'))          ? True                                          : False);
488         $rino                   =       ((x($_POST,'rino'))                             ? intval($_POST['rino'])                                : 0);
489         $embedly                =       ((x($_POST,'embedly'))                  ? notags(trim($_POST['embedly']))               : '');
490
491         if ($a->get_path() != "")
492                 $diaspora_enabled = false;
493
494         if (!$thread_allow)
495                 $ostatus_disabled = true;
496
497         if($ssl_policy != intval(get_config('system','ssl_policy'))) {
498                 if($ssl_policy == SSL_POLICY_FULL) {
499                         q("update `contact` set
500                                 `url`     = replace(`url`    , 'http:' , 'https:'),
501                                 `photo`   = replace(`photo`  , 'http:' , 'https:'),
502                                 `thumb`   = replace(`thumb`  , 'http:' , 'https:'),
503                                 `micro`   = replace(`micro`  , 'http:' , 'https:'),
504                                 `request` = replace(`request`, 'http:' , 'https:'),
505                                 `notify`  = replace(`notify` , 'http:' , 'https:'),
506                                 `poll`    = replace(`poll`   , 'http:' , 'https:'),
507                                 `confirm` = replace(`confirm`, 'http:' , 'https:'),
508                                 `poco`    = replace(`poco`   , 'http:' , 'https:')
509                                 where `self` = 1"
510                         );
511                         q("update `profile` set
512                                 `photo`   = replace(`photo`  , 'http:' , 'https:'),
513                                 `thumb`   = replace(`thumb`  , 'http:' , 'https:')
514                                 where 1 "
515                         );
516                 }
517                 elseif($ssl_policy == SSL_POLICY_SELFSIGN) {
518                         q("update `contact` set
519                                 `url`     = replace(`url`    , 'https:' , 'http:'),
520                                 `photo`   = replace(`photo`  , 'https:' , 'http:'),
521                                 `thumb`   = replace(`thumb`  , 'https:' , 'http:'),
522                                 `micro`   = replace(`micro`  , 'https:' , 'http:'),
523                                 `request` = replace(`request`, 'https:' , 'http:'),
524                                 `notify`  = replace(`notify` , 'https:' , 'http:'),
525                                 `poll`    = replace(`poll`   , 'https:' , 'http:'),
526                                 `confirm` = replace(`confirm`, 'https:' , 'http:'),
527                                 `poco`    = replace(`poco`   , 'https:' , 'http:')
528                                 where `self` = 1"
529                         );
530                         q("update `profile` set
531                                 `photo`   = replace(`photo`  , 'https:' , 'http:'),
532                                 `thumb`   = replace(`thumb`  , 'https:' , 'http:')
533                                 where 1 "
534                         );
535                 }
536         }
537         set_config('system','ssl_policy',$ssl_policy);
538         set_config('system','delivery_interval',$delivery_interval);
539         set_config('system','poll_interval',$poll_interval);
540         set_config('system','maxloadavg',$maxloadavg);
541         set_config('system','maxloadavg_frontend',$maxloadavg_frontend);
542         set_config('system','optimize_max_tablesize',$optimize_max_tablesize);
543         set_config('system','optimize_fragmentation',$optimize_fragmentation);
544         set_config('system','poco_completion',$poco_completion);
545         set_config('system','poco_requery_days',$poco_requery_days);
546         set_config('system','poco_discovery',$poco_discovery);
547         set_config('system','poco_discovery_since',$poco_discovery_since);
548         set_config('system','poco_local_search',$poco_local_search);
549         set_config('system','nodeinfo',$nodeinfo);
550         set_config('config','sitename',$sitename);
551         set_config('config','hostname',$hostname);
552         set_config('config','sender_email', $sender_email);
553         set_config('system','suppress_language',$suppress_language);
554         set_config('system','suppress_tags',$suppress_tags);
555         set_config('system','shortcut_icon',$shortcut_icon);
556         set_config('system','touch_icon',$touch_icon);
557
558         if ($banner==""){
559                 // don't know why, but del_config doesn't work...
560                 q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
561                         dbesc("system"),
562                         dbesc("banner")
563                 );
564         } else {
565                 set_config('system','banner', $banner);
566         }
567         if ($info=="") {
568                 del_config('config','info');
569         } else {
570                 set_config('config','info',$info);
571         }
572         set_config('system','language', $language);
573         set_config('system','theme', $theme);
574         if ( $theme_mobile === '---' ) {
575                 del_config('system','mobile-theme');
576         } else {
577                 set_config('system','mobile-theme', $theme_mobile);
578                 }
579                 if ( $singleuser === '---' ) {
580                         del_config('system','singleuser');
581                 } else {
582                         set_config('system','singleuser', $singleuser);
583                 }
584         set_config('system','maximagesize', $maximagesize);
585         set_config('system','max_image_length', $maximagelength);
586         set_config('system','jpeg_quality', $jpegimagequality);
587
588         set_config('config','register_policy', $register_policy);
589         set_config('system','max_daily_registrations', $daily_registrations);
590         set_config('system','account_abandon_days', $abandon_days);
591         set_config('config','register_text', $register_text);
592         set_config('system','allowed_sites', $allowed_sites);
593         set_config('system','allowed_email', $allowed_email);
594         set_config('system','block_public', $block_public);
595         set_config('system','publish_all', $force_publish);
596         set_config('system','directory', $global_directory);
597         set_config('system','thread_allow', $thread_allow);
598         set_config('system','newuser_private', $newuser_private);
599         set_config('system','enotify_no_content', $enotify_no_content);
600         set_config('system','disable_embedded', $disable_embedded);
601         set_config('system','allow_users_remote_self', $allow_users_remote_self);
602
603         set_config('system','block_extended_register', $no_multi_reg);
604         set_config('system','no_openid', $no_openid);
605         set_config('system','no_regfullname', $no_regfullname);
606         set_config('system','community_page_style', $community_page_style);
607         set_config('system','max_author_posts_community_page', $max_author_posts_community_page);
608         set_config('system','no_utf', $no_utf);
609         set_config('system','verifyssl', $verifyssl);
610         set_config('system','proxyuser', $proxyuser);
611         set_config('system','proxy', $proxy);
612         set_config('system','curl_timeout', $timeout);
613         set_config('system','dfrn_only', $dfrn_only);
614         set_config('system','ostatus_disabled', $ostatus_disabled);
615         set_config('system','ostatus_poll_interval', $ostatus_poll_interval);
616         set_config('system','diaspora_enabled', $diaspora_enabled);
617
618         set_config('config','private_addons', $private_addons);
619
620         set_config('system','force_ssl', $force_ssl);
621         set_config('system','old_share', $old_share);
622         set_config('system','hide_help', $hide_help);
623         set_config('system','use_fulltext_engine', $use_fulltext_engine);
624         set_config('system','itemcache', $itemcache);
625         set_config('system','itemcache_duration', $itemcache_duration);
626         set_config('system','max_comments', $max_comments);
627         set_config('system','lockpath', $lockpath);
628         set_config('system','temppath', $temppath);
629         set_config('system','basepath', $basepath);
630         set_config('system','proxy_disabled', $proxy_disabled);
631         set_config('system','old_pager', $old_pager);
632         set_config('system','only_tag_search', $only_tag_search);
633
634
635         if ($rino==2 and !function_exists('mcrypt_create_iv')){
636                 notice(t("RINO2 needs mcrypt php extension to work."));
637         } else {
638                 set_config('system','rino_encrypt', $rino);
639         }
640
641         set_config('system','embedly', $embedly);
642
643
644         info( t('Site settings updated.') . EOL);
645         goaway($a->get_baseurl(true) . '/admin/site' );
646         return; // NOTREACHED
647
648 }
649
650 /**
651  * @param  App $a
652  * @return string
653  */
654 function admin_page_site(&$a) {
655
656         /* Installed langs */
657         $lang_choices = get_avaiable_languages();
658
659         if (strlen(get_config('system','directory_submit_url')) AND
660                 !strlen(get_config('system','directory'))) {
661                 set_config('system','directory', dirname(get_config('system','directory_submit_url')));
662                 del_config('system','directory_submit_url');
663         }
664
665         /* Installed themes */
666         $theme_choices = array();
667         $theme_choices_mobile = array();
668         $theme_choices_mobile["---"] = t("No special theme for mobile devices");
669         $files = glob('view/theme/*'); /**/
670         if($files) {
671                 foreach($files as $file) {
672                         if (intval(file_exists($file . '/unsupported')))
673                                 continue;
674
675                         $f = basename($file);
676                         $theme_name = ((file_exists($file . '/experimental')) ?  sprintf("%s - \x28Experimental\x29", $f) : $f);
677                         if (file_exists($file . '/mobile')) {
678                                 $theme_choices_mobile[$f] = $theme_name;
679                         } else {
680                                 $theme_choices[$f] = $theme_name;
681                         }
682                 }
683         }
684
685         /* Community page style */
686         $community_page_style_choices = array(
687                 CP_NO_COMMUNITY_PAGE => t("No community page"),
688                 CP_USERS_ON_SERVER => t("Public postings from users of this site"),
689                 CP_GLOBAL_COMMUNITY => t("Global community page")
690                 );
691
692         /* OStatus conversation poll choices */
693         $ostatus_poll_choices = array(
694                 "-2" => t("Never"),
695                 "-1" => t("At post arrival"),
696                 "0" => t("Frequently"),
697                 "60" => t("Hourly"),
698                 "720" => t("Twice daily"),
699                 "1440" => t("Daily")
700                 );
701
702         $poco_discovery_choices = array(
703                 "0" => t("Disabled"),
704                 "1" => t("Users"),
705                 "2" => t("Users, Global Contacts"),
706                 "3" => t("Users, Global Contacts/fallback"),
707                 );
708
709         $poco_discovery_since_choices = array(
710                 "30" => t("One month"),
711                 "91" => t("Three months"),
712                 "182" => t("Half a year"),
713                 "365" => t("One year"),
714                 );
715
716         /* get user names to make the install a personal install of X */
717         $user_names = array();
718         $user_names['---'] = t('Multi user instance');
719         $users = q("SELECT username, nickname FROM `user`");
720         foreach ($users as $user) {
721                 $user_names[$user['nickname']] = $user['username'];
722         }
723
724         /* Banner */
725         $banner = get_config('system','banner');
726         if($banner == false)
727                 $banner = '<a href="http://friendica.com"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="http://friendica.com">Friendica</a></span>';
728         $banner = htmlspecialchars($banner);
729         $info = get_config('config','info');
730         $info = htmlspecialchars($info);
731
732         // Automatically create temporary paths
733         get_temppath();
734         get_lockpath();
735         get_itemcachepath();
736
737         //echo "<pre>"; var_dump($lang_choices); die("</pre>");
738
739         /* Register policy */
740         $register_choices = Array(
741                 REGISTER_CLOSED => t("Closed"),
742                 REGISTER_APPROVE => t("Requires approval"),
743                 REGISTER_OPEN => t("Open")
744         );
745
746         $ssl_choices = array(
747                 SSL_POLICY_NONE => t("No SSL policy, links will track page SSL state"),
748                 SSL_POLICY_FULL => t("Force all links to use SSL"),
749                 SSL_POLICY_SELFSIGN => t("Self-signed certificate, use SSL for local links only (discouraged)")
750         );
751
752         if ($a->config['hostname'] == "")
753                 $a->config['hostname'] = $a->get_hostname();
754
755         $diaspora_able = ($a->get_path() == "");
756
757         $t = get_markup_template("admin_site.tpl");
758         return replace_macros($t, array(
759                 '$title' => t('Administration'),
760                 '$page' => t('Site'),
761                 '$submit' => t('Save Settings'),
762                 '$registration' => t('Registration'),
763                 '$upload' => t('File upload'),
764                 '$corporate' => t('Policies'),
765                 '$advanced' => t('Advanced'),
766                 '$portable_contacts' => t('Auto Discovered Contact Directory'),
767                 '$performance' => t('Performance'),
768                 '$relocate'=> t('Relocate - WARNING: advanced function. Could make this server unreachable.'),
769                 '$baseurl' => $a->get_baseurl(true),
770                 // name, label, value, help string, extra data...
771                 '$sitename'             => array('sitename', t("Site name"), $a->config['sitename'],''),
772                 '$hostname'             => array('hostname', t("Host name"), $a->config['hostname'], ""),
773                 '$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"),
774                 '$banner'               => array('banner', t("Banner/Logo"), $banner, ""),
775                 '$shortcut_icon'        => array('shortcut_icon', t("Shortcut icon"), get_config('system','shortcut_icon'),  t("Link to an icon that will be used for browsers.")),
776                 '$touch_icon'           => array('touch_icon', t("Touch icon"), get_config('system','touch_icon'),  t("Link to an icon that will be used for tablets and mobiles.")),
777                 '$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())),
778                 '$language'             => array('language', t("System language"), get_config('system','language'), "", $lang_choices),
779                 '$theme'                => array('theme', t("System theme"), get_config('system','theme'), t("Default system theme - may be over-ridden by user profiles - <a href='#' id='cnftheme'>change theme settings</a>"), $theme_choices),
780                 '$theme_mobile'         => array('theme_mobile', t("Mobile system theme"), get_config('system','mobile-theme'), t("Theme for mobile devices"), $theme_choices_mobile),
781                 '$ssl_policy'           => array('ssl_policy', t("SSL link policy"), (string) intval(get_config('system','ssl_policy')), t("Determines whether generated links should be forced to use SSL"), $ssl_choices),
782                 '$force_ssl'            => array('force_ssl', t("Force SSL"), get_config('system','force_ssl'), t("Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.")),
783                 '$old_share'            => array('old_share', t("Old style 'Share'"), get_config('system','old_share'), t("Deactivates the bbcode element 'share' for repeating items.")),
784                 '$hide_help'            => array('hide_help', t("Hide help entry from navigation menu"), get_config('system','hide_help'), t("Hides the menu entry for the Help pages from the navigation menu. You can still access it calling /help directly.")),
785                 '$singleuser'           => array('singleuser', t("Single user instance"), get_config('system','singleuser'), t("Make this instance multi-user or single-user for the named user"), $user_names),
786                 '$maximagesize'         => array('maximagesize', t("Maximum image size"), get_config('system','maximagesize'), t("Maximum size in bytes of uploaded images. Default is 0, which means no limits.")),
787                 '$maximagelength'               => array('maximagelength', t("Maximum image length"), get_config('system','max_image_length'), t("Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits.")),
788                 '$jpegimagequality'             => array('jpegimagequality', t("JPEG image quality"), get_config('system','jpeg_quality'), t("Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality.")),
789
790                 '$register_policy'      => array('register_policy', t("Register policy"), $a->config['register_policy'], "", $register_choices),
791                 '$daily_registrations'  => array('max_daily_registrations', t("Maximum Daily Registrations"), get_config('system', 'max_daily_registrations'), t("If registration is permitted above, this sets the maximum number of new user registrations to accept per day.  If register is set to closed, this setting has no effect.")),
792                 '$register_text'        => array('register_text', t("Register text"), $a->config['register_text'], t("Will be displayed prominently on the registration page.")),
793                 '$abandon_days'         => array('abandon_days', t('Accounts abandoned after x days'), get_config('system','account_abandon_days'), t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')),
794                 '$allowed_sites'        => array('allowed_sites', t("Allowed friend domains"), get_config('system','allowed_sites'), t("Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains")),
795                 '$allowed_email'        => array('allowed_email', t("Allowed email domains"), get_config('system','allowed_email'), t("Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains")),
796                 '$block_public'         => array('block_public', t("Block public"), get_config('system','block_public'), t("Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.")),
797                 '$force_publish'        => array('publish_all', t("Force publish"), get_config('system','publish_all'), t("Check to force all profiles on this site to be listed in the site directory.")),
798                 '$global_directory'     => array('directory', t("Global directory URL"), get_config('system','directory'), t("URL to the global directory. If this is not set, the global directory is completely unavailable to the application.")),
799                 '$thread_allow'         => array('thread_allow', t("Allow threaded items"), get_config('system','thread_allow'), t("Allow infinite level threading for items on this site.")),
800                 '$newuser_private'      => array('newuser_private', t("Private posts by default for new users"), get_config('system','newuser_private'), t("Set default post permissions for all new members to the default privacy group rather than public.")),
801                 '$enotify_no_content'   => array('enotify_no_content', t("Don't include post content in email notifications"), get_config('system','enotify_no_content'), t("Don't include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.")),
802                 '$private_addons'       => array('private_addons', t("Disallow public access to addons listed in the apps menu."), get_config('config','private_addons'), t("Checking this box will restrict addons listed in the apps menu to members only.")),
803                 '$disable_embedded'     => array('disable_embedded', t("Don't embed private images in posts"), get_config('system','disable_embedded'), t("Don't replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.")),
804                 '$allow_users_remote_self'      => array('allow_users_remote_self', t('Allow Users to set remote_self'), get_config('system','allow_users_remote_self'), t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')),
805                 '$no_multi_reg'         => array('no_multi_reg', t("Block multiple registrations"),  get_config('system','block_extended_register'), t("Disallow users to register additional accounts for use as pages.")),
806                 '$no_openid'            => array('no_openid', t("OpenID support"), !get_config('system','no_openid'), t("OpenID support for registration and logins.")),
807                 '$no_regfullname'       => array('no_regfullname', t("Fullname check"), !get_config('system','no_regfullname'), t("Force users to register with a space between firstname and lastname in Full name, as an antispam measure")),
808                 '$no_utf'               => array('no_utf', t("UTF-8 Regular expressions"), !get_config('system','no_utf'), t("Use PHP UTF8 regular expressions")),
809                 '$community_page_style' => array('community_page_style', t("Community Page Style"), get_config('system','community_page_style'), t("Type of community page to show. 'Global community' shows every public posting from an open distributed network that arrived on this server."), $community_page_style_choices),
810                 '$max_author_posts_community_page' => array('max_author_posts_community_page', t("Posts per user on community page"), get_config('system','max_author_posts_community_page'), t("The maximum number of posts per user on the community page. (Not valid for 'Global Community')")),
811                 '$ostatus_disabled'     => array('ostatus_disabled', t("Enable OStatus support"), !get_config('system','ostatus_disabled'), t("Provide built-in OStatus \x28StatusNet, GNU Social etc.\x29 compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.")),
812                 '$ostatus_poll_interval'        => array('ostatus_poll_interval', t("OStatus conversation completion interval"), (string) intval(get_config('system','ostatus_poll_interval')), t("How often shall the poller check for new entries in OStatus conversations? This can be a very ressource task."), $ostatus_poll_choices),
813                 '$ostatus_not_able'     => t("OStatus support can only be enabled if threading is enabled."),
814                 '$diaspora_able'        => $diaspora_able,
815                 '$diaspora_not_able'    => t("Diaspora support can't be enabled because Friendica was installed into a sub directory."),
816                 '$diaspora_enabled'     => array('diaspora_enabled', t("Enable Diaspora support"), get_config('system','diaspora_enabled'), t("Provide built-in Diaspora network compatibility.")),
817                 '$dfrn_only'            => array('dfrn_only', t('Only allow Friendica contacts'), get_config('system','dfrn_only'), t("All contacts must use Friendica protocols. All other built-in communication protocols disabled.")),
818                 '$verifyssl'            => array('verifyssl', t("Verify SSL"), get_config('system','verifyssl'), t("If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites.")),
819                 '$proxyuser'            => array('proxyuser', t("Proxy user"), get_config('system','proxyuser'), ""),
820                 '$proxy'                => array('proxy', t("Proxy URL"), get_config('system','proxy'), ""),
821                 '$timeout'              => array('timeout', t("Network timeout"), (x(get_config('system','curl_timeout'))?get_config('system','curl_timeout'):60), t("Value is in seconds. Set to 0 for unlimited (not recommended).")),
822                 '$delivery_interval'    => array('delivery_interval', t("Delivery interval"), (x(get_config('system','delivery_interval'))?get_config('system','delivery_interval'):2), t("Delay background delivery processes by this many seconds to reduce system load. Recommend: 4-5 for shared hosts, 2-3 for virtual private servers. 0-1 for large dedicated servers.")),
823                 '$poll_interval'        => array('poll_interval', t("Poll interval"), (x(get_config('system','poll_interval'))?get_config('system','poll_interval'):2), t("Delay background polling processes by this many seconds to reduce system load. If 0, use delivery interval.")),
824                 '$maxloadavg'           => array('maxloadavg', t("Maximum Load Average"), ((intval(get_config('system','maxloadavg')) > 0)?get_config('system','maxloadavg'):50), t("Maximum system load before delivery and poll processes are deferred - default 50.")),
825                 '$maxloadavg_frontend'  => array('maxloadavg_frontend', t("Maximum Load Average (Frontend)"), ((intval(get_config('system','maxloadavg_frontend')) > 0)?get_config('system','maxloadavg_frontend'):50), t("Maximum system load before the frontend quits service - default 50.")),
826                 '$optimize_max_tablesize'=> array('optimize_max_tablesize', t("Maximum table size for optimization"), ((intval(get_config('system','optimize_max_tablesize')) > 0)?get_config('system','optimize_max_tablesize'):100), t("Maximum table size (in MB) for the automatic optimization - default 100 MB. Enter -1 to disable it.")),
827                 '$optimize_fragmentation'=> array('optimize_fragmentation', t("Minimum level of fragmentation"), ((intval(get_config('system','optimize_fragmentation')) > 0)?get_config('system','optimize_fragmentation'):30), t("Minimum fragmenation level to start the automatic optimization - default value is 30%.")),
828
829                 '$poco_completion'      => array('poco_completion', t("Periodical check of global contacts"), get_config('system','poco_completion'), t("If enabled, the global contacts are checked periodically for missing or outdated data and the vitality of the contacts and servers.")),
830                 '$poco_requery_days'    => array('poco_requery_days', t("Days between requery"), get_config('system','poco_requery_days'), t("Number of days after which a server is requeried for his contacts.")),
831                 '$poco_discovery'       => array('poco_discovery', t("Discover contacts from other servers"), (string) intval(get_config('system','poco_discovery')), t("Periodically query other servers for contacts. You can choose between 'users': the users on the remote system, 'Global Contacts': active contacts that are known on the system. The fallback is meant for Redmatrix servers and older friendica servers, where global contacts weren't available. The fallback increases the server load, so the recommened setting is 'Users, Global Contacts'."), $poco_discovery_choices),
832                 '$poco_discovery_since' => array('poco_discovery_since', t("Timeframe for fetching global contacts"), (string) intval(get_config('system','poco_discovery_since')), t("When the discovery is activated, this value defines the timeframe for the activity of the global contacts that are fetched from other servers."), $poco_discovery_since_choices),
833                 '$poco_local_search'    => array('poco_local_search', t("Search the local directory"), get_config('system','poco_local_search'), t("Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated.")),
834
835                 '$nodeinfo'             => array('nodeinfo', t("Publish server information"), get_config('system','nodeinfo'), t("If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See <a href='http://the-federation.info/'>the-federation.info</a> for details.")),
836
837                 '$use_fulltext_engine'  => array('use_fulltext_engine', t("Use MySQL full text engine"), get_config('system','use_fulltext_engine'), t("Activates the full text engine. Speeds up search - but can only search for four and more characters.")),
838                 '$suppress_language'    => array('suppress_language', t("Suppress Language"), get_config('system','suppress_language'), t("Suppress language information in meta information about a posting.")),
839                 '$suppress_tags'        => array('suppress_tags', t("Suppress Tags"), get_config('system','suppress_tags'), t("Suppress showing a list of hashtags at the end of the posting.")),
840                 '$itemcache'            => array('itemcache', t("Path to item cache"), get_config('system','itemcache'), t("The item caches buffers generated bbcode and external images.")),
841                 '$itemcache_duration'   => array('itemcache_duration', t("Cache duration in seconds"), get_config('system','itemcache_duration'), t("How long should the cache files be hold? Default value is 86400 seconds (One day). To disable the item cache, set the value to -1.")),
842                 '$max_comments'         => array('max_comments', t("Maximum numbers of comments per post"), get_config('system','max_comments'), t("How much comments should be shown for each post? Default value is 100.")),
843                 '$lockpath'             => array('lockpath', t("Path for lock file"), get_config('system','lockpath'), t("The lock file is used to avoid multiple pollers at one time. Only define a folder here.")),
844                 '$temppath'             => array('temppath', t("Temp path"), get_config('system','temppath'), t("If you have a restricted system where the webserver can't access the system temp path, enter another path here.")),
845                 '$basepath'             => array('basepath', t("Base path to installation"), get_config('system','basepath'), t("If the system cannot detect the correct path to your installation, enter the correct path here. This setting should only be set if you are using a restricted system and symbolic links to your webroot.")),
846                 '$proxy_disabled'       => array('proxy_disabled', t("Disable picture proxy"), get_config('system','proxy_disabled'), t("The picture proxy increases performance and privacy. It shouldn't be used on systems with very low bandwith.")),
847                 '$old_pager'            => array('old_pager', t("Enable old style pager"), get_config('system','old_pager'), t("The old style pager has page numbers but slows down massively the page speed.")),
848                 '$only_tag_search'      => array('only_tag_search', t("Only search in tags"), get_config('system','only_tag_search'), t("On large systems the text search can slow down the system extremely.")),
849
850                 '$relocate_url'         => array('relocate_url', t("New base url"), $a->get_baseurl(), t("Change base url for this server. Sends relocate message to all DFRN contacts of all users.")),
851
852                 '$rino'                 => array('rino', t("RINO Encryption"), intval(get_config('system','rino_encrypt')), t("Encryption layer between nodes."), array("Disabled", "RINO1 (deprecated)", "RINO2")),
853                 '$embedly'              => array('embedly', t("Embedly API key"), get_config('system','embedly'), t("<a href='http://embed.ly'>Embedly</a> is used to fetch additional data for web pages. This is an optional parameter.")),
854
855                 '$form_security_token' => get_form_security_token("admin_site")
856
857         ));
858
859 }
860
861
862 function admin_page_dbsync(&$a) {
863
864         $o = '';
865
866         if($a->argc > 3 && intval($a->argv[3]) && $a->argv[2] === 'mark') {
867                 set_config('database', 'update_' . intval($a->argv[3]), 'success');
868                 $curr = get_config('system','build');
869                 if(intval($curr) == intval($a->argv[3]))
870                         set_config('system','build',intval($curr) + 1);
871                 info( t('Update has been marked successful') . EOL);
872                 goaway($a->get_baseurl(true) . '/admin/dbsync');
873         }
874
875         if(($a->argc > 2) AND (intval($a->argv[2]) OR ($a->argv[2] === 'check'))) {
876                 require_once("include/dbstructure.php");
877                 $retval = update_structure(false, true);
878                 if (!$retval) {
879                         $o .= sprintf(t("Database structure update %s was successfully applied."), DB_UPDATE_VERSION)."<br />";
880                         set_config('database', 'dbupdate_'.DB_UPDATE_VERSION, 'success');
881                 } else
882                         $o .= sprintf(t("Executing of database structure update %s failed with error: %s"),
883                                         DB_UPDATE_VERSION, $retval)."<br />";
884                 if ($a->argv[2] === 'check')
885                         return $o;
886         }
887
888         if ($a->argc > 2 && intval($a->argv[2])) {
889                 require_once('update.php');
890                 $func = 'update_' . intval($a->argv[2]);
891                 if(function_exists($func)) {
892                         $retval = $func();
893                         if($retval === UPDATE_FAILED) {
894                                 $o .= sprintf(t("Executing %s failed with error: %s"), $func, $retval);
895                         }
896                         elseif($retval === UPDATE_SUCCESS) {
897                                 $o .= sprintf(t('Update %s was successfully applied.', $func));
898                                 set_config('database',$func, 'success');
899                         }
900                         else
901                                 $o .= sprintf(t('Update %s did not return a status. Unknown if it succeeded.'), $func);
902                 } else {
903                         $o .= sprintf(t('There was no additional update function %s that needed to be called.'), $func)."<br />";
904                         set_config('database',$func, 'success');
905                 }
906                 return $o;
907         }
908
909         $failed = array();
910         $r = q("select k, v from config where `cat` = 'database' ");
911         if(count($r)) {
912                 foreach($r as $rr) {
913                         $upd = intval(substr($rr['k'],7));
914                         if($upd < 1139 || $rr['v'] === 'success')
915                                 continue;
916                         $failed[] = $upd;
917                 }
918         }
919         if(! count($failed)) {
920                 $o = replace_macros(get_markup_template('structure_check.tpl'),array(
921                         '$base' => $a->get_baseurl(true),
922                         '$banner' => t('No failed updates.'),
923                         '$check' => t('Check database structure'),
924                 ));
925         } else {
926                 $o = replace_macros(get_markup_template('failed_updates.tpl'),array(
927                         '$base' => $a->get_baseurl(true),
928                         '$banner' => t('Failed Updates'),
929                         '$desc' => t('This does not include updates prior to 1139, which did not return a status.'),
930                         '$mark' => t('Mark success (if update was manually applied)'),
931                         '$apply' => t('Attempt to execute this update step automatically'),
932                         '$failed' => $failed
933                 ));
934         }
935
936         return $o;
937
938 }
939
940 /**
941  * Users admin page
942  *
943  * @param App $a
944  */
945 function admin_page_users_post(&$a){
946         $pending = ( x($_POST, 'pending') ? $_POST['pending'] : Array() );
947         $users = ( x($_POST, 'user') ? $_POST['user'] : Array() );
948         $nu_name = ( x($_POST, 'new_user_name') ? $_POST['new_user_name'] : '');
949         $nu_nickname = ( x($_POST, 'new_user_nickname') ? $_POST['new_user_nickname'] : '');
950         $nu_email = ( x($_POST, 'new_user_email') ? $_POST['new_user_email'] : '');
951
952         check_form_security_token_redirectOnErr('/admin/users', 'admin_users');
953
954         if (!($nu_name==="") && !($nu_email==="") && !($nu_nickname==="")) {
955                 require_once('include/user.php');
956
957                 $result = create_user( array('username'=>$nu_name, 'email'=>$nu_email, 'nickname'=>$nu_nickname, 'verified'=>1)  );
958                 if(! $result['success']) {
959                         notice($result['message']);
960                         return;
961                 }
962                 $nu = $result['user'];
963                 $preamble = deindent(t('
964                         Dear %1$s,
965                                 the administrator of %2$s has set up an account for you.'));
966                 $body = deindent(t('
967                         The login details are as follows:
968
969                         Site Location:  %1$s
970                         Login Name:             %2$s
971                         Password:               %3$s
972
973                         You may change your password from your account "Settings" page after logging
974                         in.
975
976                         Please take a few moments to review the other account settings on that page.
977
978                         You may also wish to add some basic information to your default profile
979                         (on the "Profiles" page) so that other people can easily find you.
980
981                         We recommend setting your full name, adding a profile photo,
982                         adding some profile "keywords" (very useful in making new friends) - and
983                         perhaps what country you live in; if you do not wish to be more specific
984                         than that.
985
986                         We fully respect your right to privacy, and none of these items are necessary.
987                         If you are new and do not know anybody here, they may help
988                         you to make some new and interesting friends.
989
990                         Thank you and welcome to %4$s.'));
991
992                 $preamble = sprintf($preamble, $nu['username'], $a->config['sitename']);
993                 $body = sprintf($body, $a->get_baseurl(), $nu['email'], $result['password'], $a->config['sitename']);
994
995                 notification(array(
996                         'type' => "SYSTEM_EMAIL",
997                         'to_email' => $nu['email'],
998                         'subject'=> sprintf( t('Registration details for %s'), $a->config['sitename']),
999                         'preamble'=> $preamble,
1000                         'body' => $body));
1001
1002         }
1003
1004         if (x($_POST,'page_users_block')){
1005                 foreach($users as $uid){
1006                         q("UPDATE `user` SET `blocked`=1-`blocked` WHERE `uid`=%s",
1007                                 intval( $uid )
1008                         );
1009                 }
1010                 notice( sprintf( tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)), count($users)) );
1011         }
1012         if (x($_POST,'page_users_delete')){
1013                 require_once("include/Contact.php");
1014                 foreach($users as $uid){
1015                         user_remove($uid);
1016                 }
1017                 notice( sprintf( tt("%s user deleted", "%s users deleted", count($users)), count($users)) );
1018         }
1019
1020         if (x($_POST,'page_users_approve')){
1021                 require_once("mod/regmod.php");
1022                 foreach($pending as $hash){
1023                         user_allow($hash);
1024                 }
1025         }
1026         if (x($_POST,'page_users_deny')){
1027                 require_once("mod/regmod.php");
1028                 foreach($pending as $hash){
1029                         user_deny($hash);
1030                 }
1031         }
1032         goaway($a->get_baseurl(true) . '/admin/users' );
1033         return; // NOTREACHED
1034 }
1035
1036 /**
1037  * @param App $a
1038  * @return string
1039  */
1040 function admin_page_users(&$a){
1041         if ($a->argc>2) {
1042                 $uid = $a->argv[3];
1043                 $user = q("SELECT username, blocked FROM `user` WHERE `uid`=%d", intval($uid));
1044                 if (count($user)==0){
1045                         notice( 'User not found' . EOL);
1046                         goaway($a->get_baseurl(true) . '/admin/users' );
1047                         return ''; // NOTREACHED
1048                 }
1049                 switch($a->argv[2]){
1050                         case "delete":{
1051                                 check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
1052                                 // delete user
1053                                 require_once("include/Contact.php");
1054                                 user_remove($uid);
1055
1056                                 notice( sprintf(t("User '%s' deleted"), $user[0]['username']) . EOL);
1057                         }; break;
1058                         case "block":{
1059                                 check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
1060                                 q("UPDATE `user` SET `blocked`=%d WHERE `uid`=%s",
1061                                         intval( 1-$user[0]['blocked'] ),
1062                                         intval( $uid )
1063                                 );
1064                                 notice( sprintf( ($user[0]['blocked']?t("User '%s' unblocked"):t("User '%s' blocked")) , $user[0]['username']) . EOL);
1065                         }; break;
1066                 }
1067                 goaway($a->get_baseurl(true) . '/admin/users' );
1068                 return ''; // NOTREACHED
1069
1070         }
1071
1072         /* get pending */
1073         $pending = q("SELECT `register`.*, `contact`.`name`, `user`.`email`
1074                                  FROM `register`
1075                                  LEFT JOIN `contact` ON `register`.`uid` = `contact`.`uid`
1076                                  LEFT JOIN `user` ON `register`.`uid` = `user`.`uid`;");
1077
1078
1079         /* get users */
1080
1081         $total = q("SELECT count(*) as total FROM `user` where 1");
1082         if(count($total)) {
1083                 $a->set_pager_total($total[0]['total']);
1084                 $a->set_pager_itemspage(100);
1085         }
1086
1087
1088         $users = q("SELECT `user` . * , `contact`.`name` , `contact`.`url` , `contact`.`micro`, `lastitem`.`lastitem_date`, `user`.`account_expired`
1089                                 FROM
1090                                         (SELECT MAX(`item`.`changed`) as `lastitem_date`, `item`.`uid`
1091                                         FROM `item`
1092                                         WHERE `item`.`type` = 'wall'
1093                                         GROUP BY `item`.`uid`) AS `lastitem`
1094                                                  RIGHT OUTER JOIN `user` ON `user`.`uid` = `lastitem`.`uid`,
1095                                            `contact`
1096                                 WHERE
1097                                            `user`.`uid` = `contact`.`uid`
1098                                                 AND `user`.`verified` =1
1099                                         AND `contact`.`self` =1
1100                                 ORDER BY `contact`.`name` LIMIT %d, %d
1101                                 ",
1102                                 intval($a->pager['start']),
1103                                 intval($a->pager['itemspage'])
1104                                 );
1105
1106         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1107         $_setup_users = function ($e) use ($adminlist){
1108                 $accounts = Array(
1109                         t('Normal Account'),
1110                         t('Soapbox Account'),
1111                         t('Community/Celebrity Account'),
1112                                                 t('Automatic Friend Account')
1113                 );
1114                 $e['page-flags'] = $accounts[$e['page-flags']];
1115                 $e['register_date'] = relative_date($e['register_date']);
1116                 $e['login_date'] = relative_date($e['login_date']);
1117                 $e['lastitem_date'] = relative_date($e['lastitem_date']);
1118                 //$e['is_admin'] = ($e['email'] === $a->config['admin_email']);
1119                 $e['is_admin'] = in_array($e['email'], $adminlist);
1120                 $e['is_deletable'] = (intval($e['uid']) != local_user());
1121                 $e['deleted'] = ($e['account_removed']?relative_date($e['account_expires_on']):False);
1122                 return $e;
1123         };
1124         $users = array_map($_setup_users, $users);
1125
1126
1127         // Get rid of dashes in key names, Smarty3 can't handle them
1128         // and extracting deleted users
1129
1130         $tmp_users = Array();
1131         $deleted = Array();
1132
1133         while(count($users)) {
1134                 $new_user = Array();
1135                 foreach( array_pop($users) as $k => $v) {
1136                         $k = str_replace('-','_',$k);
1137                         $new_user[$k] = $v;
1138                 }
1139                 if($new_user['deleted']) {
1140                         array_push($deleted, $new_user);
1141                 }
1142                 else {
1143                         array_push($tmp_users, $new_user);
1144                 }
1145         }
1146         //Reversing the two array, and moving $tmp_users to $users
1147         array_reverse($deleted);
1148         while(count($tmp_users)) {
1149                 array_push($users, array_pop($tmp_users));
1150         }
1151
1152         $t = get_markup_template("admin_users.tpl");
1153         $o = replace_macros($t, array(
1154                 // strings //
1155                 '$title' => t('Administration'),
1156                 '$page' => t('Users'),
1157                 '$submit' => t('Add User'),
1158                 '$select_all' => t('select all'),
1159                 '$h_pending' => t('User registrations waiting for confirm'),
1160                 '$h_deleted' => t('User waiting for permanent deletion'),
1161                 '$th_pending' => array( t('Request date'), t('Name'), t('Email') ),
1162                 '$no_pending' =>  t('No registrations.'),
1163                 '$approve' => t('Approve'),
1164                 '$deny' => t('Deny'),
1165                 '$delete' => t('Delete'),
1166                 '$block' => t('Block'),
1167                 '$unblock' => t('Unblock'),
1168                 '$siteadmin' => t('Site admin'),
1169                 '$accountexpired' => t('Account expired'),
1170
1171                 '$h_users' => t('Users'),
1172                 '$h_newuser' => t('New User'),
1173                 '$th_deleted' => array( t('Name'), t('Email'), t('Register date'), t('Last login'), t('Last item'), t('Deleted since') ),
1174                 '$th_users' => array( t('Name'), t('Email'), t('Register date'), t('Last login'), t('Last item'),  t('Account') ),
1175
1176                 '$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?'),
1177                 '$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?'),
1178
1179                 '$form_security_token' => get_form_security_token("admin_users"),
1180
1181                 // values //
1182                 '$baseurl' => $a->get_baseurl(true),
1183
1184                 '$pending' => $pending,
1185                 'deleted' => $deleted,
1186                 '$users' => $users,
1187                 '$newusername'  => array('new_user_name', t("Name"), '', t("Name of the new user.")),
1188                 '$newusernickname'  => array('new_user_nickname', t("Nickname"), '', t("Nickname of the new user.")),
1189                 '$newuseremail'  => array('new_user_email', t("Email"), '', t("Email address of the new user."), '', '', 'email'),
1190         ));
1191         $o .= paginate($a);
1192         return $o;
1193 }
1194
1195
1196 /**
1197  * Plugins admin page
1198  *
1199  * @param App $a
1200  * @return string
1201  */
1202 function admin_page_plugins(&$a){
1203
1204         /**
1205          * Single plugin
1206          */
1207         if ($a->argc == 3){
1208                 $plugin = $a->argv[2];
1209                 if (!is_file("addon/$plugin/$plugin.php")){
1210                         notice( t("Item not found.") );
1211                         return '';
1212                 }
1213
1214                 if (x($_GET,"a") && $_GET['a']=="t"){
1215                         check_form_security_token_redirectOnErr('/admin/plugins', 'admin_themes', 't');
1216
1217                         // Toggle plugin status
1218                         $idx = array_search($plugin, $a->plugins);
1219                         if ($idx !== false){
1220                                 unset($a->plugins[$idx]);
1221                                 uninstall_plugin($plugin);
1222                                 info( sprintf( t("Plugin %s disabled."), $plugin ) );
1223                         } else {
1224                                 $a->plugins[] = $plugin;
1225                                 install_plugin($plugin);
1226                                 info( sprintf( t("Plugin %s enabled."), $plugin ) );
1227                         }
1228                         set_config("system","addon", implode(", ",$a->plugins));
1229                         goaway($a->get_baseurl(true) . '/admin/plugins' );
1230                         return ''; // NOTREACHED
1231                 }
1232                 // display plugin details
1233                 require_once('library/markdown.php');
1234
1235                 if (in_array($plugin, $a->plugins)){
1236                         $status="on"; $action= t("Disable");
1237                 } else {
1238                         $status="off"; $action= t("Enable");
1239                 }
1240
1241                 $readme=Null;
1242                 if (is_file("addon/$plugin/README.md")){
1243                         $readme = file_get_contents("addon/$plugin/README.md");
1244                         $readme = Markdown($readme);
1245                 } else if (is_file("addon/$plugin/README")){
1246                         $readme = "<pre>". file_get_contents("addon/$plugin/README") ."</pre>";
1247                 }
1248
1249                 $admin_form="";
1250                 if (is_array($a->plugins_admin) && in_array($plugin, $a->plugins_admin)){
1251                         @require_once("addon/$plugin/$plugin.php");
1252                         $func = $plugin.'_plugin_admin';
1253                         $func($a, $admin_form);
1254                 }
1255
1256                 $t = get_markup_template("admin_plugins_details.tpl");
1257
1258                 return replace_macros($t, array(
1259                         '$title' => t('Administration'),
1260                         '$page' => t('Plugins'),
1261                         '$toggle' => t('Toggle'),
1262                         '$settings' => t('Settings'),
1263                         '$baseurl' => $a->get_baseurl(true),
1264
1265                         '$plugin' => $plugin,
1266                         '$status' => $status,
1267                         '$action' => $action,
1268                         '$info' => get_plugin_info($plugin),
1269                         '$str_author' => t('Author: '),
1270                         '$str_maintainer' => t('Maintainer: '),
1271
1272                         '$admin_form' => $admin_form,
1273                         '$function' => 'plugins',
1274                         '$screenshot' => '',
1275                         '$readme' => $readme,
1276
1277                         '$form_security_token' => get_form_security_token("admin_themes"),
1278                 ));
1279         }
1280
1281
1282
1283         /**
1284          * List plugins
1285          */
1286
1287         if (x($_GET,"a") && $_GET['a']=="r"){
1288                 check_form_security_token_redirectOnErr($a->get_baseurl().'/admin/plugins', 'admin_themes', 't');
1289                 reload_plugins();
1290                 info("Plugins reloaded");
1291                 goaway($a->get_baseurl().'/admin/plugins');
1292         }
1293
1294         $plugins = array();
1295         $files = glob("addon/*/"); /* */
1296         if($files) {
1297                 foreach($files as $file) {
1298                         if (is_dir($file)){
1299                                 list($tmp, $id)=array_map("trim", explode("/",$file));
1300                                 $info = get_plugin_info($id);
1301                                 $show_plugin = true;
1302
1303                                 // If the addon is unsupported, then only show it, when it is enabled
1304                                 if ((strtolower($info["status"]) == "unsupported") AND !in_array($id,  $a->plugins))
1305                                         $show_plugin = false;
1306
1307                                 // Override the above szenario, when the admin really wants to see outdated stuff
1308                                 if (get_config("system", "show_unsupported_addons"))
1309                                         $show_plugin = true;
1310
1311                                 if ($show_plugin)
1312                                         $plugins[] = array($id, (in_array($id,  $a->plugins)?"on":"off") , $info);
1313                         }
1314                 }
1315         }
1316
1317         $t = get_markup_template("admin_plugins.tpl");
1318         return replace_macros($t, array(
1319                 '$title' => t('Administration'),
1320                 '$page' => t('Plugins'),
1321                 '$submit' => t('Save Settings'),
1322                 '$reload' => t('Reload active plugins'),
1323                 '$baseurl' => $a->get_baseurl(true),
1324                 '$function' => 'plugins',
1325                 '$plugins' => $plugins,
1326                 '$form_security_token' => get_form_security_token("admin_themes"),
1327         ));
1328 }
1329
1330 /**
1331  * @param array $themes
1332  * @param string $th
1333  * @param int $result
1334  */
1335 function toggle_theme(&$themes,$th,&$result) {
1336         for($x = 0; $x < count($themes); $x ++) {
1337                 if($themes[$x]['name'] === $th) {
1338                         if($themes[$x]['allowed']) {
1339                                 $themes[$x]['allowed'] = 0;
1340                                 $result = 0;
1341                         }
1342                         else {
1343                                 $themes[$x]['allowed'] = 1;
1344                                 $result = 1;
1345                         }
1346                 }
1347         }
1348 }
1349
1350 /**
1351  * @param array $themes
1352  * @param string $th
1353  * @return int
1354  */
1355 function theme_status($themes,$th) {
1356         for($x = 0; $x < count($themes); $x ++) {
1357                 if($themes[$x]['name'] === $th) {
1358                         if($themes[$x]['allowed']) {
1359                                 return 1;
1360                         }
1361                         else {
1362                                 return 0;
1363                         }
1364                 }
1365         }
1366         return 0;
1367 }
1368
1369
1370 /**
1371  * @param array $themes
1372  * @return string
1373  */
1374 function rebuild_theme_table($themes) {
1375         $o = '';
1376         if(count($themes)) {
1377                 foreach($themes as $th) {
1378                         if($th['allowed']) {
1379                                 if(strlen($o))
1380                                         $o .= ',';
1381                                 $o .= $th['name'];
1382                         }
1383                 }
1384         }
1385         return $o;
1386 }
1387
1388
1389 /**
1390  * Themes admin page
1391  *
1392  * @param App $a
1393  * @return string
1394  */
1395 function admin_page_themes(&$a){
1396
1397         $allowed_themes_str = get_config('system','allowed_themes');
1398         $allowed_themes_raw = explode(',',$allowed_themes_str);
1399         $allowed_themes = array();
1400         if(count($allowed_themes_raw))
1401                 foreach($allowed_themes_raw as $x)
1402                         if(strlen(trim($x)))
1403                                 $allowed_themes[] = trim($x);
1404
1405         $themes = array();
1406         $files = glob('view/theme/*'); /* */
1407         if($files) {
1408                 foreach($files as $file) {
1409                         $f = basename($file);
1410                         $is_experimental = intval(file_exists($file . '/experimental'));
1411                         $is_supported = 1-(intval(file_exists($file . '/unsupported')));
1412                         $is_allowed = intval(in_array($f,$allowed_themes));
1413
1414                         if ($is_allowed OR $is_supported OR get_config("system", "show_unsupported_themes"))
1415                                 $themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed);
1416                 }
1417         }
1418
1419         if(! count($themes)) {
1420                 notice( t('No themes found.'));
1421                 return '';
1422         }
1423
1424         /**
1425          * Single theme
1426          */
1427
1428         if ($a->argc == 3){
1429                 $theme = $a->argv[2];
1430                 if(! is_dir("view/theme/$theme")){
1431                         notice( t("Item not found.") );
1432                         return '';
1433                 }
1434
1435                 if (x($_GET,"a") && $_GET['a']=="t"){
1436                         check_form_security_token_redirectOnErr('/admin/themes', 'admin_themes', 't');
1437
1438                         // Toggle theme status
1439
1440                         toggle_theme($themes,$theme,$result);
1441                         $s = rebuild_theme_table($themes);
1442                         if($result) {
1443                                 install_theme($theme);
1444                                 info( sprintf('Theme %s enabled.',$theme));
1445                         }
1446                         else {
1447                                 uninstall_theme($theme);
1448                                 info( sprintf('Theme %s disabled.',$theme));
1449                         }
1450
1451                         set_config('system','allowed_themes',$s);
1452                         goaway($a->get_baseurl(true) . '/admin/themes' );
1453                         return ''; // NOTREACHED
1454                 }
1455
1456                 // display theme details
1457                 require_once('library/markdown.php');
1458
1459                 if (theme_status($themes,$theme)) {
1460                         $status="on"; $action= t("Disable");
1461                 } else {
1462                         $status="off"; $action= t("Enable");
1463                 }
1464
1465                 $readme=Null;
1466                 if (is_file("view/theme/$theme/README.md")){
1467                         $readme = file_get_contents("view/theme/$theme/README.md");
1468                         $readme = Markdown($readme);
1469                 } else if (is_file("view/theme/$theme/README")){
1470                         $readme = "<pre>". file_get_contents("view/theme/$theme/README") ."</pre>";
1471                 }
1472
1473                 $admin_form="";
1474                 if (is_file("view/theme/$theme/config.php")){
1475                         function __get_theme_admin_form(&$a, $theme) {
1476                                 $orig_theme = $a->theme;
1477                                 $orig_page = $a->page;
1478                                 $orig_session_theme = $_SESSION['theme'];
1479                                 require_once("view/theme/$theme/theme.php");
1480                                 require_once("view/theme/$theme/config.php");
1481                                 $_SESSION['theme'] = $theme;
1482
1483
1484                                 $init = $theme."_init";
1485                                 if(function_exists($init)) $init($a);
1486                                 if(function_exists("theme_admin")){
1487                                         $admin_form = theme_admin($a);
1488                                 }
1489
1490                                 $_SESSION['theme'] = $orig_session_theme;
1491                                 $a->theme = $orig_theme;
1492                                 $a->page = $orig_page;
1493                                 return $admin_form;
1494                         }
1495                         $admin_form = __get_theme_admin_form($a, $theme);
1496                 }
1497
1498                 $screenshot = array( get_theme_screenshot($theme), t('Screenshot'));
1499                 if(! stristr($screenshot[0],$theme))
1500                         $screenshot = null;
1501
1502                 $t = get_markup_template("admin_plugins_details.tpl");
1503                 return replace_macros($t, array(
1504                         '$title' => t('Administration'),
1505                         '$page' => t('Themes'),
1506                         '$toggle' => t('Toggle'),
1507                         '$settings' => t('Settings'),
1508                         '$baseurl' => $a->get_baseurl(true),
1509
1510                         '$plugin' => $theme,
1511                         '$status' => $status,
1512                         '$action' => $action,
1513                         '$info' => get_theme_info($theme),
1514                         '$function' => 'themes',
1515                         '$admin_form' => $admin_form,
1516                         '$str_author' => t('Author: '),
1517                         '$str_maintainer' => t('Maintainer: '),
1518                         '$screenshot' => $screenshot,
1519                         '$readme' => $readme,
1520
1521                         '$form_security_token' => get_form_security_token("admin_themes"),
1522                 ));
1523         }
1524
1525
1526         // reload active themes
1527         if (x($_GET,"a") && $_GET['a']=="r"){
1528                 check_form_security_token_redirectOnErr($a->get_baseurl().'/admin/themes', 'admin_themes', 't');
1529                 if ($themes) {
1530                         foreach($themes as $th) {
1531                                 if ($th['allowed']) {
1532                                         uninstall_theme($th['name']);
1533                                         install_theme($th['name']);
1534                                 }
1535                         }
1536                 }
1537                 info("Themes reloaded");
1538                 goaway($a->get_baseurl().'/admin/themes');
1539         }
1540
1541         /**
1542          * List themes
1543          */
1544
1545         $xthemes = array();
1546         if($themes) {
1547                 foreach($themes as $th) {
1548                         $xthemes[] = array($th['name'],(($th['allowed']) ? "on" : "off"), get_theme_info($th['name']));
1549                 }
1550         }
1551
1552
1553         $t = get_markup_template("admin_plugins.tpl");
1554         return replace_macros($t, array(
1555                 '$title' => t('Administration'),
1556                 '$page' => t('Themes'),
1557                 '$submit' => t('Save Settings'),
1558                 '$reload' => t('Reload active themes'),
1559                 '$baseurl' => $a->get_baseurl(true),
1560                 '$function' => 'themes',
1561                 '$plugins' => $xthemes,
1562                 '$experimental' => t('[Experimental]'),
1563                 '$unsupported' => t('[Unsupported]'),
1564                 '$form_security_token' => get_form_security_token("admin_themes"),
1565         ));
1566 }
1567
1568
1569 /**
1570  * Logs admin page
1571  *
1572  * @param App $a
1573  */
1574
1575 function admin_page_logs_post(&$a) {
1576         if (x($_POST,"page_logs")) {
1577                 check_form_security_token_redirectOnErr('/admin/logs', 'admin_logs');
1578
1579                 $logfile                =       ((x($_POST,'logfile'))          ? notags(trim($_POST['logfile']))       : '');
1580                 $debugging              =       ((x($_POST,'debugging'))        ? true                                                          : false);
1581                 $loglevel               =       ((x($_POST,'loglevel'))         ? intval(trim($_POST['loglevel']))      : 0);
1582
1583                 set_config('system','logfile', $logfile);
1584                 set_config('system','debugging',  $debugging);
1585                 set_config('system','loglevel', $loglevel);
1586
1587
1588         }
1589
1590         info( t("Log settings updated.") );
1591         goaway($a->get_baseurl(true) . '/admin/logs' );
1592         return; // NOTREACHED
1593 }
1594
1595 /**
1596  * @param App $a
1597  * @return string
1598  */
1599 function admin_page_logs(&$a){
1600
1601         $log_choices = Array(
1602                 LOGGER_NORMAL => 'Normal',
1603                 LOGGER_TRACE => 'Trace',
1604                 LOGGER_DEBUG => 'Debug',
1605                 LOGGER_DATA => 'Data',
1606                 LOGGER_ALL => 'All'
1607         );
1608
1609         $t = get_markup_template("admin_logs.tpl");
1610
1611         $f = get_config('system','logfile');
1612
1613         $data = '';
1614
1615         if(!file_exists($f)) {
1616                 $data = t("Error trying to open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f exist and is
1617 readable.");
1618         }
1619         else {
1620                 $fp = fopen($f, 'r');
1621                 if(!$fp) {
1622                         $data = t("Couldn't open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f is readable.");
1623                 }
1624                 else {
1625                         $fstat = fstat($fp);
1626                         $size = $fstat['size'];
1627                         if($size != 0)
1628                         {
1629                                 if($size > 5000000 || $size < 0)
1630                                         $size = 5000000;
1631                                 $seek = fseek($fp,0-$size,SEEK_END);
1632                                 if($seek === 0) {
1633                                         $data = escape_tags(fread($fp,$size));
1634                                         while(! feof($fp))
1635                                                 $data .= escape_tags(fread($fp,4096));
1636                                 }
1637                         }
1638                         fclose($fp);
1639                 }
1640         }
1641
1642         return replace_macros($t, array(
1643                 '$title' => t('Administration'),
1644                 '$page' => t('Logs'),
1645                 '$submit' => t('Save Settings'),
1646                 '$clear' => t('Clear'),
1647                 '$data' => $data,
1648                 '$baseurl' => $a->get_baseurl(true),
1649                 '$logname' =>  get_config('system','logfile'),
1650
1651                                                                         // name, label, value, help string, extra data...
1652                 '$debugging'            => array('debugging', t("Enable Debugging"),get_config('system','debugging'), ""),
1653                 '$logfile'                      => array('logfile', t("Log file"), get_config('system','logfile'), t("Must be writable by web server. Relative to your Friendica top-level directory.")),
1654                 '$loglevel'             => array('loglevel', t("Log level"), get_config('system','loglevel'), "", $log_choices),
1655
1656                 '$form_security_token' => get_form_security_token("admin_logs"),
1657         ));
1658 }
1659
1660 /**
1661  * @param App $a
1662  */
1663 function admin_page_remoteupdate_post(&$a) {
1664         // this function should be called via ajax post
1665         if(!is_site_admin()) {
1666                 return;
1667         }
1668
1669
1670         if (x($_POST,'remotefile') && $_POST['remotefile']!=""){
1671                 $remotefile = $_POST['remotefile'];
1672                 $ftpdata = (x($_POST['ftphost'])?$_POST:false);
1673                 doUpdate($remotefile, $ftpdata);
1674         } else {
1675                 echo "No remote file to download. Abort!";
1676         }
1677
1678         killme();
1679 }
1680
1681 /**
1682  * @param App $a
1683  * @return string
1684  */
1685 function admin_page_remoteupdate(&$a) {
1686         if(!is_site_admin()) {
1687                 return login(false);
1688         }
1689
1690         $canwrite = canWeWrite();
1691         $canftp = function_exists('ftp_connect');
1692
1693         $needupdate = true;
1694         $u = checkUpdate();
1695         if (!is_array($u)){
1696                 $needupdate = false;
1697                 $u = array('','','');
1698         }
1699
1700         $tpl = get_markup_template("admin_remoteupdate.tpl");
1701         return replace_macros($tpl, array(
1702                 '$baseurl' => $a->get_baseurl(true),
1703                 '$submit' => t("Update now"),
1704                 '$close' => t("Close"),
1705                 '$localversion' => FRIENDICA_VERSION,
1706                 '$remoteversion' => $u[1],
1707                 '$needupdate' => $needupdate,
1708                 '$canwrite' => $canwrite,
1709                 '$canftp'       => $canftp,
1710                 '$ftphost'      => array('ftphost', t("FTP Host"), '',''),
1711                 '$ftppath'      => array('ftppath', t("FTP Path"), '/',''),
1712                 '$ftpuser'      => array('ftpuser', t("FTP User"), '',''),
1713                 '$ftppwd'       => array('ftppwd', t("FTP Password"), '',''),
1714                 '$remotefile'=>array('remotefile','', $u['2'],''),
1715         ));
1716
1717 }