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