]> git.mxchange.org Git - friendica.git/blob - mod/admin.php
implement max load average before queuing/deferring delivery and poller processes
[friendica.git] / mod / admin.php
1 <?php
2
3  /**
4   * Friendica admin
5   */
6 require_once("include/remoteupdate.php");
7
8
9 /**
10  * @param App $a
11  */
12 function admin_post(&$a){
13
14
15         if(!is_site_admin()) {
16                 return;
17         }
18
19         // do not allow a page manager to access the admin panel at all.
20
21         if(x($_SESSION,'submanage') && intval($_SESSION['submanage']))
22                 return;
23         
24
25
26         // urls
27         if ($a->argc > 1){
28                 switch ($a->argv[1]){
29                         case 'site':
30                                 admin_page_site_post($a);
31                                 break;
32                         case 'users':
33                                 admin_page_users_post($a);
34                                 break;
35                         case 'plugins':
36                                 if ($a->argc > 2 && 
37                                         is_file("addon/".$a->argv[2]."/".$a->argv[2].".php")){
38                                                 @include_once("addon/".$a->argv[2]."/".$a->argv[2].".php");
39                                                 if(function_exists($a->argv[2].'_plugin_admin_post')) {
40                                                         $func = $a->argv[2].'_plugin_admin_post';
41                                                         $func($a);
42                                                 }
43                                 }
44                                 goaway($a->get_baseurl(true) . '/admin/plugins/' . $a->argv[2] );
45                                 return; // NOTREACHED
46                                 break;
47                         case 'themes':
48                                 $theme = $a->argv[2];
49                                 if (is_file("view/theme/$theme/config.php")){
50                                         require_once("view/theme/$theme/config.php");
51                                         if (function_exists("theme_admin_post")){
52                                                 theme_admin_post($a);
53                                         }
54                                 }
55                                 info(t('Theme settings updated.'));
56                                 if(is_ajax()) return;
57                                 
58                                 goaway($a->get_baseurl(true) . '/admin/themes/' . $theme );
59                                 return;
60                                 break;
61                         case 'logs':
62                                 admin_page_logs_post($a);
63                                 break;
64                         case 'dbsync':
65                                 admin_page_dbsync_post($a);
66                                 break;
67                         case 'update':
68                                 admin_page_remoteupdate_post($a);
69                                 break;
70                 }
71         }
72
73         goaway($a->get_baseurl(true) . '/admin' );
74         return; // NOTREACHED   
75 }
76
77 /**
78  * @param App $a
79  * @return string
80  */
81 function admin_content(&$a) {
82
83         if(!is_site_admin()) {
84                 return login(false);
85         }
86
87         if(x($_SESSION,'submanage') && intval($_SESSION['submanage']))
88                 return "";
89
90         /**
91          * Side bar links
92          */
93
94         // array( url, name, extra css classes )
95         $aside = Array(
96                 'site'   =>     Array($a->get_baseurl(true)."/admin/site/", t("Site") , "site"),
97                 'users'  =>     Array($a->get_baseurl(true)."/admin/users/", t("Users") , "users"),
98                 'plugins'=>     Array($a->get_baseurl(true)."/admin/plugins/", t("Plugins") , "plugins"),
99                 'themes' =>     Array($a->get_baseurl(true)."/admin/themes/", t("Themes") , "themes"),
100                 'dbsync' => Array($a->get_baseurl(true)."/admin/dbsync/", t('DB updates'), "dbsync"),
101                 'update' =>     Array($a->get_baseurl(true)."/admin/update/", t("Software Update") , "update")
102         );
103         
104         /* get plugins admin page */
105         
106         $r = q("SELECT * FROM `addon` WHERE `plugin_admin`=1");
107         $aside['plugins_admin']=Array();
108         foreach ($r as $h){
109                 $plugin =$h['name'];
110                 $aside['plugins_admin'][] = Array($a->get_baseurl(true)."/admin/plugins/".$plugin, $plugin, "plugin");
111                 // temp plugins with admin
112                 $a->plugins_admin[] = $plugin;
113         }
114                 
115         $aside['logs'] = Array($a->get_baseurl(true)."/admin/logs/", t("Logs"), "logs");
116
117         $t = get_markup_template("admin_aside.tpl");
118         $a->page['aside'] = replace_macros( $t, array(
119                         '$admin' => $aside, 
120                         '$h_pending' => t('User registrations waiting for confirmation'),
121                         '$admurl'=> $a->get_baseurl(true)."/admin/"
122         ));
123
124
125
126         /**
127          * Page content
128          */
129         $o = '';
130         
131         // urls
132         if ($a->argc > 1){
133                 switch ($a->argv[1]){
134                         case 'site':
135                                 $o = admin_page_site($a);
136                                 break;
137                         case 'users':
138                                 $o = admin_page_users($a);
139                                 break;
140                         case 'plugins':
141                                 $o = admin_page_plugins($a);
142                                 break;
143                         case 'themes':
144                                 $o = admin_page_themes($a);
145                                 break;
146                         case 'logs':
147                                 $o = admin_page_logs($a);
148                                 break;
149                         case 'dbsync':
150                                 $o = admin_page_dbsync($a);
151                                 break;
152                         case 'update':
153                                 $o = admin_page_remoteupdate($a);
154                                 break;
155                         default:
156                                 notice( t("Item not found.") );
157                 }
158         } else {
159                 $o = admin_page_summary($a);
160         }
161         
162         if(is_ajax()) {
163                 echo $o; 
164                 killme();
165                 return '';
166         } else {
167                 return $o;
168         }
169
170
171
172 /**
173  * Admin Summary Page
174  * @param App $a
175  * @return string
176  */
177 function admin_page_summary(&$a) {
178         $r = q("SELECT `page-flags`, COUNT(uid) as `count` FROM `user` GROUP BY `page-flags`");
179         $accounts = Array(
180                 Array( t('Normal Account'), 0),
181                 Array( t('Soapbox Account'), 0),
182                 Array( t('Community/Celebrity Account'), 0),
183                 Array( t('Automatic Friend Account'), 0)
184         );
185         $users=0;
186         foreach ($r as $u){ $accounts[$u['page-flags']][1] = $u['count']; $users+= $u['count']; }
187
188         logger('accounts: ' . print_r($accounts,true));
189
190         $r = q("SELECT COUNT(id) as `count` FROM `register`");
191         $pending = $r[0]['count'];
192                 
193         $t = get_markup_template("admin_summary.tpl");
194         return replace_macros($t, array(
195                 '$title' => t('Administration'),
196                 '$page' => t('Summary'),
197                 '$users' => Array( t('Registered users'), $users),
198                 '$accounts' => $accounts,
199                 '$pending' => Array( t('Pending registrations'), $pending),
200                 '$version' => Array( t('Version'), FRIENDICA_VERSION),
201                 '$build' =>  get_config('system','build'),
202                 '$plugins' => Array( t('Active plugins'), $a->plugins )
203         ));
204 }
205
206
207 /**
208  * Admin Site Page
209  *  @param App $a
210  */
211 function admin_page_site_post(&$a){
212         if (!x($_POST,"page_site")){
213                 return;
214         }
215
216     check_form_security_token_redirectOnErr('/admin/site', 'admin_site');
217
218         $sitename                       =       ((x($_POST,'sitename'))                 ? notags(trim($_POST['sitename']))                      : '');
219         $banner                         =       ((x($_POST,'banner'))                   ? trim($_POST['banner'])                                        : false);
220         $language                       =       ((x($_POST,'language'))                 ? notags(trim($_POST['language']))                      : '');
221         $theme                          =       ((x($_POST,'theme'))                    ? notags(trim($_POST['theme']))                         : '');
222         $maximagesize           =       ((x($_POST,'maximagesize'))             ? intval(trim($_POST['maximagesize']))          :  0);
223         
224         
225         $register_policy        =       ((x($_POST,'register_policy'))  ? intval(trim($_POST['register_policy']))       :  0);
226         $abandon_days       =   ((x($_POST,'abandon_days'))         ? intval(trim($_POST['abandon_days']))          :  0);
227
228         $register_text          =       ((x($_POST,'register_text'))    ? notags(trim($_POST['register_text']))         : '');  
229         
230         $allowed_sites          =       ((x($_POST,'allowed_sites'))    ? notags(trim($_POST['allowed_sites']))         : '');
231         $allowed_email          =       ((x($_POST,'allowed_email'))    ? notags(trim($_POST['allowed_email']))         : '');
232         $block_public           =       ((x($_POST,'block_public'))             ? True  :       False);
233         $force_publish          =       ((x($_POST,'publish_all'))              ? True  :       False);
234         $global_directory       =       ((x($_POST,'directory_submit_url'))     ? notags(trim($_POST['directory_submit_url']))  : '');
235         $no_multi_reg           =       ((x($_POST,'no_multi_reg'))             ? True  :       False);
236         $no_openid                      =       !((x($_POST,'no_openid'))               ? True  :       False);
237         $no_regfullname         =       !((x($_POST,'no_regfullname'))  ? True  :       False);
238         $no_utf                         =       !((x($_POST,'no_utf'))                  ? True  :       False);
239         $no_community_page      =       !((x($_POST,'no_community_page'))       ? True  :       False);
240
241         $verifyssl                      =       ((x($_POST,'verifyssl'))                ? True  :       False);
242         $proxyuser                      =       ((x($_POST,'proxyuser'))                ? notags(trim($_POST['proxyuser']))     : '');
243         $proxy                          =       ((x($_POST,'proxy'))                    ? notags(trim($_POST['proxy'])) : '');
244         $timeout                        =       ((x($_POST,'timeout'))                  ? intval(trim($_POST['timeout']))               : 60);
245         $delivery_interval      =       ((x($_POST,'delivery_interval'))? intval(trim($_POST['delivery_interval']))             : 0);
246         $maxloadavg             =       ((x($_POST,'maxloadavg'))       ? intval(trim($_POST['maxloadavg']))            : 50);
247         $dfrn_only          =   ((x($_POST,'dfrn_only'))            ? True      :       False);
248         $ostatus_disabled   =   !((x($_POST,'ostatus_disabled')) ? True  :   False);
249         $diaspora_enabled   =   ((x($_POST,'diaspora_enabled')) ? True   :  False);
250         $ssl_policy         =   ((x($_POST,'ssl_policy')) ? intval($_POST['ssl_policy']) : 0);
251
252         if($ssl_policy != intval(get_config('system','ssl_policy'))) {
253                 if($ssl_policy == SSL_POLICY_FULL) {
254                         q("update `contact` set 
255                                 `url`     = replace(`url`    , 'http:' , 'https:'),
256                                 `photo`   = replace(`photo`  , 'http:' , 'https:'),
257                                 `thumb`   = replace(`thumb`  , 'http:' , 'https:'),
258                                 `micro`   = replace(`micro`  , 'http:' , 'https:'),
259                                 `request` = replace(`request`, 'http:' , 'https:'),
260                                 `notify`  = replace(`notify` , 'http:' , 'https:'),
261                                 `poll`    = replace(`poll`   , 'http:' , 'https:'),
262                                 `confirm` = replace(`confirm`, 'http:' , 'https:'),
263                                 `poco`    = replace(`poco`   , 'http:' , 'https:')
264                                 where `self` = 1"
265                         );
266                         q("update `profile` set 
267                                 `photo`   = replace(`photo`  , 'http:' , 'https:'),
268                                 `thumb`   = replace(`thumb`  , 'http:' , 'https:')
269                                 where 1 "
270                         );
271                 }
272                 elseif($ssl_policy == SSL_POLICY_SELFSIGN) {
273                         q("update `contact` set 
274                                 `url`     = replace(`url`    , 'https:' , 'http:'),
275                                 `photo`   = replace(`photo`  , 'https:' , 'http:'),
276                                 `thumb`   = replace(`thumb`  , 'https:' , 'http:'),
277                                 `micro`   = replace(`micro`  , 'https:' , 'http:'),
278                                 `request` = replace(`request`, 'https:' , 'http:'),
279                                 `notify`  = replace(`notify` , 'https:' , 'http:'),
280                                 `poll`    = replace(`poll`   , 'https:' , 'http:'),
281                                 `confirm` = replace(`confirm`, 'https:' , 'http:'),
282                                 `poco`    = replace(`poco`   , 'https:' , 'http:')
283                                 where `self` = 1"
284                         );
285                         q("update `profile` set 
286                                 `photo`   = replace(`photo`  , 'https:' , 'http:'),
287                                 `thumb`   = replace(`thumb`  , 'https:' , 'http:')
288                                 where 1 "
289                         );
290                 }
291         }
292         set_config('system','ssl_policy',$ssl_policy);
293         set_config('system','delivery_interval',$delivery_interval);
294         set_config('system','maxloadavg',$maxloadavg);
295         set_config('config','sitename',$sitename);
296         if ($banner==""){
297                 // don't know why, but del_config doesn't work...
298                 q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
299                         dbesc("system"),
300                         dbesc("banner")
301                 );
302         } else {
303                 set_config('system','banner', $banner);
304         }
305         set_config('system','language', $language);
306         set_config('system','theme', $theme);
307         set_config('system','maximagesize', $maximagesize);
308         
309         set_config('config','register_policy', $register_policy);
310         set_config('system','account_abandon_days', $abandon_days);
311         set_config('config','register_text', $register_text);
312         set_config('system','allowed_sites', $allowed_sites);
313         set_config('system','allowed_email', $allowed_email);
314         set_config('system','block_public', $block_public);
315         set_config('system','publish_all', $force_publish);
316         if ($global_directory==""){
317                 // don't know why, but del_config doesn't work...
318                 q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
319                         dbesc("system"),
320                         dbesc("directory_submit_url")
321                 );
322         } else {
323                 set_config('system','directory_submit_url', $global_directory);
324         }
325
326         set_config('system','block_extended_register', $no_multi_reg);
327         set_config('system','no_openid', $no_openid);
328         set_config('system','no_regfullname', $no_regfullname);
329         set_config('system','no_community_page', $no_community_page);
330         set_config('system','no_utf', $no_utf);
331         set_config('system','verifyssl', $verifyssl);
332         set_config('system','proxyuser', $proxyuser);
333         set_config('system','proxy', $proxy);
334         set_config('system','curl_timeout', $timeout);
335         set_config('system','dfrn_only', $dfrn_only);
336         set_config('system','ostatus_disabled', $ostatus_disabled);
337         set_config('system','diaspora_enabled', $diaspora_enabled);
338
339         info( t('Site settings updated.') . EOL);
340         goaway($a->get_baseurl(true) . '/admin/site' );
341         return; // NOTREACHED   
342         
343 }
344
345 /**
346  * @param  App $a
347  * @return string
348  */
349 function admin_page_site(&$a) {
350         
351         /* Installed langs */
352         $lang_choices = array();
353         $langs = glob('view/*/strings.php');
354         
355         if(is_array($langs) && count($langs)) {
356                 if(! in_array('view/en/strings.php',$langs))
357                         $langs[] = 'view/en/';
358                 asort($langs);
359                 foreach($langs as $l) {
360                         $t = explode("/",$l);
361                         $lang_choices[$t[1]] = $t[1];
362                 }
363         }
364         
365         /* Installed themes */
366         $theme_choices = array();
367         $files = glob('view/theme/*');
368         if($files) {
369                 foreach($files as $file) {
370                         $f = basename($file);
371                         $theme_name = ((file_exists($file . '/experimental')) ?  sprintf("%s - \x28Experimental\x29", $f) : $f);
372                         $theme_choices[$f] = $theme_name;
373                 }
374         }
375         
376         
377         /* Banner */
378         $banner = get_config('system','banner');
379         if($banner == false) 
380                 $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>';
381         $banner = htmlspecialchars($banner);
382         
383         //echo "<pre>"; var_dump($lang_choices); die("</pre>");
384
385         /* Register policy */
386         $register_choices = Array(
387                 REGISTER_CLOSED => t("Closed"),
388                 REGISTER_APPROVE => t("Requires approval"),
389                 REGISTER_OPEN => t("Open")
390         ); 
391
392         $ssl_choices = array(
393                 SSL_POLICY_NONE => t("No SSL policy, links will track page SSL state"),
394                 SSL_POLICY_FULL => t("Force all links to use SSL"),
395                 SSL_POLICY_SELFSIGN => t("Self-signed certificate, use SSL for local links only (discouraged)")
396         );
397
398         $t = get_markup_template("admin_site.tpl");
399         return replace_macros($t, array(
400                 '$title' => t('Administration'),
401                 '$page' => t('Site'),
402                 '$submit' => t('Submit'),
403                 '$registration' => t('Registration'),
404                 '$upload' => t('File upload'),
405                 '$corporate' => t('Policies'),
406                 '$advanced' => t('Advanced'),
407                 
408                 '$baseurl' => $a->get_baseurl(true),
409                                                                         // name, label, value, help string, extra data...
410                 '$sitename'             => array('sitename', t("Site name"), htmlentities($a->config['sitename'], ENT_QUOTES), ""),
411                 '$banner'                       => array('banner', t("Banner/Logo"), $banner, ""),
412                 '$language'             => array('language', t("System language"), get_config('system','language'), "", $lang_choices),
413                 '$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),
414                 '$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),
415                 '$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.")),
416
417                 '$register_policy'      => array('register_policy', t("Register policy"), $a->config['register_policy'], "", $register_choices),
418                 '$register_text'        => array('register_text', t("Register text"), htmlentities($a->config['register_text'], ENT_QUOTES), t("Will be displayed prominently on the registration page.")),
419                 '$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.')),
420                 '$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")),
421                 '$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")),
422                 '$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.")),
423                 '$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.")),
424                 '$global_directory'     => array('directory_submit_url', t("Global directory update URL"), get_config('system','directory_submit_url'), t("URL to update the global directory. If this is not set, the global directory is completely unavailable to the application.")),
425                         
426                 '$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.")),
427                 '$no_openid'            => array('no_openid', t("OpenID support"), !get_config('system','no_openid'), t("OpenID support for registration and logins.")),
428                 '$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")),
429                 '$no_utf'                       => array('no_utf', t("UTF-8 Regular expressions"), !get_config('system','no_utf'), t("Use PHP UTF8 regular expressions")),
430                 '$no_community_page' => array('no_community_page', t("Show Community Page"), !get_config('system','no_community_page'), t("Display a Community page showing all recent public postings on this site.")),
431                 '$ostatus_disabled' => array('ostatus_disabled', t("Enable OStatus support"), !get_config('system','ostatus_disable'), t("Provide built-in OStatus \x28identi.ca, status.net, etc.\x29 compatibility. All communications in OStatus are public, so privacy warnings will be occasionally displayed.")), 
432                 '$diaspora_enabled' => array('diaspora_enabled', t("Enable Diaspora support"), get_config('system','diaspora_enabled'), t("Provide built-in Diaspora network compatibility.")), 
433                 '$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.")),
434                 '$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.")),
435                 '$proxyuser'            => array('proxyuser', t("Proxy user"), get_config('system','proxyuser'), ""),
436                 '$proxy'                        => array('proxy', t("Proxy URL"), get_config('system','proxy'), ""),
437                 '$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).")),
438                 '$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.")),
439                 '$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.")),
440         '$form_security_token' => get_form_security_token("admin_site"),
441                         
442         ));
443
444 }
445
446
447 function admin_page_dbsync(&$a) {
448
449         $o = '';
450
451         if($a->argc > 3 && intval($a->argv[3]) && $a->argv[2] === 'mark') {
452                 set_config('database', 'update_' . intval($a->argv[3]), 'success');
453                 info( t('Update has been marked successful') . EOL);
454                 goaway($a->get_baseurl(true) . '/admin/dbsync');
455         }
456
457         if($a->argc > 2 && intval($a->argv[2])) {
458                 require_once('update.php');
459                 $func = 'update_' . intval($a->argv[2]);
460                 if(function_exists($func)) {
461                         $retval = $func();
462                         if($retval === UPDATE_FAILED) {
463                                 $o .= sprintf( t('Executing %s failed. Check system logs.'), $func); 
464                         }
465                         elseif($retval === UPDATE_SUCCESS) {
466                                 $o .= sprintf( t('Update %s was successfully applied.', $func));
467                                 set_config('database',$func, 'success');
468                         }
469                         else
470                                 $o .= sprintf( t('Update %s did not return a status. Unknown if it succeeded.'), $func);
471                 }
472                 else
473                         $o .= sprintf( t('Update function %s could not be found.'), $func);
474                 return $o;
475         }
476
477         $failed = array();
478         $r = q("select * from config where `cat` = 'database' ");
479         if(count($r)) {
480                 foreach($r as $rr) {
481                         $upd = intval(substr($rr['k'],7));
482                         if($upd < 1139 || $rr['v'] === 'success')
483                                 continue;
484                         $failed[] = $upd;
485                 }
486         }
487         if(! count($failed))
488                 return '<h3>' . t('No failed updates.') . '</h3>';
489
490         $o = replace_macros(get_markup_template('failed_updates.tpl'),array(
491                 '$base' => $a->get_baseurl(true),
492                 '$banner' => t('Failed Updates'),
493                 '$desc' => t('This does not include updates prior to 1139, which did not return a status.'),
494                 '$mark' => t('Mark success (if update was manually applied)'),
495                 '$apply' => t('Attempt to execute this update step automatically'),
496                 '$failed' => $failed
497         ));     
498
499         return $o;
500
501 }
502
503 /**
504  * Users admin page
505  *
506  * @param App $a
507  */
508 function admin_page_users_post(&$a){
509         $pending = ( x($_POST, 'pending') ? $_POST['pending'] : Array() );
510         $users = ( x($_POST, 'user') ? $_POST['user'] : Array() );
511
512     check_form_security_token_redirectOnErr('/admin/users', 'admin_users');
513
514         if (x($_POST,'page_users_block')){
515                 foreach($users as $uid){
516                         q("UPDATE `user` SET `blocked`=1-`blocked` WHERE `uid`=%s",
517                                 intval( $uid )
518                         );
519                 }
520                 notice( sprintf( tt("%s user blocked/unblocked", "%s users blocked/unblocked", count($users)), count($users)) );
521         }
522         if (x($_POST,'page_users_delete')){
523                 require_once("include/Contact.php");
524                 foreach($users as $uid){
525                         user_remove($uid);
526                 }
527                 notice( sprintf( tt("%s user deleted", "%s users deleted", count($users)), count($users)) );
528         }
529         
530         if (x($_POST,'page_users_approve')){
531                 require_once("mod/regmod.php");
532                 foreach($pending as $hash){
533                         user_allow($hash);
534                 }
535         }
536         if (x($_POST,'page_users_deny')){
537                 require_once("mod/regmod.php");
538                 foreach($pending as $hash){
539                         user_deny($hash);
540                 }
541         }
542         goaway($a->get_baseurl(true) . '/admin/users' );
543         return; // NOTREACHED   
544 }
545
546 /**
547  * @param App $a
548  * @return string
549  */
550 function admin_page_users(&$a){
551         if ($a->argc>2) {
552                 $uid = $a->argv[3];
553                 $user = q("SELECT * FROM `user` WHERE `uid`=%d", intval($uid));
554                 if (count($user)==0){
555                         notice( 'User not found' . EOL);
556                         goaway($a->get_baseurl(true) . '/admin/users' );
557                         return ''; // NOTREACHED
558                 }               
559                 switch($a->argv[2]){
560                         case "delete":{
561                 check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
562                                 // delete user
563                                 require_once("include/Contact.php");
564                                 user_remove($uid);
565                                 
566                                 notice( sprintf(t("User '%s' deleted"), $user[0]['username']) . EOL);
567                         }; break;
568                         case "block":{
569                 check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't');
570                                 q("UPDATE `user` SET `blocked`=%d WHERE `uid`=%s",
571                                         intval( 1-$user[0]['blocked'] ),
572                                         intval( $uid )
573                                 );
574                                 notice( sprintf( ($user[0]['blocked']?t("User '%s' unblocked"):t("User '%s' blocked")) , $user[0]['username']) . EOL);
575                         }; break;
576                 }
577                 goaway($a->get_baseurl(true) . '/admin/users' );
578                 return ''; // NOTREACHED
579                 
580         }
581         
582         /* get pending */
583         $pending = q("SELECT `register`.*, `contact`.`name`, `user`.`email`
584                                  FROM `register`
585                                  LEFT JOIN `contact` ON `register`.`uid` = `contact`.`uid`
586                                  LEFT JOIN `user` ON `register`.`uid` = `user`.`uid`;");
587         
588         
589         /* get users */
590
591         $total = q("SELECT count(*) as total FROM `user` where 1");
592         if(count($total)) {
593                 $a->set_pager_total($total[0]['total']);
594                 $a->set_pager_itemspage(100);
595         }
596         
597         
598         $users = q("SELECT `user` . * , `contact`.`name` , `contact`.`url` , `contact`.`micro`, `lastitem`.`lastitem_date`
599                                 FROM
600                                         (SELECT MAX(`item`.`changed`) as `lastitem_date`, `item`.`uid`
601                                         FROM `item`
602                                         WHERE `item`.`type` = 'wall'
603                                         GROUP BY `item`.`uid`) AS `lastitem`
604                                                  RIGHT OUTER JOIN `user` ON `user`.`uid` = `lastitem`.`uid`,
605                                            `contact`
606                                 WHERE
607                                            `user`.`uid` = `contact`.`uid`
608                                                 AND `user`.`verified` =1
609                                         AND `contact`.`self` =1
610                                 ORDER BY `contact`.`name` LIMIT %d, %d
611                                 ",
612                                 intval($a->pager['start']),
613                                 intval($a->pager['itemspage'])
614                                 );
615                                         
616         function _setup_users($e){
617                 $accounts = Array(
618                         t('Normal Account'), 
619                         t('Soapbox Account'),
620                         t('Community/Celebrity Account'),
621                         t('Automatic Friend Account')
622                 );
623                 $e['page-flags'] = $accounts[$e['page-flags']];
624                 $e['register_date'] = relative_date($e['register_date']);
625                 $e['login_date'] = relative_date($e['login_date']);
626                 $e['lastitem_date'] = relative_date($e['lastitem_date']);
627                 return $e;
628         }
629         $users = array_map("_setup_users", $users);
630         
631         
632         $t = get_markup_template("admin_users.tpl");
633         $o = replace_macros($t, array(
634                 // strings //
635                 '$title' => t('Administration'),
636                 '$page' => t('Users'),
637                 '$submit' => t('Submit'),
638                 '$select_all' => t('select all'),
639                 '$h_pending' => t('User registrations waiting for confirm'),
640                 '$th_pending' => array( t('Request date'), t('Name'), t('Email') ),
641                 '$no_pending' =>  t('No registrations.'),
642                 '$approve' => t('Approve'),
643                 '$deny' => t('Deny'),
644                 '$delete' => t('Delete'),
645                 '$block' => t('Block'),
646                 '$unblock' => t('Unblock'),
647                 
648                 '$h_users' => t('Users'),
649                 '$th_users' => array( t('Name'), t('Email'), t('Register date'), t('Last login'), t('Last item'),  t('Account') ),
650
651                 '$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?'),
652                 '$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?'),
653
654         '$form_security_token' => get_form_security_token("admin_users"),
655
656                 // values //
657                 '$baseurl' => $a->get_baseurl(true),
658
659                 '$pending' => $pending,
660                 '$users' => $users,
661         ));
662         $o .= paginate($a);
663         return $o;
664 }
665
666
667 /**
668  * Plugins admin page
669  *
670  * @param App $a
671  * @return string
672  */
673 function admin_page_plugins(&$a){
674         
675         /**
676          * Single plugin
677          */
678         if ($a->argc == 3){
679                 $plugin = $a->argv[2];
680                 if (!is_file("addon/$plugin/$plugin.php")){
681                         notice( t("Item not found.") );
682                         return '';
683                 }
684                 
685                 if (x($_GET,"a") && $_GET['a']=="t"){
686             check_form_security_token_redirectOnErr('/admin/plugins', 'admin_themes', 't');
687
688                         // Toggle plugin status
689                         $idx = array_search($plugin, $a->plugins);
690                         if ($idx !== false){
691                                 unset($a->plugins[$idx]);
692                                 uninstall_plugin($plugin);
693                                 info( sprintf( t("Plugin %s disabled."), $plugin ) );
694                         } else {
695                                 $a->plugins[] = $plugin;
696                                 install_plugin($plugin);
697                                 info( sprintf( t("Plugin %s enabled."), $plugin ) );
698                         }
699                         set_config("system","addon", implode(", ",$a->plugins));
700                         goaway($a->get_baseurl(true) . '/admin/plugins' );
701                         return ''; // NOTREACHED
702                 }
703                 // display plugin details
704                 require_once('library/markdown.php');
705
706                 if (in_array($plugin, $a->plugins)){
707                         $status="on"; $action= t("Disable");
708                 } else {
709                         $status="off"; $action= t("Enable");
710                 }
711                 
712                 $readme=Null;
713                 if (is_file("addon/$plugin/README.md")){
714                         $readme = file_get_contents("addon/$plugin/README.md");
715                         $readme = Markdown($readme);
716                 } else if (is_file("addon/$plugin/README")){
717                         $readme = "<pre>". file_get_contents("addon/$plugin/README") ."</pre>";
718                 } 
719                 
720                 $admin_form="";
721                 if (is_array($a->plugins_admin) && in_array($plugin, $a->plugins_admin)){
722                         @require_once("addon/$plugin/$plugin.php");
723                         $func = $plugin.'_plugin_admin';
724                         $func($a, $admin_form);
725                 }
726                 
727                 $t = get_markup_template("admin_plugins_details.tpl");
728                 return replace_macros($t, array(
729                         '$title' => t('Administration'),
730                         '$page' => t('Plugins'),
731                         '$toggle' => t('Toggle'),
732                         '$settings' => t('Settings'),
733                         '$baseurl' => $a->get_baseurl(true),
734                 
735                         '$plugin' => $plugin,
736                         '$status' => $status,
737                         '$action' => $action,
738                         '$info' => get_plugin_info($plugin),
739                         '$str_author' => t('Author: '),
740                         '$str_maintainer' => t('Maintainer: '),                 
741                 
742                         '$admin_form' => $admin_form,
743                         '$function' => 'plugins',
744                         '$screenshot' => '',
745                         '$readme' => $readme,
746
747             '$form_security_token' => get_form_security_token("admin_themes"),
748                 ));
749         } 
750          
751          
752         
753         /**
754          * List plugins
755          */
756         
757         $plugins = array();
758         $files = glob("addon/*/");
759         if($files) {
760                 foreach($files as $file) {      
761                         if (is_dir($file)){
762                                 list($tmp, $id)=array_map("trim", explode("/",$file));
763                                 $info = get_plugin_info($id);
764                                 $plugins[] = array( $id, (in_array($id,  $a->plugins)?"on":"off") , $info);
765                         }
766                 }
767         }
768         
769         $t = get_markup_template("admin_plugins.tpl");
770         return replace_macros($t, array(
771                 '$title' => t('Administration'),
772                 '$page' => t('Plugins'),
773                 '$submit' => t('Submit'),
774                 '$baseurl' => $a->get_baseurl(true),
775                 '$function' => 'plugins',       
776                 '$plugins' => $plugins,
777         '$form_security_token' => get_form_security_token("admin_themes"),
778         ));
779 }
780
781 /**
782  * @param array $themes
783  * @param string $th
784  * @param int $result
785  */
786 function toggle_theme(&$themes,$th,&$result) {
787         for($x = 0; $x < count($themes); $x ++) {
788                 if($themes[$x]['name'] === $th) {
789                         if($themes[$x]['allowed']) {
790                                 $themes[$x]['allowed'] = 0;
791                                 $result = 0;
792                         }
793                         else {
794                                 $themes[$x]['allowed'] = 1;
795                                 $result = 1;
796                         }
797                 }
798         }
799 }
800
801 /**
802  * @param array $themes
803  * @param string $th
804  * @return int
805  */
806 function theme_status($themes,$th) {
807         for($x = 0; $x < count($themes); $x ++) {
808                 if($themes[$x]['name'] === $th) {
809                         if($themes[$x]['allowed']) {
810                                 return 1;
811                         }
812                         else {
813                                 return 0;
814                         }
815                 }
816         }
817         return 0;
818 }
819
820
821 /**
822  * @param array $themes
823  * @return string
824  */
825 function rebuild_theme_table($themes) {
826         $o = '';
827         if(count($themes)) {
828                 foreach($themes as $th) {
829                         if($th['allowed']) {
830                                 if(strlen($o))
831                                         $o .= ',';
832                                 $o .= $th['name'];
833                         }
834                 }
835         }
836         return $o;
837 }
838
839         
840 /**
841  * Themes admin page
842  *
843  * @param App $a
844  * @return string
845  */
846 function admin_page_themes(&$a){
847         
848         $allowed_themes_str = get_config('system','allowed_themes');
849         $allowed_themes_raw = explode(',',$allowed_themes_str);
850         $allowed_themes = array();
851         if(count($allowed_themes_raw))
852                 foreach($allowed_themes_raw as $x)
853                         if(strlen(trim($x)))
854                                 $allowed_themes[] = trim($x);
855
856         $themes = array();
857     $files = glob('view/theme/*');
858     if($files) {
859         foreach($files as $file) {
860             $f = basename($file);
861             $is_experimental = intval(file_exists($file . '/experimental'));
862                         $is_supported = 1-(intval(file_exists($file . '/unsupported'))); // Is not used yet
863                         $is_allowed = intval(in_array($f,$allowed_themes));
864                         $themes[] = array('name' => $f, 'experimental' => $is_experimental, 'supported' => $is_supported, 'allowed' => $is_allowed);
865         }
866     }
867
868         if(! count($themes)) {
869                 notice( t('No themes found.'));
870                 return '';
871         }
872
873         /**
874          * Single theme
875          */
876
877         if ($a->argc == 3){
878                 $theme = $a->argv[2];
879                 if(! is_dir("view/theme/$theme")){
880                         notice( t("Item not found.") );
881                         return '';
882                 }
883                 
884                 if (x($_GET,"a") && $_GET['a']=="t"){
885             check_form_security_token_redirectOnErr('/admin/themes', 'admin_themes', 't');
886
887                         // Toggle theme status
888
889                         toggle_theme($themes,$theme,$result);
890                         $s = rebuild_theme_table($themes);
891                         if($result)
892                                 info( sprintf('Theme %s enabled.',$theme));
893                         else
894                                 info( sprintf('Theme %s disabled.',$theme));
895
896                         set_config('system','allowed_themes',$s);
897                         goaway($a->get_baseurl(true) . '/admin/themes' );
898                         return ''; // NOTREACHED
899                 }
900
901                 // display theme details
902                 require_once('library/markdown.php');
903
904                 if (theme_status($themes,$theme)) {
905                         $status="on"; $action= t("Disable");
906                 } else {
907                         $status="off"; $action= t("Enable");
908                 }
909                 
910                 $readme=Null;
911                 if (is_file("view/theme/$theme/README.md")){
912                         $readme = file_get_contents("view/theme/$theme/README.md");
913                         $readme = Markdown($readme);
914                 } else if (is_file("view/theme/$theme/README")){
915                         $readme = "<pre>". file_get_contents("view/theme/$theme/README") ."</pre>";
916                 } 
917                 
918                 $admin_form="";
919                 if (is_file("view/theme/$theme/config.php")){
920                         require_once("view/theme/$theme/config.php");
921                         if(function_exists("theme_admin")){
922                                 $admin_form = theme_admin($a);
923                         }
924                         
925                 }
926                 
927
928                 $screenshot = array( get_theme_screenshot($theme), t('Screenshot'));
929                 if(! stristr($screenshot[0],$theme))
930                         $screenshot = null;             
931
932                 $t = get_markup_template("admin_plugins_details.tpl");
933                 return replace_macros($t, array(
934                         '$title' => t('Administration'),
935                         '$page' => t('Themes'),
936                         '$toggle' => t('Toggle'),
937                         '$settings' => t('Settings'),
938                         '$baseurl' => $a->get_baseurl(true),
939                 
940                         '$plugin' => $theme,
941                         '$status' => $status,
942                         '$action' => $action,
943                         '$info' => get_theme_info($theme),
944                         '$function' => 'themes',
945                         '$admin_form' => $admin_form,
946                         '$str_author' => t('Author: '),
947                         '$str_maintainer' => t('Maintainer: '),
948                         '$screenshot' => $screenshot,
949                         '$readme' => $readme,
950
951                         '$form_security_token' => get_form_security_token("admin_themes"),
952                 ));
953         } 
954          
955          
956         
957         /**
958          * List themes
959          */
960         
961         $xthemes = array();
962         if($themes) {
963                 foreach($themes as $th) {
964                         $xthemes[] = array($th['name'],(($th['allowed']) ? "on" : "off"), get_theme_info($th['name']));
965                 }
966         }
967         
968         $t = get_markup_template("admin_plugins.tpl");
969         return replace_macros($t, array(
970                 '$title' => t('Administration'),
971                 '$page' => t('Themes'),
972                 '$submit' => t('Submit'),
973                 '$baseurl' => $a->get_baseurl(true),
974                 '$function' => 'themes',
975                 '$plugins' => $xthemes,
976                 '$experimental' => t('[Experimental]'),
977                 '$unsupported' => t('[Unsupported]'),
978         '$form_security_token' => get_form_security_token("admin_themes"),
979         ));
980 }
981
982
983 /**
984  * Logs admin page
985  *
986  * @param App $a
987  */
988  
989 function admin_page_logs_post(&$a) {
990         if (x($_POST,"page_logs")) {
991         check_form_security_token_redirectOnErr('/admin/logs', 'admin_logs');
992
993                 $logfile                =       ((x($_POST,'logfile'))          ? notags(trim($_POST['logfile']))       : '');
994                 $debugging              =       ((x($_POST,'debugging'))        ? true                                                          : false);
995                 $loglevel               =       ((x($_POST,'loglevel'))         ? intval(trim($_POST['loglevel']))      : 0);
996
997                 set_config('system','logfile', $logfile);
998                 set_config('system','debugging',  $debugging);
999                 set_config('system','loglevel', $loglevel);
1000
1001                 
1002         }
1003
1004         info( t("Log settings updated.") );
1005         goaway($a->get_baseurl(true) . '/admin/logs' );
1006         return; // NOTREACHED   
1007 }
1008
1009 /**
1010  * @param App $a
1011  * @return string
1012  */
1013 function admin_page_logs(&$a){
1014         
1015         $log_choices = Array(
1016                 LOGGER_NORMAL => 'Normal',
1017                 LOGGER_TRACE => 'Trace',
1018                 LOGGER_DEBUG => 'Debug',
1019                 LOGGER_DATA => 'Data',
1020                 LOGGER_ALL => 'All'
1021         );
1022         
1023         $t = get_markup_template("admin_logs.tpl");
1024
1025         $f = get_config('system','logfile');
1026
1027         $data = '';
1028
1029         if(!file_exists($f)) {
1030                 $data = t("Error trying to open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f exist and is 
1031 readable.");
1032         }
1033         else {
1034                 $fp = fopen($f, 'r');
1035                 if(!$fp) {
1036                         $data = t("Couldn't open <strong>$f</strong> log file.\r\n<br/>Check to see if file $f is readable.");
1037                 }
1038                 else {
1039                         $fstat = fstat($fp);
1040                         $size = $fstat['size'];
1041                         if($size != 0)
1042                         {
1043                                 if($size > 5000000 || $size < 0)
1044                                         $size = 5000000;
1045                                 $seek = fseek($fp,0-$size,SEEK_END);
1046                                 if($seek === 0) {
1047                                         $data = escape_tags(fread($fp,$size));
1048                                         while(! feof($fp))
1049                                                 $data .= escape_tags(fread($fp,4096));
1050                                 }
1051                         }
1052                         fclose($fp);
1053                 }
1054         }                       
1055
1056         return replace_macros($t, array(
1057                 '$title' => t('Administration'),
1058                 '$page' => t('Logs'),
1059                 '$submit' => t('Submit'),
1060                 '$clear' => t('Clear'),
1061                 '$data' => $data,
1062                 '$baseurl' => $a->get_baseurl(true),
1063                 '$logname' =>  get_config('system','logfile'),
1064                 
1065                                                                         // name, label, value, help string, extra data...
1066                 '$debugging'            => array('debugging', t("Debugging"),get_config('system','debugging'), ""),
1067                 '$logfile'                      => array('logfile', t("Log file"), get_config('system','logfile'), t("Must be writable by web server. Relative to your Friendica top-level directory.")),
1068                 '$loglevel'             => array('loglevel', t("Log level"), get_config('system','loglevel'), "", $log_choices),
1069
1070         '$form_security_token' => get_form_security_token("admin_logs"),
1071         ));
1072 }
1073
1074 /**
1075  * @param App $a
1076  */
1077 function admin_page_remoteupdate_post(&$a) {
1078         // this function should be called via ajax post
1079         if(!is_site_admin()) {
1080                 return;
1081         }
1082
1083         
1084         if (x($_POST,'remotefile') && $_POST['remotefile']!=""){
1085                 $remotefile = $_POST['remotefile'];
1086                 $ftpdata = (x($_POST['ftphost'])?$_POST:false);
1087                 doUpdate($remotefile, $ftpdata);
1088         } else {
1089                 echo "No remote file to download. Abort!";
1090         }
1091
1092         killme();
1093 }
1094
1095 /**
1096  * @param App $a
1097  * @return string
1098  */
1099 function admin_page_remoteupdate(&$a) {
1100         if(!is_site_admin()) {
1101                 return login(false);
1102         }
1103
1104         $canwrite = canWeWrite();
1105         $canftp = function_exists('ftp_connect');
1106         
1107         $needupdate = true;
1108         $u = checkUpdate();
1109         if (!is_array($u)){
1110                 $needupdate = false;
1111                 $u = array('','','');
1112         }
1113         
1114         $tpl = get_markup_template("admin_remoteupdate.tpl");
1115         return replace_macros($tpl, array(
1116                 '$baseurl' => $a->get_baseurl(true),
1117                 '$submit' => t("Update now"),
1118                 '$close' => t("Close"),
1119                 '$localversion' => FRIENDICA_VERSION,
1120                 '$remoteversion' => $u[1],
1121                 '$needupdate' => $needupdate,
1122                 '$canwrite' => $canwrite,
1123                 '$canftp'       => $canftp,
1124                 '$ftphost'      => array('ftphost', t("FTP Host"), '',''),
1125                 '$ftppath'      => array('ftppath', t("FTP Path"), '/',''),
1126                 '$ftpuser'      => array('ftpuser', t("FTP User"), '',''),
1127                 '$ftppwd'       => array('ftppwd', t("FTP Password"), '',''),
1128                 '$remotefile'=>array('remotefile','', $u['2'],'')
1129         ));
1130         
1131 }