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