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