]> git.mxchange.org Git - friendica.git/blob - mod/admin.php
allow -rc in friendica version listings
[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 total 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
235             where platform like "'.$p.'" and last_contact > last_failure
236             order by version asc;');
237         // what versions for that platform do we know at all?
238         // again only the active nodes
239         $v = q('select count(*), version from gserver
240             where last_contact > last_failure and platform like "'.$p.'" 
241             group by version
242             order by version;');
243         //
244         // clean up version numbers
245         //
246         // in the DB the Diaspora versions have the format x.x.x.x-xx the last
247         // part (-xx) should be removed to clean up the versions from the "head
248         // commit" information and combined into a single entry for x.x.x.x
249         if ($p=='Diaspora') {
250             $newV = array();
251             $newVv = array();
252             foreach($v as $vv) {
253                 $newVC = $vv['count(*)'];
254                 $newVV = $vv['version'];
255                 $posDash = strpos($newVV, '-');
256                 if ($posDash) 
257                     $newVV = substr($newVV, 0, $posDash);
258                 if (isset($newV[$newVV]))
259                 { 
260                     $newV[$newVV] += $newVC; 
261                 } else { 
262                     $newV[$newVV] = $newVC; 
263                 }
264             }
265             foreach ($newV as $key => $value) {
266                 array_push($newVv, array('count(*)'=>$value, 'version'=>$key));
267             }
268             $v = $newVv;
269         }
270         // early friendica versions have the format x.x.xxxx where xxxx is the
271         // DB version stamp; those should be operated out and versions be
272         // conbined
273         if ($p=='Friendica') {
274             $newV = array();
275             $newVv = array();
276             foreach ($v as $vv) {
277                 $newVC = $vv['count(*)'];
278                 $newVV = $vv['version'];
279                 $lastDot = strrpos($newVV,'.');
280                 $len = strlen($newVV)-1;
281                 if (($lastDot == $len-4) && (!strrpos($newVV,'-rc')==$len-3))
282                     $newVV = substr($newVV, 0, $lastDot);
283                 if (isset($newV[$newVV])) 
284                 { 
285                     $newV[$newVV] += $newVC; 
286                 } else { 
287                     $newV[$newVV] = $newVC; 
288                 }
289             }
290             foreach ($newV as $key => $value) {
291                 array_push($newVv, array('count(*)'=>$value, 'version'=>$key));
292             }
293             $v = $newVv;
294         }
295         // the 3rd array item is needed for the JavaScript graphs as JS does
296         // not like some characters in the names of variables...
297         $counts[$p]=array($c[0], $v, str_replace(array(' ','%'),'',$p));
298     }
299     // some helpful text
300     $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.');
301     $hint = t('The <em>Auto Discovered Contact Directory</em> feature is not enabled, it will improve the data displayed here.');
302     // load the template, replace the macros and return the page content
303     $t = get_markup_template("admin_federation.tpl");
304     return replace_macros($t, array(
305         '$title' => t('Administration'),
306         '$page' => t('Federation Statistics'),
307         '$intro' => $intro,
308         '$hint' => $hint,
309         '$autoactive' => get_config('system', 'poco_completion'),
310         '$counts' => $counts,
311         '$version' => FRIENDICA_VERSION,
312         '$legendtext' => t('Currently this node is aware of nodes from the following platforms:'),
313     ));
314 }
315 /**
316  * Admin Inspect Queue Page
317  * @param App $a
318  * return string
319  */
320 function admin_page_queue(&$a) {
321         // get content from the queue table
322         $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;");
323
324         $t = get_markup_template("admin_queue.tpl");
325         return replace_macros($t, array(
326                 '$title' => t('Administration'),
327                 '$page' => t('Inspect Queue'),
328                 '$count' => sizeof($r),
329                 'id_header' => t('ID'),
330                 '$to_header' => t('Recipient Name'),
331                 '$url_header' => t('Recipient Profile'),
332                 '$network_header' => t('Network'),
333                 '$created_header' => t('Created'),
334                 '$last_header' => t('Last Tried'),
335                 '$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.'),
336                 '$entries' => $r,
337         ));
338 }
339 /**
340  * Admin Summary Page
341  * @param App $a
342  * @return string
343  */
344 function admin_page_summary(&$a) {
345         $r = q("SELECT `page-flags`, COUNT(uid) as `count` FROM `user` GROUP BY `page-flags`");
346         $accounts = Array(
347                 Array( t('Normal Account'), 0),
348                 Array( t('Soapbox Account'), 0),
349                 Array( t('Community/Celebrity Account'), 0),
350                 Array( t('Automatic Friend Account'), 0),
351                 Array( t('Blog Account'), 0),
352                 Array( t('Private Forum'), 0)
353         );
354
355         $users=0;
356         foreach ($r as $u){ $accounts[$u['page-flags']][1] = $u['count']; $users+= $u['count']; }
357
358         logger('accounts: ' . print_r($accounts,true),LOGGER_DATA);
359
360         $r = q("SELECT COUNT(id) as `count` FROM `register`");
361         $pending = $r[0]['count'];
362
363         $r = q("select count(*) as total from deliverq where 1");
364         $deliverq = (($r) ? $r[0]['total'] : 0);
365
366         $r = q("select count(*) as total from queue where 1");
367         $queue = (($r) ? $r[0]['total'] : 0);
368
369         // We can do better, but this is a quick queue status
370
371         $queues = array( 'label' => t('Message queues'), 'deliverq' => $deliverq, 'queue' => $queue );
372
373
374         $t = get_markup_template("admin_summary.tpl");
375         return replace_macros($t, array(
376                 '$title' => t('Administration'),
377                 '$page' => t('Summary'),
378                 '$queues' => $queues,
379                 '$users' => Array( t('Registered users'), $users),
380                 '$accounts' => $accounts,
381                 '$pending' => Array( t('Pending registrations'), $pending),
382                 '$version' => Array( t('Version'), FRIENDICA_VERSION),
383                 '$baseurl' => $a->get_baseurl(),
384                 '$platform' => FRIENDICA_PLATFORM,
385                 '$codename' => FRIENDICA_CODENAME,
386                 '$build' =>  get_config('system','build'),
387                 '$plugins' => Array( t('Active plugins'), $a->plugins )
388         ));
389 }
390
391
392 /**
393  * Admin Site Page
394  *  @param App $a
395  */
396 function admin_page_site_post(&$a){
397         if (!x($_POST,"page_site")){
398                 return;
399         }
400
401         check_form_security_token_redirectOnErr('/admin/site', 'admin_site');
402
403         // relocate
404         if (x($_POST,'relocate') && x($_POST,'relocate_url') && $_POST['relocate_url']!=""){
405                 $new_url = $_POST['relocate_url'];
406                 $new_url = rtrim($new_url,"/");
407
408                 $parsed = @parse_url($new_url);
409                 if (!$parsed || (!x($parsed,'host') || !x($parsed,'scheme'))) {
410                         notice(t("Can not parse base url. Must have at least <scheme>://<domain>"));
411                         goaway($a->get_baseurl(true) . '/admin/site' );
412                 }
413
414                 /* steps:
415                  * replace all "baseurl" to "new_url" in config, profile, term, items and contacts
416                  * send relocate for every local user
417                  * */
418
419                 $old_url = $a->get_baseurl(true);
420
421                 function update_table($table_name, $fields, $old_url, $new_url) {
422                         global $db, $a;
423
424                         $dbold = dbesc($old_url);
425                         $dbnew = dbesc($new_url);
426
427                         $upd = array();
428                         foreach ($fields as $f) {
429                                 $upd[] = "`$f` = REPLACE(`$f`, '$dbold', '$dbnew')";
430                         }
431
432                         $upds = implode(", ", $upd);
433
434
435
436                         $q = sprintf("UPDATE %s SET %s;", $table_name, $upds);
437                         $r = q($q);
438                         if (!$r) {
439                                 notice( "Failed updating '$table_name': " . $db->error );
440                                 goaway($a->get_baseurl(true) . '/admin/site' );
441                         }
442                 }
443
444                 // update tables
445                 update_table("profile", array('photo', 'thumb'), $old_url, $new_url);
446                 update_table("term", array('url'), $old_url, $new_url);
447                 update_table("contact", array('photo','thumb','micro','url','nurl','request','notify','poll','confirm','poco'), $old_url, $new_url);
448                 update_table("gcontact", array('photo','url','nurl','server_url'), $old_url, $new_url);
449                 update_table("item", array('owner-link','owner-avatar','author-name','author-link','author-avatar','body','plink','tag'), $old_url, $new_url);
450
451                 // update config
452                 $a->set_baseurl($new_url);
453                 set_config('system','url',$new_url);
454
455                 // send relocate
456                 $users = q("SELECT uid FROM user WHERE account_removed = 0 AND account_expired = 0");
457
458                 foreach ($users as $user) {
459                         proc_run('php', 'include/notifier.php', 'relocate', $user['uid']);
460                 }
461
462                 info("Relocation started. Could take a while to complete.");
463
464                 goaway($a->get_baseurl(true) . '/admin/site' );
465         }
466         // end relocate
467
468         $sitename               =       ((x($_POST,'sitename'))                 ? notags(trim($_POST['sitename']))              : '');
469         $hostname               =       ((x($_POST,'hostname'))                 ? notags(trim($_POST['hostname']))              : '');
470         $sender_email           =       ((x($_POST,'sender_email'))             ? notags(trim($_POST['sender_email']))          : '');
471         $banner                 =       ((x($_POST,'banner'))                   ? trim($_POST['banner'])                        : false);
472         $shortcut_icon          =       ((x($_POST,'shortcut_icon'))            ? notags(trim($_POST['shortcut_icon']))         : '');
473         $touch_icon             =       ((x($_POST,'touch_icon'))               ? notags(trim($_POST['touch_icon']))            : '');
474         $info                   =       ((x($_POST,'info'))                     ? trim($_POST['info'])                  : false);
475         $language               =       ((x($_POST,'language'))                 ? notags(trim($_POST['language']))              : '');
476         $theme                  =       ((x($_POST,'theme'))                    ? notags(trim($_POST['theme']))                 : '');
477         $theme_mobile           =       ((x($_POST,'theme_mobile'))             ? notags(trim($_POST['theme_mobile']))          : '');
478         $maximagesize           =       ((x($_POST,'maximagesize'))             ? intval(trim($_POST['maximagesize']))          :  0);
479         $maximagelength         =       ((x($_POST,'maximagelength'))           ? intval(trim($_POST['maximagelength']))        :  MAX_IMAGE_LENGTH);
480         $jpegimagequality       =       ((x($_POST,'jpegimagequality'))         ? intval(trim($_POST['jpegimagequality']))      :  JPEG_QUALITY);
481
482
483         $register_policy        =       ((x($_POST,'register_policy'))          ? intval(trim($_POST['register_policy']))       :  0);
484         $daily_registrations    =       ((x($_POST,'max_daily_registrations'))  ? intval(trim($_POST['max_daily_registrations']))       :0);
485         $abandon_days           =       ((x($_POST,'abandon_days'))             ? intval(trim($_POST['abandon_days']))          :  0);
486
487         $register_text          =       ((x($_POST,'register_text'))            ? notags(trim($_POST['register_text']))         : '');
488
489         $allowed_sites          =       ((x($_POST,'allowed_sites'))            ? notags(trim($_POST['allowed_sites']))         : '');
490         $allowed_email          =       ((x($_POST,'allowed_email'))            ? notags(trim($_POST['allowed_email']))         : '');
491         $block_public           =       ((x($_POST,'block_public'))             ? True                                          : False);
492         $force_publish          =       ((x($_POST,'publish_all'))              ? True                                          : False);
493         $global_directory       =       ((x($_POST,'directory'))                ? notags(trim($_POST['directory']))     : '');
494         $thread_allow           =       ((x($_POST,'thread_allow'))             ? True                                          : False);
495         $newuser_private                =       ((x($_POST,'newuser_private'))          ? True                                          : False);
496         $enotify_no_content             =       ((x($_POST,'enotify_no_content'))       ? True                                          : False);
497         $private_addons                 =       ((x($_POST,'private_addons'))           ? True                                          : False);
498         $disable_embedded               =       ((x($_POST,'disable_embedded'))         ? True                                          : False);
499         $allow_users_remote_self        =       ((x($_POST,'allow_users_remote_self'))          ? True                                          : False);
500
501         $no_multi_reg           =       ((x($_POST,'no_multi_reg'))             ? True                                          : False);
502         $no_openid              =       !((x($_POST,'no_openid'))               ? True                                          : False);
503         $no_regfullname         =       !((x($_POST,'no_regfullname'))          ? True                                          : False);
504         $no_utf                 =       !((x($_POST,'no_utf'))                  ? True                                          : False);
505         $community_page_style   =       ((x($_POST,'community_page_style'))     ? intval(trim($_POST['community_page_style']))  : 0);
506         $max_author_posts_community_page        =       ((x($_POST,'max_author_posts_community_page'))  ? intval(trim($_POST['max_author_posts_community_page']))       : 0);
507
508         $verifyssl              =       ((x($_POST,'verifyssl'))                ? True                                          : False);
509         $proxyuser              =       ((x($_POST,'proxyuser'))                ? notags(trim($_POST['proxyuser']))             : '');
510         $proxy                  =       ((x($_POST,'proxy'))                    ? notags(trim($_POST['proxy']))                 : '');
511         $timeout                =       ((x($_POST,'timeout'))                  ? intval(trim($_POST['timeout']))               : 60);
512         $delivery_interval      =       ((x($_POST,'delivery_interval'))        ? intval(trim($_POST['delivery_interval']))     : 0);
513         $poll_interval          =       ((x($_POST,'poll_interval'))            ? intval(trim($_POST['poll_interval']))         : 0);
514         $maxloadavg             =       ((x($_POST,'maxloadavg'))               ? intval(trim($_POST['maxloadavg']))            : 50);
515         $maxloadavg_frontend    =       ((x($_POST,'maxloadavg_frontend'))      ? intval(trim($_POST['maxloadavg_frontend']))   : 50);
516         $optimize_max_tablesize =       ((x($_POST,'optimize_max_tablesize'))   ? intval(trim($_POST['optimize_max_tablesize'])): 100);
517         $optimize_fragmentation =       ((x($_POST,'optimize_fragmentation'))   ? intval(trim($_POST['optimize_fragmentation'])): 30);
518         $poco_completion        =       ((x($_POST,'poco_completion'))          ? intval(trim($_POST['poco_completion']))       : false);
519         $poco_requery_days      =       ((x($_POST,'poco_requery_days'))        ? intval(trim($_POST['poco_requery_days']))     : 7);
520         $poco_discovery         =       ((x($_POST,'poco_discovery'))           ? intval(trim($_POST['poco_discovery']))        : 0);
521         $poco_discovery_since   =       ((x($_POST,'poco_discovery_since'))     ? intval(trim($_POST['poco_discovery_since']))  : 30);
522         $poco_local_search      =       ((x($_POST,'poco_local_search'))        ? intval(trim($_POST['poco_local_search']))     : false);
523         $nodeinfo               =       ((x($_POST,'nodeinfo'))                 ? intval(trim($_POST['nodeinfo']))              : false);
524         $dfrn_only              =       ((x($_POST,'dfrn_only'))                ? True                                          : False);
525         $ostatus_disabled       =       !((x($_POST,'ostatus_disabled'))        ? True                                          : False);
526         $ostatus_poll_interval  =       ((x($_POST,'ostatus_poll_interval'))    ? intval(trim($_POST['ostatus_poll_interval'])) :  0);
527         $diaspora_enabled       =       ((x($_POST,'diaspora_enabled'))         ? True                                          : False);
528         $ssl_policy             =       ((x($_POST,'ssl_policy'))               ? intval($_POST['ssl_policy'])                  : 0);
529         $force_ssl              =       ((x($_POST,'force_ssl'))                ? True                                          : False);
530         $old_share              =       ((x($_POST,'old_share'))                ? True                                          : False);
531         $hide_help              =       ((x($_POST,'hide_help'))                ? True                                          : False);
532         $suppress_language      =       ((x($_POST,'suppress_language'))        ? True                                          : False);
533         $suppress_tags          =       ((x($_POST,'suppress_tags'))            ? True                                          : False);
534         $use_fulltext_engine    =       ((x($_POST,'use_fulltext_engine'))      ? True                                          : False);
535         $itemcache              =       ((x($_POST,'itemcache'))                ? notags(trim($_POST['itemcache']))             : '');
536         $itemcache_duration     =       ((x($_POST,'itemcache_duration'))       ? intval($_POST['itemcache_duration'])          : 0);
537         $max_comments           =       ((x($_POST,'max_comments'))             ? intval($_POST['max_comments'])                : 0);
538         $lockpath               =       ((x($_POST,'lockpath'))                 ? notags(trim($_POST['lockpath']))              : '');
539         $temppath               =       ((x($_POST,'temppath'))                 ? notags(trim($_POST['temppath']))              : '');
540         $basepath               =       ((x($_POST,'basepath'))                 ? notags(trim($_POST['basepath']))              : '');
541         $singleuser             =       ((x($_POST,'singleuser'))               ? notags(trim($_POST['singleuser']))            : '');
542         $proxy_disabled         =       ((x($_POST,'proxy_disabled'))           ? True                                          : False);
543         $old_pager              =       ((x($_POST,'old_pager'))                ? True                                          : False);
544         $only_tag_search        =       ((x($_POST,'only_tag_search'))          ? True                                          : False);
545         $rino                   =       ((x($_POST,'rino'))                             ? intval($_POST['rino'])                                : 0);
546         $embedly                =       ((x($_POST,'embedly'))                  ? notags(trim($_POST['embedly']))               : '');
547
548         if ($a->get_path() != "")
549                 $diaspora_enabled = false;
550
551         if (!$thread_allow)
552                 $ostatus_disabled = true;
553
554         if($ssl_policy != intval(get_config('system','ssl_policy'))) {
555                 if($ssl_policy == SSL_POLICY_FULL) {
556                         q("update `contact` set
557                                 `url`     = replace(`url`    , 'http:' , 'https:'),
558                                 `photo`   = replace(`photo`  , 'http:' , 'https:'),
559                                 `thumb`   = replace(`thumb`  , 'http:' , 'https:'),
560                                 `micro`   = replace(`micro`  , 'http:' , 'https:'),
561                                 `request` = replace(`request`, 'http:' , 'https:'),
562                                 `notify`  = replace(`notify` , 'http:' , 'https:'),
563                                 `poll`    = replace(`poll`   , 'http:' , 'https:'),
564                                 `confirm` = replace(`confirm`, 'http:' , 'https:'),
565                                 `poco`    = replace(`poco`   , 'http:' , 'https:')
566                                 where `self` = 1"
567                         );
568                         q("update `profile` set
569                                 `photo`   = replace(`photo`  , 'http:' , 'https:'),
570                                 `thumb`   = replace(`thumb`  , 'http:' , 'https:')
571                                 where 1 "
572                         );
573                 }
574                 elseif($ssl_policy == SSL_POLICY_SELFSIGN) {
575                         q("update `contact` set
576                                 `url`     = replace(`url`    , 'https:' , 'http:'),
577                                 `photo`   = replace(`photo`  , 'https:' , 'http:'),
578                                 `thumb`   = replace(`thumb`  , 'https:' , 'http:'),
579                                 `micro`   = replace(`micro`  , 'https:' , 'http:'),
580                                 `request` = replace(`request`, 'https:' , 'http:'),
581                                 `notify`  = replace(`notify` , 'https:' , 'http:'),
582                                 `poll`    = replace(`poll`   , 'https:' , 'http:'),
583                                 `confirm` = replace(`confirm`, 'https:' , 'http:'),
584                                 `poco`    = replace(`poco`   , 'https:' , 'http:')
585                                 where `self` = 1"
586                         );
587                         q("update `profile` set
588                                 `photo`   = replace(`photo`  , 'https:' , 'http:'),
589                                 `thumb`   = replace(`thumb`  , 'https:' , 'http:')
590                                 where 1 "
591                         );
592                 }
593         }
594         set_config('system','ssl_policy',$ssl_policy);
595         set_config('system','delivery_interval',$delivery_interval);
596         set_config('system','poll_interval',$poll_interval);
597         set_config('system','maxloadavg',$maxloadavg);
598         set_config('system','maxloadavg_frontend',$maxloadavg_frontend);
599         set_config('system','optimize_max_tablesize',$optimize_max_tablesize);
600         set_config('system','optimize_fragmentation',$optimize_fragmentation);
601         set_config('system','poco_completion',$poco_completion);
602         set_config('system','poco_requery_days',$poco_requery_days);
603         set_config('system','poco_discovery',$poco_discovery);
604         set_config('system','poco_discovery_since',$poco_discovery_since);
605         set_config('system','poco_local_search',$poco_local_search);
606         set_config('system','nodeinfo',$nodeinfo);
607         set_config('config','sitename',$sitename);
608         set_config('config','hostname',$hostname);
609         set_config('config','sender_email', $sender_email);
610         set_config('system','suppress_language',$suppress_language);
611         set_config('system','suppress_tags',$suppress_tags);
612         set_config('system','shortcut_icon',$shortcut_icon);
613         set_config('system','touch_icon',$touch_icon);
614
615         if ($banner==""){
616                 // don't know why, but del_config doesn't work...
617                 q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
618                         dbesc("system"),
619                         dbesc("banner")
620                 );
621         } else {
622                 set_config('system','banner', $banner);
623         }
624         if ($info=="") {
625                 del_config('config','info');
626         } else {
627                 set_config('config','info',$info);
628         }
629         set_config('system','language', $language);
630         set_config('system','theme', $theme);
631         if ( $theme_mobile === '---' ) {
632                 del_config('system','mobile-theme');
633         } else {
634                 set_config('system','mobile-theme', $theme_mobile);
635                 }
636                 if ( $singleuser === '---' ) {
637                         del_config('system','singleuser');
638                 } else {
639                         set_config('system','singleuser', $singleuser);
640                 }
641         set_config('system','maximagesize', $maximagesize);
642         set_config('system','max_image_length', $maximagelength);
643         set_config('system','jpeg_quality', $jpegimagequality);
644
645         set_config('config','register_policy', $register_policy);
646         set_config('system','max_daily_registrations', $daily_registrations);
647         set_config('system','account_abandon_days', $abandon_days);
648         set_config('config','register_text', $register_text);
649         set_config('system','allowed_sites', $allowed_sites);
650         set_config('system','allowed_email', $allowed_email);
651         set_config('system','block_public', $block_public);
652         set_config('system','publish_all', $force_publish);
653         set_config('system','directory', $global_directory);
654         set_config('system','thread_allow', $thread_allow);
655         set_config('system','newuser_private', $newuser_private);
656         set_config('system','enotify_no_content', $enotify_no_content);
657         set_config('system','disable_embedded', $disable_embedded);
658         set_config('system','allow_users_remote_self', $allow_users_remote_self);
659
660         set_config('system','block_extended_register', $no_multi_reg);
661         set_config('system','no_openid', $no_openid);
662         set_config('system','no_regfullname', $no_regfullname);
663         set_config('system','community_page_style', $community_page_style);
664         set_config('system','max_author_posts_community_page', $max_author_posts_community_page);
665         set_config('system','no_utf', $no_utf);
666         set_config('system','verifyssl', $verifyssl);
667         set_config('system','proxyuser', $proxyuser);
668         set_config('system','proxy', $proxy);
669         set_config('system','curl_timeout', $timeout);
670         set_config('system','dfrn_only', $dfrn_only);
671         set_config('system','ostatus_disabled', $ostatus_disabled);
672         set_config('system','ostatus_poll_interval', $ostatus_poll_interval);
673         set_config('system','diaspora_enabled', $diaspora_enabled);
674
675         set_config('config','private_addons', $private_addons);
676
677         set_config('system','force_ssl', $force_ssl);
678         set_config('system','old_share', $old_share);
679         set_config('system','hide_help', $hide_help);
680         set_config('system','use_fulltext_engine', $use_fulltext_engine);
681         set_config('system','itemcache', $itemcache);
682         set_config('system','itemcache_duration', $itemcache_duration);
683         set_config('system','max_comments', $max_comments);
684         set_config('system','lockpath', $lockpath);
685         set_config('system','temppath', $temppath);
686         set_config('system','basepath', $basepath);
687         set_config('system','proxy_disabled', $proxy_disabled);
688         set_config('system','old_pager', $old_pager);
689         set_config('system','only_tag_search', $only_tag_search);
690
691
692         if ($rino==2 and !function_exists('mcrypt_create_iv')){
693                 notice(t("RINO2 needs mcrypt php extension to work."));
694         } else {
695                 set_config('system','rino_encrypt', $rino);
696         }
697
698         set_config('system','embedly', $embedly);
699
700
701         info( t('Site settings updated.') . EOL);
702         goaway($a->get_baseurl(true) . '/admin/site' );
703         return; // NOTREACHED
704
705 }
706
707 /**
708  * @param  App $a
709  * @return string
710  */
711 function admin_page_site(&$a) {
712
713         /* Installed langs */
714         $lang_choices = get_avaiable_languages();
715
716         if (strlen(get_config('system','directory_submit_url')) AND
717                 !strlen(get_config('system','directory'))) {
718                 set_config('system','directory', dirname(get_config('system','directory_submit_url')));
719                 del_config('system','directory_submit_url');
720         }
721
722         /* Installed themes */
723         $theme_choices = array();
724         $theme_choices_mobile = array();
725         $theme_choices_mobile["---"] = t("No special theme for mobile devices");
726         $files = glob('view/theme/*'); /**/
727         if($files) {
728                 foreach($files as $file) {
729                         if (intval(file_exists($file . '/unsupported')))
730                                 continue;
731
732                         $f = basename($file);
733                         $theme_name = ((file_exists($file . '/experimental')) ?  sprintf("%s - \x28Experimental\x29", $f) : $f);
734                         if (file_exists($file . '/mobile')) {
735                                 $theme_choices_mobile[$f] = $theme_name;
736                         } else {
737                                 $theme_choices[$f] = $theme_name;
738                         }
739                 }
740         }
741
742         /* Community page style */
743         $community_page_style_choices = array(
744                 CP_NO_COMMUNITY_PAGE => t("No community page"),
745                 CP_USERS_ON_SERVER => t("Public postings from users of this site"),
746                 CP_GLOBAL_COMMUNITY => t("Global community page")
747                 );
748
749         /* OStatus conversation poll choices */
750         $ostatus_poll_choices = array(
751                 "-2" => t("Never"),
752                 "-1" => t("At post arrival"),
753                 "0" => t("Frequently"),
754                 "60" => t("Hourly"),
755                 "720" => t("Twice daily"),
756                 "1440" => t("Daily")
757                 );
758
759         $poco_discovery_choices = array(
760                 "0" => t("Disabled"),
761                 "1" => t("Users"),
762                 "2" => t("Users, Global Contacts"),
763                 "3" => t("Users, Global Contacts/fallback"),
764                 );
765
766         $poco_discovery_since_choices = array(
767                 "30" => t("One month"),
768                 "91" => t("Three months"),
769                 "182" => t("Half a year"),
770                 "365" => t("One year"),
771                 );
772
773         /* get user names to make the install a personal install of X */
774         $user_names = array();
775         $user_names['---'] = t('Multi user instance');
776         $users = q("SELECT username, nickname FROM `user`");
777         foreach ($users as $user) {
778                 $user_names[$user['nickname']] = $user['username'];
779         }
780
781         /* Banner */
782         $banner = get_config('system','banner');
783         if($banner == false)
784                 $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>';
785         $banner = htmlspecialchars($banner);
786         $info = get_config('config','info');
787         $info = htmlspecialchars($info);
788
789         // Automatically create temporary paths
790         get_temppath();
791         get_lockpath();
792         get_itemcachepath();
793
794         //echo "<pre>"; var_dump($lang_choices); die("</pre>");
795
796         /* Register policy */
797         $register_choices = Array(
798                 REGISTER_CLOSED => t("Closed"),
799                 REGISTER_APPROVE => t("Requires approval"),
800                 REGISTER_OPEN => t("Open")
801         );
802
803         $ssl_choices = array(
804                 SSL_POLICY_NONE => t("No SSL policy, links will track page SSL state"),
805                 SSL_POLICY_FULL => t("Force all links to use SSL"),
806                 SSL_POLICY_SELFSIGN => t("Self-signed certificate, use SSL for local links only (discouraged)")
807         );
808
809         if ($a->config['hostname'] == "")
810                 $a->config['hostname'] = $a->get_hostname();
811
812         $diaspora_able = ($a->get_path() == "");
813
814         $t = get_markup_template("admin_site.tpl");
815         return replace_macros($t, array(
816                 '$title' => t('Administration'),
817                 '$page' => t('Site'),
818                 '$submit' => t('Save Settings'),
819                 '$registration' => t('Registration'),
820                 '$upload' => t('File upload'),
821                 '$corporate' => t('Policies'),
822                 '$advanced' => t('Advanced'),
823                 '$portable_contacts' => t('Auto Discovered Contact Directory'),
824                 '$performance' => t('Performance'),
825                 '$relocate'=> t('Relocate - WARNING: advanced function. Could make this server unreachable.'),
826                 '$baseurl' => $a->get_baseurl(true),
827                 // name, label, value, help string, extra data...
828                 '$sitename'             => array('sitename', t("Site name"), $a->config['sitename'],''),
829                 '$hostname'             => array('hostname', t("Host name"), $a->config['hostname'], ""),
830                 '$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"),
831                 '$banner'               => array('banner', t("Banner/Logo"), $banner, ""),
832                 '$shortcut_icon'        => array('shortcut_icon', t("Shortcut icon"), get_config('system','shortcut_icon'),  t("Link to an icon that will be used for browsers.")),
833                 '$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.")),
834                 '$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())),
835                 '$language'             => array('language', t("System language"), get_config('system','language'), "", $lang_choices),
836                 '$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),
837                 '$theme_mobile'         => array('theme_mobile', t("Mobile system theme"), get_config('system','mobile-theme'), t("Theme for mobile devices"), $theme_choices_mobile),
838                 '$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),
839                 '$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.")),
840                 '$old_share'            => array('old_share', t("Old style 'Share'"), get_config('system','old_share'), t("Deactivates the bbcode element 'share' for repeating items.")),
841                 '$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.")),
842                 '$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),
843                 '$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.")),
844                 '$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.")),
845                 '$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.")),
846
847                 '$register_policy'      => array('register_policy', t("Register policy"), $a->config['register_policy'], "", $register_choices),
848                 '$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.")),
849                 '$register_text'        => array('register_text', t("Register text"), $a->config['register_text'], t("Will be displayed prominently on the registration page.")),
850                 '$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.')),
851                 '$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")),
852                 '$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")),
853                 '$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.")),
854                 '$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.")),
855                 '$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.")),
856                 '$thread_allow'         => array('thread_allow', t("Allow threaded items"), get_config('system','thread_allow'), t("Allow infinite level threading for items on this site.")),
857                 '$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.")),
858                 '$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.")),
859                 '$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.")),
860                 '$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.")),
861                 '$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.')),
862                 '$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.")),
863                 '$no_openid'            => array('no_openid', t("OpenID support"), !get_config('system','no_openid'), t("OpenID support for registration and logins.")),
864                 '$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")),
865                 '$no_utf'               => array('no_utf', t("UTF-8 Regular expressions"), !get_config('system','no_utf'), t("Use PHP UTF8 regular expressions")),
866                 '$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),
867                 '$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')")),
868                 '$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.")),
869                 '$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),
870                 '$ostatus_not_able'     => t("OStatus support can only be enabled if threading is enabled."),
871                 '$diaspora_able'        => $diaspora_able,
872                 '$diaspora_not_able'    => t("Diaspora support can't be enabled because Friendica was installed into a sub directory."),
873                 '$diaspora_enabled'     => array('diaspora_enabled', t("Enable Diaspora support"), get_config('system','diaspora_enabled'), t("Provide built-in Diaspora network compatibility.")),
874                 '$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.")),
875                 '$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.")),
876                 '$proxyuser'            => array('proxyuser', t("Proxy user"), get_config('system','proxyuser'), ""),
877                 '$proxy'                => array('proxy', t("Proxy URL"), get_config('system','proxy'), ""),
878                 '$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).")),
879                 '$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.")),
880                 '$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.")),
881                 '$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.")),
882                 '$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.")),
883                 '$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.")),
884                 '$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%.")),
885
886                 '$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.")),
887                 '$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.")),
888                 '$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),
889                 '$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),
890                 '$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.")),
891
892                 '$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.")),
893
894                 '$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.")),
895                 '$suppress_language'    => array('suppress_language', t("Suppress Language"), get_config('system','suppress_language'), t("Suppress language information in meta information about a posting.")),
896                 '$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.")),
897                 '$itemcache'            => array('itemcache', t("Path to item cache"), get_config('system','itemcache'), t("The item caches buffers generated bbcode and external images.")),
898                 '$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.")),
899                 '$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.")),
900                 '$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.")),
901                 '$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.")),
902                 '$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.")),
903                 '$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.")),
904                 '$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.")),
905                 '$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.")),
906
907                 '$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.")),
908
909                 '$rino'                 => array('rino', t("RINO Encryption"), intval(get_config('system','rino_encrypt')), t("Encryption layer between nodes."), array("Disabled", "RINO1 (deprecated)", "RINO2")),
910                 '$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.")),
911
912                 '$form_security_token' => get_form_security_token("admin_site")
913
914         ));
915
916 }
917
918
919 function admin_page_dbsync(&$a) {
920
921         $o = '';
922
923         if($a->argc > 3 && intval($a->argv[3]) && $a->argv[2] === 'mark') {
924                 set_config('database', 'update_' . intval($a->argv[3]), 'success');
925                 $curr = get_config('system','build');
926                 if(intval($curr) == intval($a->argv[3]))
927                         set_config('system','build',intval($curr) + 1);
928                 info( t('Update has been marked successful') . EOL);
929                 goaway($a->get_baseurl(true) . '/admin/dbsync');
930         }
931
932         if(($a->argc > 2) AND (intval($a->argv[2]) OR ($a->argv[2] === 'check'))) {
933                 require_once("include/dbstructure.php");
934                 $retval = update_structure(false, true);
935                 if (!$retval) {
936                         $o .= sprintf(t("Database structure update %s was successfully applied."), DB_UPDATE_VERSION)."<br />";
937                         set_config('database', 'dbupdate_'.DB_UPDATE_VERSION, 'success');
938                 } else
939                         $o .= sprintf(t("Executing of database structure update %s failed with error: %s"),
940                                         DB_UPDATE_VERSION, $retval)."<br />";
941                 if ($a->argv[2] === 'check')
942                         return $o;
943         }
944
945         if ($a->argc > 2 && intval($a->argv[2])) {
946                 require_once('update.php');
947                 $func = 'update_' . intval($a->argv[2]);
948                 if(function_exists($func)) {
949                         $retval = $func();
950                         if($retval === UPDATE_FAILED) {
951                                 $o .= sprintf(t("Executing %s failed with error: %s"), $func, $retval);
952                         }
953                         elseif($retval === UPDATE_SUCCESS) {
954                                 $o .= sprintf(t('Update %s was successfully applied.', $func));
955                                 set_config('database',$func, 'success');
956                         }
957                         else
958                                 $o .= sprintf(t('Update %s did not return a status. Unknown if it succeeded.'), $func);
959                 } else {
960                         $o .= sprintf(t('There was no additional update function %s that needed to be called.'), $func)."<br />";
961                         set_config('database',$func, 'success');
962                 }
963                 return $o;
964         }
965
966         $failed = array();
967         $r = q("select k, v from config where `cat` = 'database' ");
968         if(count($r)) {
969                 foreach($r as $rr) {
970                         $upd = intval(substr($rr['k'],7));
971                         if($upd < 1139 || $rr['v'] === 'success')
972                                 continue;
973                         $failed[] = $upd;
974                 }
975         }
976         if(! count($failed)) {
977                 $o = replace_macros(get_markup_template('structure_check.tpl'),array(
978                         '$base' => $a->get_baseurl(true),
979                         '$banner' => t('No failed updates.'),
980                         '$check' => t('Check database structure'),
981                 ));
982         } else {
983                 $o = replace_macros(get_markup_template('failed_updates.tpl'),array(
984                         '$base' => $a->get_baseurl(true),
985                         '$banner' => t('Failed Updates'),
986                         '$desc' => t('This does not include updates prior to 1139, which did not return a status.'),
987                         '$mark' => t('Mark success (if update was manually applied)'),
988                         '$apply' => t('Attempt to execute this update step automatically'),
989                         '$failed' => $failed
990                 ));
991         }
992
993         return $o;
994
995 }
996
997 /**
998  * Users admin page
999  *
1000  * @param App $a
1001  */
1002 function admin_page_users_post(&$a){
1003         $pending = ( x($_POST, 'pending') ? $_POST['pending'] : Array() );
1004         $users = ( x($_POST, 'user') ? $_POST['user'] : Array() );
1005         $nu_name = ( x($_POST, 'new_user_name') ? $_POST['new_user_name'] : '');
1006         $nu_nickname = ( x($_POST, 'new_user_nickname') ? $_POST['new_user_nickname'] : '');
1007         $nu_email = ( x($_POST, 'new_user_email') ? $_POST['new_user_email'] : '');
1008
1009         check_form_security_token_redirectOnErr('/admin/users', 'admin_users');
1010
1011         if (!($nu_name==="") && !($nu_email==="") && !($nu_nickname==="")) {
1012                 require_once('include/user.php');
1013
1014                 $result = create_user( array('username'=>$nu_name, 'email'=>$nu_email, 'nickname'=>$nu_nickname, 'verified'=>1)  );
1015                 if(! $result['success']) {
1016                         notice($result['message']);
1017                         return;
1018                 }
1019                 $nu = $result['user'];
1020                 $preamble = deindent(t('
1021                         Dear %1$s,
1022                                 the administrator of %2$s has set up an account for you.'));
1023                 $body = deindent(t('
1024                         The login details are as follows:
1025
1026                         Site Location:  %1$s
1027                         Login Name:             %2$s
1028                         Password:               %3$s
1029
1030                         You may change your password from your account "Settings" page after logging
1031                         in.
1032
1033                         Please take a few moments to review the other account settings on that page.
1034
1035                         You may also wish to add some basic information to your default profile
1036                         (on the "Profiles" page) so that other people can easily find you.
1037
1038                         We recommend setting your full name, adding a profile photo,
1039                         adding some profile "keywords" (very useful in making new friends) - and
1040                         perhaps what country you live in; if you do not wish to be more specific
1041                         than that.
1042
1043                         We fully respect your right to privacy, and none of these items are necessary.
1044                         If you are new and do not know anybody here, they may help
1045                         you to make some new and interesting friends.
1046
1047                         Thank you and welcome to %4$s.'));
1048
1049                 $preamble = sprintf($preamble, $nu['username'], $a->config['sitename']);
1050                 $body = sprintf($body, $a->get_baseurl(), $nu['email'], $result['password'], $a->config['sitename']);
1051
1052                 notification(array(
1053                         'type' => "SYSTEM_EMAIL",
1054                         'to_email' => $nu['email'],
1055                         'subject'=> sprintf( t('Registration details for %s'), $a->config['sitename']),
1056                         'preamble'=> $preamble,
1057                         'body' => $body));
1058
1059         }
1060
1061         if (x($_POST,'page_users_block')){
1062                 foreach($users as $uid){
1063                         q("UPDATE `user` SET `blocked`=1-`blocked` WHERE `uid`=%s",
1064                                 intval( $uid )
1065                         );
1066                 }
1067                 notice( sprintf( tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)), count($users)) );
1068         }
1069         if (x($_POST,'page_users_delete')){
1070                 require_once("include/Contact.php");
1071                 foreach($users as $uid){
1072                         user_remove($uid);
1073                 }
1074                 notice( sprintf( tt("%s user deleted", "%s users deleted", count($users)), count($users)) );
1075         }
1076
1077         if (x($_POST,'page_users_approve')){
1078                 require_once("mod/regmod.php");
1079                 foreach($pending as $hash){
1080                         user_allow($hash);
1081                 }
1082         }
1083         if (x($_POST,'page_users_deny')){
1084                 require_once("mod/regmod.php");
1085                 foreach($pending as $hash){
1086                         user_deny($hash);
1087                 }
1088         }
1089         goaway($a->get_baseurl(true) . '/admin/users' );
1090         return; // NOTREACHED
1091 }
1092
1093 /**
1094  * @param App $a
1095  * @return string
1096  */
1097 function admin_page_users(&$a){
1098         if ($a->argc>2) {
1099                 $uid = $a->argv[3];
1100                 $user = q("SELECT username, blocked FROM `user` WHERE `uid`=%d", intval($uid));
1101                 if (count($user)==0){
1102                         notice( 'User not found' . EOL);
1103                         goaway($a->get_baseurl(true) . '/admin/users' );
1104                         return ''; // NOTREACHED
1105                 }
1106                 switch($a->argv[2]){
1107                         case "delete":{
1108                                 check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
1109                                 // delete user
1110                                 require_once("include/Contact.php");
1111                                 user_remove($uid);
1112
1113                                 notice( sprintf(t("User '%s' deleted"), $user[0]['username']) . EOL);
1114                         }; break;
1115                         case "block":{
1116                                 check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
1117                                 q("UPDATE `user` SET `blocked`=%d WHERE `uid`=%s",
1118                                         intval( 1-$user[0]['blocked'] ),
1119                                         intval( $uid )
1120                                 );
1121                                 notice( sprintf( ($user[0]['blocked']?t("User '%s' unblocked"):t("User '%s' blocked")) , $user[0]['username']) . EOL);
1122                         }; break;
1123                 }
1124                 goaway($a->get_baseurl(true) . '/admin/users' );
1125                 return ''; // NOTREACHED
1126
1127         }
1128
1129         /* get pending */
1130         $pending = q("SELECT `register`.*, `contact`.`name`, `user`.`email`
1131                                  FROM `register`
1132                                  LEFT JOIN `contact` ON `register`.`uid` = `contact`.`uid`
1133                                  LEFT JOIN `user` ON `register`.`uid` = `user`.`uid`;");
1134
1135
1136         /* get users */
1137
1138         $total = q("SELECT count(*) as total FROM `user` where 1");
1139         if(count($total)) {
1140                 $a->set_pager_total($total[0]['total']);
1141                 $a->set_pager_itemspage(100);
1142         }
1143
1144
1145         $users = q("SELECT `user` . * , `contact`.`name` , `contact`.`url` , `contact`.`micro`, `lastitem`.`lastitem_date`, `user`.`account_expired`
1146                                 FROM
1147                                         (SELECT MAX(`item`.`changed`) as `lastitem_date`, `item`.`uid`
1148                                         FROM `item`
1149                                         WHERE `item`.`type` = 'wall'
1150                                         GROUP BY `item`.`uid`) AS `lastitem`
1151                                                  RIGHT OUTER JOIN `user` ON `user`.`uid` = `lastitem`.`uid`,
1152                                            `contact`
1153                                 WHERE
1154                                            `user`.`uid` = `contact`.`uid`
1155                                                 AND `user`.`verified` =1
1156                                         AND `contact`.`self` =1
1157                                 ORDER BY `contact`.`name` LIMIT %d, %d
1158                                 ",
1159                                 intval($a->pager['start']),
1160                                 intval($a->pager['itemspage'])
1161                                 );
1162
1163         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1164         $_setup_users = function ($e) use ($adminlist){
1165                 $accounts = Array(
1166                         t('Normal Account'),
1167                         t('Soapbox Account'),
1168                         t('Community/Celebrity Account'),
1169                                                 t('Automatic Friend Account')
1170                 );
1171                 $e['page-flags'] = $accounts[$e['page-flags']];
1172                 $e['register_date'] = relative_date($e['register_date']);
1173                 $e['login_date'] = relative_date($e['login_date']);
1174                 $e['lastitem_date'] = relative_date($e['lastitem_date']);
1175                 //$e['is_admin'] = ($e['email'] === $a->config['admin_email']);
1176                 $e['is_admin'] = in_array($e['email'], $adminlist);
1177                 $e['is_deletable'] = (intval($e['uid']) != local_user());
1178                 $e['deleted'] = ($e['account_removed']?relative_date($e['account_expires_on']):False);
1179                 return $e;
1180         };
1181         $users = array_map($_setup_users, $users);
1182
1183
1184         // Get rid of dashes in key names, Smarty3 can't handle them
1185         // and extracting deleted users
1186
1187         $tmp_users = Array();
1188         $deleted = Array();
1189
1190         while(count($users)) {
1191                 $new_user = Array();
1192                 foreach( array_pop($users) as $k => $v) {
1193                         $k = str_replace('-','_',$k);
1194                         $new_user[$k] = $v;
1195                 }
1196                 if($new_user['deleted']) {
1197                         array_push($deleted, $new_user);
1198                 }
1199                 else {
1200                         array_push($tmp_users, $new_user);
1201                 }
1202         }
1203         //Reversing the two array, and moving $tmp_users to $users
1204         array_reverse($deleted);
1205         while(count($tmp_users)) {
1206                 array_push($users, array_pop($tmp_users));
1207         }
1208
1209         $t = get_markup_template("admin_users.tpl");
1210         $o = replace_macros($t, array(
1211                 // strings //
1212                 '$title' => t('Administration'),
1213                 '$page' => t('Users'),
1214                 '$submit' => t('Add User'),
1215                 '$select_all' => t('select all'),
1216                 '$h_pending' => t('User registrations waiting for confirm'),
1217                 '$h_deleted' => t('User waiting for permanent deletion'),
1218                 '$th_pending' => array( t('Request date'), t('Name'), t('Email') ),
1219                 '$no_pending' =>  t('No registrations.'),
1220                 '$approve' => t('Approve'),
1221                 '$deny' => t('Deny'),
1222                 '$delete' => t('Delete'),
1223                 '$block' => t('Block'),
1224                 '$unblock' => t('Unblock'),
1225                 '$siteadmin' => t('Site admin'),
1226                 '$accountexpired' => t('Account expired'),
1227
1228                 '$h_users' => t('Users'),
1229                 '$h_newuser' => t('New User'),
1230                 '$th_deleted' => array( t('Name'), t('Email'), t('Register date'), t('Last login'), t('Last item'), t('Deleted since') ),
1231                 '$th_users' => array( t('Name'), t('Email'), t('Register date'), t('Last login'), t('Last item'),  t('Account') ),
1232
1233                 '$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?'),
1234                 '$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?'),
1235
1236                 '$form_security_token' => get_form_security_token("admin_users"),
1237
1238                 // values //
1239                 '$baseurl' => $a->get_baseurl(true),
1240
1241                 '$pending' => $pending,
1242                 'deleted' => $deleted,
1243                 '$users' => $users,
1244                 '$newusername'  => array('new_user_name', t("Name"), '', t("Name of the new user.")),
1245                 '$newusernickname'  => array('new_user_nickname', t("Nickname"), '', t("Nickname of the new user.")),
1246                 '$newuseremail'  => array('new_user_email', t("Email"), '', t("Email address of the new user."), '', '', 'email'),
1247         ));
1248         $o .= paginate($a);
1249         return $o;
1250 }
1251
1252
1253 /**
1254  * Plugins admin page
1255  *
1256  * @param App $a
1257  * @return string
1258  */
1259 function admin_page_plugins(&$a){
1260
1261         /**
1262          * Single plugin
1263          */
1264         if ($a->argc == 3){
1265                 $plugin = $a->argv[2];
1266                 if (!is_file("addon/$plugin/$plugin.php")){
1267                         notice( t("Item not found.") );
1268                         return '';
1269                 }
1270
1271                 if (x($_GET,"a") && $_GET['a']=="t"){
1272                         check_form_security_token_redirectOnErr('/admin/plugins', 'admin_themes', 't');
1273
1274                         // Toggle plugin status
1275                         $idx = array_search($plugin, $a->plugins);
1276                         if ($idx !== false){
1277                                 unset($a->plugins[$idx]);
1278                                 uninstall_plugin($plugin);
1279                                 info( sprintf( t("Plugin %s disabled."), $plugin ) );
1280                         } else {
1281                                 $a->plugins[] = $plugin;
1282                                 install_plugin($plugin);
1283                                 info( sprintf( t("Plugin %s enabled."), $plugin ) );
1284                         }
1285                         set_config("system","addon", implode(", ",$a->plugins));
1286                         goaway($a->get_baseurl(true) . '/admin/plugins' );
1287                         return ''; // NOTREACHED
1288                 }
1289                 // display plugin details
1290                 require_once('library/markdown.php');
1291
1292                 if (in_array($plugin, $a->plugins)){
1293                         $status="on"; $action= t("Disable");
1294                 } else {
1295                         $status="off"; $action= t("Enable");
1296                 }
1297
1298                 $readme=Null;
1299                 if (is_file("addon/$plugin/README.md")){
1300                         $readme = file_get_contents("addon/$plugin/README.md");
1301                         $readme = Markdown($readme);
1302                 } else if (is_file("addon/$plugin/README")){
1303                         $readme = "<pre>". file_get_contents("addon/$plugin/README") ."</pre>";
1304                 }
1305
1306                 $admin_form="";
1307                 if (is_array($a->plugins_admin) && in_array($plugin, $a->plugins_admin)){
1308                         @require_once("addon/$plugin/$plugin.php");
1309                         $func = $plugin.'_plugin_admin';
1310                         $func($a, $admin_form);
1311                 }
1312
1313                 $t = get_markup_template("admin_plugins_details.tpl");
1314
1315                 return replace_macros($t, array(
1316                         '$title' => t('Administration'),
1317                         '$page' => t('Plugins'),
1318                         '$toggle' => t('Toggle'),
1319                         '$settings' => t('Settings'),
1320                         '$baseurl' => $a->get_baseurl(true),
1321
1322                         '$plugin' => $plugin,
1323                         '$status' => $status,
1324                         '$action' => $action,
1325                         '$info' => get_plugin_info($plugin),
1326                         '$str_author' => t('Author: '),
1327                         '$str_maintainer' => t('Maintainer: '),
1328
1329                         '$admin_form' => $admin_form,
1330                         '$function' => 'plugins',
1331                         '$screenshot' => '',
1332                         '$readme' => $readme,
1333
1334                         '$form_security_token' => get_form_security_token("admin_themes"),
1335                 ));
1336         }
1337
1338
1339
1340         /**
1341          * List plugins
1342          */
1343
1344         if (x($_GET,"a") && $_GET['a']=="r"){
1345                 check_form_security_token_redirectOnErr($a->get_baseurl().'/admin/plugins', 'admin_themes', 't');
1346                 reload_plugins();
1347                 info("Plugins reloaded");
1348                 goaway($a->get_baseurl().'/admin/plugins');
1349         }
1350
1351         $plugins = array();
1352         $files = glob("addon/*/"); /* */
1353         if($files) {
1354                 foreach($files as $file) {
1355                         if (is_dir($file)){
1356                                 list($tmp, $id)=array_map("trim", explode("/",$file));
1357                                 $info = get_plugin_info($id);
1358                                 $show_plugin = true;
1359
1360                                 // If the addon is unsupported, then only show it, when it is enabled
1361                                 if ((strtolower($info["status"]) == "unsupported") AND !in_array($id,  $a->plugins))
1362                                         $show_plugin = false;
1363
1364                                 // Override the above szenario, when the admin really wants to see outdated stuff
1365                                 if (get_config("system", "show_unsupported_addons"))
1366                                         $show_plugin = true;
1367
1368                                 if ($show_plugin)
1369                                         $plugins[] = array($id, (in_array($id,  $a->plugins)?"on":"off") , $info);
1370                         }
1371                 }
1372         }
1373
1374         $t = get_markup_template("admin_plugins.tpl");
1375         return replace_macros($t, array(
1376                 '$title' => t('Administration'),
1377                 '$page' => t('Plugins'),
1378                 '$submit' => t('Save Settings'),
1379                 '$reload' => t('Reload active plugins'),
1380                 '$baseurl' => $a->get_baseurl(true),
1381                 '$function' => 'plugins',
1382                 '$plugins' => $plugins,
1383                 '$form_security_token' => get_form_security_token("admin_themes"),
1384         ));
1385 }
1386
1387 /**
1388  * @param array $themes
1389  * @param string $th
1390  * @param int $result
1391  */
1392 function toggle_theme(&$themes,$th,&$result) {
1393         for($x = 0; $x < count($themes); $x ++) {
1394                 if($themes[$x]['name'] === $th) {
1395                         if($themes[$x]['allowed']) {
1396                                 $themes[$x]['allowed'] = 0;
1397                                 $result = 0;
1398                         }
1399                         else {
1400                                 $themes[$x]['allowed'] = 1;
1401                                 $result = 1;
1402                         }
1403                 }
1404         }
1405 }
1406
1407 /**
1408  * @param array $themes
1409  * @param string $th
1410  * @return int
1411  */
1412 function theme_status($themes,$th) {
1413         for($x = 0; $x < count($themes); $x ++) {
1414                 if($themes[$x]['name'] === $th) {
1415                         if($themes[$x]['allowed']) {
1416                                 return 1;
1417                         }
1418                         else {
1419                                 return 0;
1420                         }
1421                 }
1422         }
1423         return 0;
1424 }
1425
1426
1427 /**
1428  * @param array $themes
1429  * @return string
1430  */
1431 function rebuild_theme_table($themes) {
1432         $o = '';
1433         if(count($themes)) {
1434                 foreach($themes as $th) {
1435                         if($th['allowed']) {
1436                                 if(strlen($o))
1437                                         $o .= ',';
1438                                 $o .= $th['name'];
1439                         }
1440                 }
1441         }
1442         return $o;
1443 }
1444
1445
1446 /**
1447  * Themes admin page
1448  *
1449  * @param App $a
1450  * @return string
1451  */
1452 function admin_page_themes(&$a){
1453
1454         $allowed_themes_str = get_config('system','allowed_themes');
1455         $allowed_themes_raw = explode(',',$allowed_themes_str);
1456         $allowed_themes = array();
1457         if(count($allowed_themes_raw))
1458                 foreach($allowed_themes_raw as $x)
1459                         if(strlen(trim($x)))
1460                                 $allowed_themes[] = trim($x);
1461
1462         $themes = array();
1463         $files = glob('view/theme/*'); /* */
1464         if($files) {
1465                 foreach($files as $file) {
1466                         $f = basename($file);
1467                         $is_experimental = intval(file_exists($file . '/experimental'));
1468                         $is_supported = 1-(intval(file_exists($file . '/unsupported')));
1469                         $is_allowed = intval(in_array($f,$allowed_themes));
1470
1471                         if ($is_allowed OR $is_supported OR get_config("system", "show_unsupported_themes"))
1472                                 $themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed);
1473                 }
1474         }
1475
1476         if(! count($themes)) {
1477                 notice( t('No themes found.'));
1478                 return '';
1479         }
1480
1481         /**
1482          * Single theme
1483          */
1484
1485         if ($a->argc == 3){
1486                 $theme = $a->argv[2];
1487                 if(! is_dir("view/theme/$theme")){
1488                         notice( t("Item not found.") );
1489                         return '';
1490                 }
1491
1492                 if (x($_GET,"a") && $_GET['a']=="t"){
1493                         check_form_security_token_redirectOnErr('/admin/themes', 'admin_themes', 't');
1494
1495                         // Toggle theme status
1496
1497                         toggle_theme($themes,$theme,$result);
1498                         $s = rebuild_theme_table($themes);
1499                         if($result) {
1500                                 install_theme($theme);
1501                                 info( sprintf('Theme %s enabled.',$theme));
1502                         }
1503                         else {
1504                                 uninstall_theme($theme);
1505                                 info( sprintf('Theme %s disabled.',$theme));
1506                         }
1507
1508                         set_config('system','allowed_themes',$s);
1509                         goaway($a->get_baseurl(true) . '/admin/themes' );
1510                         return ''; // NOTREACHED
1511                 }
1512
1513                 // display theme details
1514                 require_once('library/markdown.php');
1515
1516                 if (theme_status($themes,$theme)) {
1517                         $status="on"; $action= t("Disable");
1518                 } else {
1519                         $status="off"; $action= t("Enable");
1520                 }
1521
1522                 $readme=Null;
1523                 if (is_file("view/theme/$theme/README.md")){
1524                         $readme = file_get_contents("view/theme/$theme/README.md");
1525                         $readme = Markdown($readme);
1526                 } else if (is_file("view/theme/$theme/README")){
1527                         $readme = "<pre>". file_get_contents("view/theme/$theme/README") ."</pre>";
1528                 }
1529
1530                 $admin_form="";
1531                 if (is_file("view/theme/$theme/config.php")){
1532                         function __get_theme_admin_form(&$a, $theme) {
1533                                 $orig_theme = $a->theme;
1534                                 $orig_page = $a->page;
1535                                 $orig_session_theme = $_SESSION['theme'];
1536                                 require_once("view/theme/$theme/theme.php");
1537                                 require_once("view/theme/$theme/config.php");
1538                                 $_SESSION['theme'] = $theme;
1539
1540
1541                                 $init = $theme."_init";
1542                                 if(function_exists($init)) $init($a);
1543                                 if(function_exists("theme_admin")){
1544                                         $admin_form = theme_admin($a);
1545                                 }
1546
1547                                 $_SESSION['theme'] = $orig_session_theme;
1548                                 $a->theme = $orig_theme;
1549                                 $a->page = $orig_page;
1550                                 return $admin_form;
1551                         }
1552                         $admin_form = __get_theme_admin_form($a, $theme);
1553                 }
1554
1555                 $screenshot = array( get_theme_screenshot($theme), t('Screenshot'));
1556                 if(! stristr($screenshot[0],$theme))
1557                         $screenshot = null;
1558
1559                 $t = get_markup_template("admin_plugins_details.tpl");
1560                 return replace_macros($t, array(
1561                         '$title' => t('Administration'),
1562                         '$page' => t('Themes'),
1563                         '$toggle' => t('Toggle'),
1564                         '$settings' => t('Settings'),
1565                         '$baseurl' => $a->get_baseurl(true),
1566
1567                         '$plugin' => $theme,
1568                         '$status' => $status,
1569                         '$action' => $action,
1570                         '$info' => get_theme_info($theme),
1571                         '$function' => 'themes',
1572                         '$admin_form' => $admin_form,
1573                         '$str_author' => t('Author: '),
1574                         '$str_maintainer' => t('Maintainer: '),
1575                         '$screenshot' => $screenshot,
1576                         '$readme' => $readme,
1577
1578                         '$form_security_token' => get_form_security_token("admin_themes"),
1579                 ));
1580         }
1581
1582
1583         // reload active themes
1584         if (x($_GET,"a") && $_GET['a']=="r"){
1585                 check_form_security_token_redirectOnErr($a->get_baseurl().'/admin/themes', 'admin_themes', 't');
1586                 if ($themes) {
1587                         foreach($themes as $th) {
1588                                 if ($th['allowed']) {
1589                                         uninstall_theme($th['name']);
1590                                         install_theme($th['name']);
1591                                 }
1592                         }
1593                 }
1594                 info("Themes reloaded");
1595                 goaway($a->get_baseurl().'/admin/themes');
1596         }
1597
1598         /**
1599          * List themes
1600          */
1601
1602         $xthemes = array();
1603         if($themes) {
1604                 foreach($themes as $th) {
1605                         $xthemes[] = array($th['name'],(($th['allowed']) ? "on" : "off"), get_theme_info($th['name']));
1606                 }
1607         }
1608
1609
1610         $t = get_markup_template("admin_plugins.tpl");
1611         return replace_macros($t, array(
1612                 '$title' => t('Administration'),
1613                 '$page' => t('Themes'),
1614                 '$submit' => t('Save Settings'),
1615                 '$reload' => t('Reload active themes'),
1616                 '$baseurl' => $a->get_baseurl(true),
1617                 '$function' => 'themes',
1618                 '$plugins' => $xthemes,
1619                 '$experimental' => t('[Experimental]'),
1620                 '$unsupported' => t('[Unsupported]'),
1621                 '$form_security_token' => get_form_security_token("admin_themes"),
1622         ));
1623 }
1624
1625
1626 /**
1627  * Logs admin page
1628  *
1629  * @param App $a
1630  */
1631
1632 function admin_page_logs_post(&$a) {
1633         if (x($_POST,"page_logs")) {
1634                 check_form_security_token_redirectOnErr('/admin/logs', 'admin_logs');
1635
1636                 $logfile                =       ((x($_POST,'logfile'))          ? notags(trim($_POST['logfile']))       : '');
1637                 $debugging              =       ((x($_POST,'debugging'))        ? true                                                          : false);
1638                 $loglevel               =       ((x($_POST,'loglevel'))         ? intval(trim($_POST['loglevel']))      : 0);
1639
1640                 set_config('system','logfile', $logfile);
1641                 set_config('system','debugging',  $debugging);
1642                 set_config('system','loglevel', $loglevel);
1643
1644
1645         }
1646
1647         info( t("Log settings updated.") );
1648         goaway($a->get_baseurl(true) . '/admin/logs' );
1649         return; // NOTREACHED
1650 }
1651
1652 /**
1653  * @param App $a
1654  * @return string
1655  */
1656 function admin_page_logs(&$a){
1657
1658         $log_choices = Array(
1659                 LOGGER_NORMAL => 'Normal',
1660                 LOGGER_TRACE => 'Trace',
1661                 LOGGER_DEBUG => 'Debug',
1662                 LOGGER_DATA => 'Data',
1663                 LOGGER_ALL => 'All'
1664         );
1665
1666         $t = get_markup_template("admin_logs.tpl");
1667
1668         $f = get_config('system','logfile');
1669
1670         $data = '';
1671
1672         if(!file_exists($f)) {
1673                 $data = t("Error trying to open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f exist and is
1674 readable.");
1675         }
1676         else {
1677                 $fp = fopen($f, 'r');
1678                 if(!$fp) {
1679                         $data = t("Couldn't open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f is readable.");
1680                 }
1681                 else {
1682                         $fstat = fstat($fp);
1683                         $size = $fstat['size'];
1684                         if($size != 0)
1685                         {
1686                                 if($size > 5000000 || $size < 0)
1687                                         $size = 5000000;
1688                                 $seek = fseek($fp,0-$size,SEEK_END);
1689                                 if($seek === 0) {
1690                                         $data = escape_tags(fread($fp,$size));
1691                                         while(! feof($fp))
1692                                                 $data .= escape_tags(fread($fp,4096));
1693                                 }
1694                         }
1695                         fclose($fp);
1696                 }
1697         }
1698
1699         return replace_macros($t, array(
1700                 '$title' => t('Administration'),
1701                 '$page' => t('Logs'),
1702                 '$submit' => t('Save Settings'),
1703                 '$clear' => t('Clear'),
1704                 '$data' => $data,
1705                 '$baseurl' => $a->get_baseurl(true),
1706                 '$logname' =>  get_config('system','logfile'),
1707
1708                                                                         // name, label, value, help string, extra data...
1709                 '$debugging'            => array('debugging', t("Enable Debugging"),get_config('system','debugging'), ""),
1710                 '$logfile'                      => array('logfile', t("Log file"), get_config('system','logfile'), t("Must be writable by web server. Relative to your Friendica top-level directory.")),
1711                 '$loglevel'             => array('loglevel', t("Log level"), get_config('system','loglevel'), "", $log_choices),
1712
1713                 '$form_security_token' => get_form_security_token("admin_logs"),
1714         ));
1715 }
1716
1717 /**
1718  * @param App $a
1719  */
1720 function admin_page_remoteupdate_post(&$a) {
1721         // this function should be called via ajax post
1722         if(!is_site_admin()) {
1723                 return;
1724         }
1725
1726
1727         if (x($_POST,'remotefile') && $_POST['remotefile']!=""){
1728                 $remotefile = $_POST['remotefile'];
1729                 $ftpdata = (x($_POST['ftphost'])?$_POST:false);
1730                 doUpdate($remotefile, $ftpdata);
1731         } else {
1732                 echo "No remote file to download. Abort!";
1733         }
1734
1735         killme();
1736 }
1737
1738 /**
1739  * @param App $a
1740  * @return string
1741  */
1742 function admin_page_remoteupdate(&$a) {
1743         if(!is_site_admin()) {
1744                 return login(false);
1745         }
1746
1747         $canwrite = canWeWrite();
1748         $canftp = function_exists('ftp_connect');
1749
1750         $needupdate = true;
1751         $u = checkUpdate();
1752         if (!is_array($u)){
1753                 $needupdate = false;
1754                 $u = array('','','');
1755         }
1756
1757         $tpl = get_markup_template("admin_remoteupdate.tpl");
1758         return replace_macros($tpl, array(
1759                 '$baseurl' => $a->get_baseurl(true),
1760                 '$submit' => t("Update now"),
1761                 '$close' => t("Close"),
1762                 '$localversion' => FRIENDICA_VERSION,
1763                 '$remoteversion' => $u[1],
1764                 '$needupdate' => $needupdate,
1765                 '$canwrite' => $canwrite,
1766                 '$canftp'       => $canftp,
1767                 '$ftphost'      => array('ftphost', t("FTP Host"), '',''),
1768                 '$ftppath'      => array('ftppath', t("FTP Path"), '/',''),
1769                 '$ftpuser'      => array('ftpuser', t("FTP User"), '',''),
1770                 '$ftppwd'       => array('ftppwd', t("FTP Password"), '',''),
1771                 '$remotefile'=>array('remotefile','', $u['2'],''),
1772         ));
1773
1774 }