* @param string op2 - step 2 action name
 * @param boolean select_one - if requesting page saves 1 or multiple user(group) ID values. Default is 0, page saves multiple values.
 * @param string paste2box - opener input box name where to send result ID value
 * @param string pastename2box - opener input box name where to send result NAME value
 * @param string show_checkboxes = 0/1, if we need to select multiple groups, put here 1. Default is 0
 * 
 */
global $site;
$class_path = "../classes/";
include $class_path . "port.inc.php";
include $class_path . "adminpage.inc.php";
include $class_path . "user_html.inc.php";
$site = new Site(array(on_debug => $_COOKIE["debug"] ? 1 : 0, on_admin_keel => 1));
$op = $site->fdat['op'];
$op2 = $site->fdat['op2'];
$site->fdat['group_id'] = (int) ($site->fdat['group_id'] ? $site->fdat['group_id'] : get_topparent_group(array("site" => $site)));
#################
# GET GROUP INFO
if ($site->fdat['group_id']) {
    $group = new Group(array(group_id => $site->fdat[group_id]));
    $breadcrumb_focus_str = ",'" . $group->all['name'] . "'";
}
/*
 * SAVE bookmark
*/
if ($site->fdat['bookmark'] == 1) {
    if (is_numeric($site->fdat['user_id']) && is_numeric($site->fdat['group_id'])) {
        $site->user->toggle_favorite(array(user_id => $site->fdat['user_id']));
    } else {
        if (is_numeric($site->fdat['group_id'])) {
            $site->user->toggle_favorite(array(group_id => $site->fdat['group_id']));
/**
 * show object permission rows
 *
 * Shows all objected permissions: user/group name + CRUPD matrix + subtree checkbox
 * Allows to add new user/group as new permission row and delete rows
 * NB! Used some global variables (doesn't have to be this way later... only for development convienence now)
 * 
 * @param string type - permission type (OBJ/ADMIN/ACL/..)
 *
 * Call:
 *		edit_permissions(array(
 *			"type" => 'OBJ'	
 *		));
 */
function edit_permissions ($args) {
	global $site;
	global $objekt;
	global $class_path;
	global $keel;

	$db_permissions = array();
	$existing_users = array();
	$existing_groups = array();
	$selected_users = array();
	$selected_groups = array();
	$crud = array();

	# if objekt is not created (probably error situation), try to create it again
	if(!$objekt->objekt_id){
		$objekt = new Objekt(array(
			objekt_id => $site->fdat['id']
		));
	}

	$everybody_group_id = get_topparent_group(array("site" => $site));

	# default permission set
	if($args['permissions']){ $crud = split(",",$args['permissions']); }
	else { $crud = split(",","C,R,U,P,D,S"); }
	$crudnames = array(
		"C"=>"Create", 
		"R"=>"Read",
		"U"=>"Update",
		"P"=>"Publish",
		"D"=>"Delete",
		"S"=>"",
	);

	if($args['type']) {


##################
# HTML
?>
<SCRIPT LANGUAGE="JavaScript"><!--

function sanity_check(obj,acl,type,id){
//	alert(obj.checked+type+id);
	// rule 1: !R => !C & !U & !P & !D
	if(type=='R' && !obj.checked) {
		if(document.getElementById(acl+"_C_"+id)) { document.getElementById(acl+"_C_"+id).checked=false; }
		if(document.getElementById(acl+"_U_"+id)) { document.getElementById(acl+"_U_"+id).checked=false; }
		if(document.getElementById(acl+"_P_"+id)){ document.getElementById(acl+"_P_"+id).checked=false; }
		if(document.getElementById(acl+"_D_"+id)) { document.getElementById(acl+"_D_"+id).checked=false; }
	}
	// rule 2: C || U || P || D => R
	if(type=='C' && obj.checked || 
		type=='U' && obj.checked || 
		type=='P' && obj.checked || 
		type=='D' && obj.checked) {
		document.getElementById(acl+"_R_"+id).checked=true;
	}
}
function get_copypermissions_url(acl,id){
	var crud = '';
	if(document.getElementById(acl+"_C_"+id)) { 
		if(document.getElementById(acl+"_C_"+id).checked) { crud = crud + '1'; } else { crud = crud + '0'; }
	}
	if(document.getElementById(acl+"_R_"+id)) { 
		if(document.getElementById(acl+"_R_"+id).checked) { crud = crud + '1'; } else { crud = crud + '0'; }
	}
	if(document.getElementById(acl+"_U_"+id)) { 
		if(document.getElementById(acl+"_U_"+id).checked) { crud = crud + '1'; } else { crud = crud + '0'; }
	}
	if(document.getElementById(acl+"_P_"+id)) { 
		if(document.getElementById(acl+"_P_"+id).checked) { crud = crud + '1'; } else { crud = crud + '0'; }
	}
	if(document.getElementById(acl+"_D_"+id)) { 
		if(document.getElementById(acl+"_D_"+id).checked) { crud = crud + '1'; } else { crud = crud + '0'; }
	}
	return crud;
}
-->
</script>
<?
	######## gather all fdat values into url string
	foreach($site->fdat as $fdat_field=>$fdat_value) { 
		if($fdat_field != 'id'){
			$url_parameters .= '&'.$fdat_field."=".$fdat_value;
#not used?			$hidden_parameters .= '<input type=hidden name="'.$fdat_field.'" value="'.$fdat_value.'">';
		} 
	} 

	######################
	# OBJECT PERMISSIONS

	$sql = $site->db->prepare("SELECT permissions.*, roles.name AS role_name, groups.name AS group_name, CONCAT(users.firstname,' ',users.lastname) AS user_name, groups.is_predefined AS predefined_group 
	FROM permissions 
		LEFT JOIN roles ON permissions.role_id=roles.role_id 
		LEFT JOIN groups ON permissions.group_id=groups.group_id
		LEFT JOIN users ON permissions.user_id=users.user_id 
	WHERE permissions.type=? AND permissions.source_id=?
	ORDER BY permissions.group_id DESC, permissions.user_id DESC, groups.name, users.firstname,users.lastname
		",
		$args['type'],
		$site->fdat['id']
	);
	$sth = new SQL($sql);
	$saved_permissions_found = $sth->rows ? true : false;

	$site->debug->msg($sth->debug->get_msgs());	
#print $sql;
	while ($permtmp = $sth->fetch()){
		$permtmp['is_role'] = $permtmp['role_id'] ? 1 : 0;
		$permtmp['is_group'] = $permtmp['group_id'] ? 1 : 0;
		$permtmp['name'] = $permtmp['role_id'] ? $permtmp['role_name'] : ($permtmp['group_id'] ? $permtmp['group_name'] : $permtmp['user_name']);


		$db_permissions[] = $permtmp;
		if($permtmp['user_id']) {
			$existing_users[] = $permtmp['user_id'];
		}
		if($permtmp['group_id']) {
			$existing_groups[] = $permtmp['group_id'];
		}
	}
	######################

	######################
	# HOME section permissions (sys_alias=home) will be default permissions through all website
	# get site permissions for everybody:
	$sql = $site->db->prepare("SELECT permissions.*, groups.name
	FROM permissions 
		LEFT JOIN groups ON permissions.group_id=groups.group_id
	WHERE permissions.type=? AND permissions.source_id=?
		",
		'OBJ',
		$site->alias("rub_home_id")
	);

	$sth = new SQL($sql);
	$home_permissions_found = $sth->rows ? true : false;
	$site->debug->msg($sth->debug->get_msgs());	
#print $sql;
	while ($permtmp = $sth->fetch()){
		$permtmp['is_group'] = $permtmp['group_id'] ? 1 : 0;

		$home_permissions[] = $permtmp;
		if($permtmp['group_id']) {
			$home_existing_groups[] = $permtmp['group_id'];
		}
	}
	# if for some reason home section doesn't have permissions
	# then use default mask: only Read permission (CRUPD=01000)
	if(!is_array($home_permissions)) {
		$home_permissions[] = array(
			id => '',
			type => 'OBJ',
			source_id => $site->alias("rub_home_id"),
			group_id => 1,
			user_id => '',
			C => 0,
			R => 1,
			U => 0,
			P => 0,
			D => 0,
			is_role => 0,
			is_group => 1,
			name => 'Everybody'
		);
	}
#printr($home_permissions);

	######################
	# TEMPORALLY SELECTED USERS & GROUPS PERMISSIONS
	# they are in the list but not in database yet
#echo printr($site->fdat['selected_groups']);
	if(trim($site->fdat['selected_users'])) {
		$selected_users = split(",",trim($site->fdat['selected_users']));
		$selected_users = array_unique($selected_users);

		### remove user from array if asked in url
		if( $site->fdat['remove_user_id'] ) {
			$key = array_search($site->fdat['remove_user_id'], $selected_users);  
			unset($selected_users[$key]);
		}
	}
	if(trim($site->fdat['selected_groups'])) {
		$selected_groups = split(",",trim($site->fdat['selected_groups']));
		$selected_groups = array_unique($selected_groups);
		### remove group from array if asked in url
		if( $site->fdat['remove_group_id'] ) {
			$key = array_search($site->fdat['remove_group_id'], $selected_groups);  
			unset($selected_groups[$key]);
		}
	}
#printr($selected_groups);
#printr($existing_groups);

	# add selected groups to permission list
	if(sizeof($selected_groups) > 0) {
		foreach($selected_groups as $group_id) {
			# if group not found in existing groups (in database) then add it
			if( !in_array($group_id,$existing_groups) ) {
				# get group info: to get group name
				$group = new Group(array(
					group_id => $group_id,
				));
				$permtmp = array();
				$permtmp['type'] = $args['type'];
				$permtmp['source_id'] = $site->fdat['id'];
				$permtmp['group_id'] = $group_id;
				$permtmp['is_group'] = 1;
				$permtmp['name'] = $group->name;
				# insert permission to the permissions array:
				$db_permissions[] = $permtmp;
			} # if group not found in existing groups
		} # foreach group id
	} # if selected_groups
	if(sizeof($selected_users) > 0) {
		foreach($selected_users as $user_id) {
			# if user not found in existing users (in database) then add it
			if( !in_array($user_id,$existing_users) ) {

				# get user info: to get user full name
				$user = new User(array(
					user_id => $user_id,
				));
				$permtmp = array();
				$permtmp['type'] = $args['type'];
				$permtmp['source_id'] = $site->fdat['id'];
				$permtmp['user_id'] = $user_id;
				$permtmp['is_group'] = 0;
				$permtmp['name'] = $user->all['firstname'].' '.$user->all['lastname'];

				# insert permission to the permissions array:
				$db_permissions[] = $permtmp;
			} # if user not found in existing users
		} # foreach user id
	} # if selected_users
	# / TEMPORALLY SELECTED USERS & GROUPS PERMISSIONS
	######################
#printr($db_permissions);
?>
  <tr> 
    <td valign="top" width="100%" class="scms_dialog_area" height="100%"> 
      <div class="scms_scrolltable_border"> 
        <div style="width:100%;" class="scms_scrolltable_header">
		   <table width="100%" cellpadding="0" cellspacing="0">
	<form name="frmEdit" action="<?=$site->self?>" method="POST">
	<input type=hidden name=tab value="<?=$site->fdat['tab']?>">
	<input type=hidden name=id value="<?=$site->fdat['id']?>">
	<input type=hidden name=keel value="<?=$site->fdat['keel']?>">
	<input type=hidden name=op value="<?=$site->fdat['op']?>">
	<input type=hidden name="callback" value="<?=$site->fdat['callback']?>">
	<input type=hidden name=op2 value="">
	<input type=hidden name=selected_users value="<?=join(',',$selected_users)?>">
	<input type=hidden name=selected_groups value="<?=join(',',$selected_groups)?>">
	
	<tr> 
              <td><?=$site->sys_sona(array(sona => "role", tyyp=>"kasutaja"))?> / <?=$site->sys_sona(array(sona => "group", tyyp=>"kasutaja"))?> / <?=$site->sys_sona(array(sona => "user", tyyp=>"kasutaja"))?></td>
			  <td align="right"><a href="javascript:void(openpopup('select_group.php','selectgroup','980','600'))"><?=$site->sys_sona(array(sona => "lisa", tyyp=>"editor"))?></a></td>
            </tr>
            <tr> 
              <td colspan="2" align="right" class="scms_scrolltable_header2" style="padding-right:30px"> 
                <table  border="0" cellspacing="0" cellpadding="3" class="scms_scrolltable_header2" >
				<?############## C R U P D S ###########?>
                  <tr> 
				  <? foreach($crud as $char) {?>
                    <td width="24" align="center"><?if($char!='S'){?><a href="#" title="<?=$crudnames[$char]?>"><?=$char?></a><?}?></td>
				  <?}?>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
        </div>
        <div id="scrolltableDiv" class="scms_scrolltable" style="height:290px"> 
          <table width="100%"  border="0" cellspacing="0" cellpadding="3">
<?	
####################
# 1. OBJECT PERMISSIONS saved into database (if found any)
#printr($db_permissions);
if(sizeof($db_permissions)>0) {

	foreach ($db_permissions as $key=>$perm){ 

		######### create remove link
		$remove_href = $site->self."?tab=".$site->fdat['tab']."&id=".$site->fdat['id'].$url_parameters;
		$remove_href .= sizeof($selected_users) > 0 ? "&selected_users=".join(',',$selected_users) : '';
		$remove_href .= sizeof($selected_groups) > 0 ? "&selected_groups=".join(',',$selected_groups) : '';
		$remove_href .=  "&remove_".($perm['is_group']?'group_id='.$perm['group_id']:'user_id='.$perm['user_id']);

		######### create copy link (permission data will be added later)
		$copy_href = $site->self."?tab=".$site->fdat['tab']."&id=".$site->fdat['id'].$url_parameters;

		######### dont print permission row if it's the removed
		if($perm['is_group'] && $perm['group_id'] == $site->fdat['remove_group_id'] || 
			!$perm['is_group'] && $perm['user_id'] == $site->fdat['remove_user_id']) 		{

			# goto next row
			continue;
		}
		########### print permission row
		else {

			print_permission_row(array(
				"perm" => $perm,
				"remove_href" => $remove_href,
				"copy_href" => $copy_href,
				"crud" => $crud
			));

		} # if not in remove list => print permission row
	} # foreach
}# if object permissions found	
# / 1. OBJECT PERMISSIONS saved into database (if found any)
####################

####################
# 2. HOME permissions row: when NO SAVED PERMISSIONS found in database
# - get permission values from default site values
# - dont allow to delete everybody row
#sizeof($db_permissions)==0
if(!$saved_permissions_found && ($args['type']=='OBJ' || $args['type']=='ACL') ){

	foreach ($home_permissions as $key=>$perm){ 
		######### create copy link (permission data will be added later)
		$copy_href = $site->self."?tab=".$site->fdat['tab']."&id=".$site->fdat['id'].$url_parameters;

		########### print permission row
		print_permission_row(array(
			"perm" => $perm,
			"remove_href" => $remove_href,
			"copy_href" => $copy_href,
			"crud" => $crud
		));
	} 
}
# / 2. HOME permissions 
####################
?>
			</table>
        </div></div>
    </td>
  </tr>
  <tr> 
    <td align="right" valign="top" class="scms_dialog_area_bottom"> 
     <input type="button" value="<?=$site->sys_sona(array(sona => "apply", tyyp=>"editor")) ?>" onclick="javascript:frmEdit.op2.value='save';this.form.submit();">
    <input type="button" value="<?=$site->sys_sona(array(sona => "Salvesta", tyyp=>"editor")) ?>" onclick="javascript:frmEdit.op2.value='saveclose';this.form.submit();">
	<input type="button" value="<?=$site->sys_sona(array(sona => "close", tyyp=>"editor")) ?>" onclick="javascript:window.close();"> 
    </td>
  </tr>

</form>
<?
	}  # if permission type provided
}
if (!$site->user->allowed_adminpage()) {
    exit;
}
######### get adminpage name
$adminpage_names = get_adminpage_name(array("script_name" => $site->script_name));
$parent_pagename = $adminpage_names['parent_pagename'];
$pagename = $adminpage_names['pagename'];
global $read_allowed_groups;
global $all_levels;
global $selected_parents;
global $column_count;
###########
# PERMISSIONS CHECK - get read-allowed group ID-s for current user
$read_allowed_groups = get_allowed_groups();
#echo printr($read_allowed_groups);
$top_group = get_topparent_group(array("site" => $site));
########### find user_id & group_id & role_id (what was selected in selectbox)
if ($site->fdat['selected_group']) {
    list($type, $sel_id) = split(":", $site->fdat['selected_group']);
    $site->fdat['user_id'] = $type == 'user_id' ? $sel_id : '';
    $site->fdat['group_id'] = $type == 'group_id' ? $sel_id : '';
    $site->fdat['role_id'] = $type == 'role_id' ? $sel_id : '';
    if ($type == 'user_id') {
        $site->fdat['group_id'] = get_my_group(array("who" => $site->fdat['selected_group']));
    }
} else {
    $site->fdat['selected_group'] = 'group_id:' . $site->fdat['group_id'];
}
#echo $site->fdat['selected_group']. " gr:".$site->fdat['group_id'];
########### find ALL GROUPS as TREE
# push all groups to level array
 function Site()
 {
     global $class_path;
     $args = func_get_arg(0);
     $this->args =& $args;
     $this->timer = new Timer();
     $this->cash = array();
     $this->rub_loetelu = array();
     $this->noaccess_hash = array();
     $this->fatal_error = '';
     $this->script_version = '4.7.FINAL';
     $this->site_poll_url = "http://extranet.saurus.ee/register/cms_site_polling.php";
     // auth is register:register
     ######################
     # this->fdat
     $this->fdat = array();
     $this->fdat = sizeof($_POST) > 0 ? $_POST : $_GET;
     ## set magic_quotes_gpc to OFF using transcribe() function
     $this->fdat = $this->transcribe($this->fdat);
     ######################
     # alternatiiv "?id" muutujale: t��tab ka "pg"
     $this->fdat['id'] = $this->fdat['id'] ? $this->fdat['id'] : $this->fdat['pg'];
     ######################
     # this->cookie
     $this->cookie = array();
     if (sizeof($_COOKIE) > 0) {
         while (list($name, $value) = each($_COOKIE)) {
             if (is_array($value)) {
                 while (list($arrname, $arrvalue) = each($value)) {
                     $this->cookie[$name][$arrname] = $arrvalue;
                 }
             } else {
                 $this->cookie[$name] = $value;
             }
         }
     }
     ######################
     # alias translation are in custom.inc.php
     $this->fdat['op'] = translate_ee($this->fdat['op']);
     if (isset($this->fdat['query'])) {
         $this->fdat['otsi'] =& $this->fdat['query'];
     }
     ######################
     # this->self: URL koos scriptinimega, nt /port/index.php
     # lets check if web server is Apache or not
     if (preg_match("/apache/i", $_SERVER["SERVER_SOFTWARE"]) || preg_match("/apache/i", $_SERVER["SERVER_SOFTWARE"])) {
         $this->self = $_SERVER["REQUEST_URI"];
         # kui apache
     } else {
         $this->self = $_SERVER["SCRIPT_NAME"];
         # kui muu (nt IIS)
     }
     #echo "<font color=red>test=".$this->self."</font></br>";
     #$this->self = "/index.php";
     $this->fullself = $this->self;
     # failinimi l�pust maha
     if (preg_match("/^[^\\?]*\\//", $this->self, $matches)) {
         $path = $matches[0];
     } else {
         $path = $this->self;
     }
     # slash l�ppu!
     if (!preg_match("/\\/\$/", $path)) {
         $path .= "/";
     }
     $this->self = $path;
     # this->self
     ######################
     ######################
     # find hostname & wwwroot from url
     #
     # this->hostname: serveri nimi, nt dino.saurus.ee
     # this->wwwroot: URL ilma scriptinimega, nt /port
     #    on t�histring kui saidil oma virtuaalhost ja dns-kirje.
     $this->wwwroot = $path;
     # v�ta l�pust "/extensions/<MY_EXTENSION_NAME>/admin/" maha kui on (Bug #2190)
     $this->wwwroot = preg_replace("/\\/extensions\\/(.*)\\/admin\\/\$/i", "", $this->wwwroot);
     # v�tame admin/ ja editor/ osa maha
     $re = '/' . preg_replace("/\\//", "\\\\/", '(editor|admin|classes|temp)/.*$') . '/i';
     $this->wwwroot = preg_replace($re, "", $this->wwwroot);
     # slash l�pust maha!
     $this->wwwroot = preg_replace("/\\/\$/", "", $this->wwwroot);
     # find hostname from url
     $this->hostname = $_SERVER["HTTP_HOST"];
     # / find hostname & this->wwwroot from url
     ####################
     ######################
     # $this->script_name - ainult scriptinimi, nt index.php. Bug #2690: $site->script_name leitakse valesti kui url-is esineb kaldkriips
     $this->script_name = $_SERVER["SCRIPT_NAME"];
     $break = explode('/', $this->script_name);
     $this->script_name = $break[count($break) - 1];
     # $this->script_name
     ######################
     # self = url + failinimi
     $this->self .= $this->script_name;
     ######################
     # $this->URI - $site->self + ? + $_SERVER["QUERY_STRING"], nt /port/index.php?id=666
     # Kui asi seotud aliastega, siis tyhjendame query_string:
     $ENV_QUERY_STRING = $_SERVER["QUERY_STRING"];
     # bug #791
     if (substr_count($ENV_QUERY_STRING, 'mod_rewrite') || substr_count($this->self, "/map/")) {
         $this->URI = $this->self;
         if (count($this->fdat > 1)) {
             $this->URI .= "?";
             foreach ($this->fdat as $key => $value) {
                 if ($value && $key != 'keel' && $key != 'mod_rewrite' && $key != 'cmd') {
                     $this->URI .= $key . "=" . $value . "&";
                 }
             }
         }
     } else {
         $this->URI = $this->self . ($ENV_QUERY_STRING ? "?" . $ENV_QUERY_STRING : "");
     }
     #$this->URI = $this->self."?".(substr_count($ENV_QUERY_STRING,'mod_rewrite') ? "":$ENV_QUERY_STRING);
     $this->safeURI = urlencode($this->URI);
     ######################
     # $this->absolute_path - absolute path of website root
     $this->absolute_path = getcwd() . '/';
     # l�pust /admin|editor|classes/ maha
     if (preg_match("/(.*)\\/(admin|editor|classes|temp)\\/\$/", $this->absolute_path, $matches) || preg_match("/(.*)\\\\(admin|editor|classes|temp)\\/\$/", $this->absolute_path, $matches)) {
         $this->absolute_path = $matches[1];
     }
     # slash l�ppu!
     if (!preg_match("/\\/\$/", $this->absolute_path)) {
         $this->absolute_path .= "/";
     }
     # windows compatible
     $this->absolute_path = str_replace('\\', '/', $this->absolute_path);
     ######################
     # $this->on_debug
     $this->on_debug = $args["on_debug"];
     $this->agent = 1;
     # defineerime debug classi s�ltuvalt selles,
     # kas on_debug = 1 v�i 0
     if ($this->on_debug) {
         include_once $class_path . "debug.inc.php";
     } else {
         include_once $class_path . "nodebug.inc.php";
     }
     $this->debug = new Debug();
     $this->editor_debug = new Debug();
     $this->debug->msg("Site->hostname: " . $this->hostname);
     $this->debug->msg("Site->wwwroot: " . $this->wwwroot);
     $this->debug->msg("Site->self: " . $this->self);
     $this->debug->msg("Site->script_name: " . $this->script_name);
     $this->debug->msg("Site->URI: " . $this->URI);
     ######################
     # $this->CONF: values from file 'config.php'
     $this->CONF = $this->ReadConf();
     $this->dbstyles = array();
     ######################
     # $this->db
     # andmebaasist s�ltumatu API
     include_once $class_path . $this->CONF["dbtype"] . ".inc.php";
     $this->db = new DB(array("host" => $this->CONF["dbhost"], "port" => $this->CONF["dbport"], "dbname" => $this->CONF["db"], "user" => $this->CONF["user"], "pass" => $this->CONF["passwd"], 'mysql_set_names' => $this->CONF["mysql_set_names"]));
     if ($this->db->error) {
         print "<font face=\"arial, verdana\" color=red>Error! Can't connect to database!</font>";
         exit;
     }
     # OMG, php OO sakib nii kohutavalt, seep???rast tuleb kasutada globaalset muutujat site instance-i k???tte saamiseks kui see pole veel l???puni valmis looddud. seda on vaja SQL classis.
     global $site;
     $site = $this;
     ######################
     # $this->CONF: merge values from file and database
     $this->CONF = array_merge($this->CONF, $this->ReadConfDB());
     ######################
     # hostname & wwwroot
     /* save old values */
     $this->db_hostname = $this->CONF['hostname'];
     $this->db_wwwroot = $this->CONF['wwwroot'];
     ## 1. CRON: if hostname is still empty => we may have cron-job running here,
     # in that case: get hostname and wwwroot from database conf variables (Bug #1903)
     if (trim($this->hostname) == '') {
         $this->hostname = $this->CONF['hostname'];
         $this->wwwroot = $this->CONF['wwwroot'];
     } else {
         # arvesta tegelikke v��rtuseid ja mitte andmebaasi kirjutatud v��rtuseid (Bug #1439):
         $this->CONF["hostname"] = $this->hostname;
         # Bug #2319. �rme kirjuta �le CONF['wwwroot'] v��rtust, sest aliaste puhul kui meil on nt URL
         # www.site.com/aliaste/rodu/ on suht v�imatu v�lja peilida, mis siis ikkagi on
         # TEGELIK wwwroot. Seep�rast kasutame andmebaasi v��rtust.
         # old: $this->CONF["wwwroot"] = $this->wwwroot;
         #$this->wwwroot = $this->CONF['wwwroot']; # new. no �kki peaks tegema
     }
     ######################
     # $this->img_path
     $this->img_path = $this->CONF["wwwroot"] . $this->CONF["img_path"];
     ######################
     # current version nr in database
     $sql = "SELECT version_nr FROM version ORDER BY release_date DESC LIMIT 1";
     $sth = new SQL($sql);
     $this->cms_version = $sth->fetchsingle();
     $this->debug->msg("Site CMS version: " . $this->cms_version);
     ######################
     # minimum (install) version nr in database
     $sql = "SELECT version_nr FROM version ORDER BY release_date ASC LIMIT 1";
     $sth = new SQL($sql);
     $this->cms_min_version = $sth->fetchsingle();
     $this->debug->msg("Site CMS minimum (install) version: " . $this->cms_min_version);
     ######################
     # current version nr in script
     $this->debug->msg("Site->script version: " . $this->script_version);
     ######################
     # lang/keel in URL
     $this->fdat['keel'] = isset($this->fdat['lang']) ? $this->fdat['lang'] : $this->fdat['keel'];
     # $this->keel
     # $this->encoding
     # $this->extension
     # $this->locale
     $tmp_arr = $this->get_keel(array("on_admin_keel" => $args["on_admin_keel"]));
     $this->keel = $tmp_arr['keel_id'];
     $this->encoding = $tmp_arr['encoding'];
     $this->extension = $tmp_arr['extension'];
     $this->locale = $tmp_arr['locale'];
     $this->glossary_id = $tmp_arr['glossary_id'];
     ############### aliases
     $this->load_aliases();
     $this->license = 'Saurus CMS Community Edition';
     $this->title = 'Saurus CMS Community Edition';
     ######################
     # $this->admin
     # "in_editor" on true juhul kui ollakse toimetaja keskkonnas:
     # kui URLis leidub editor/
     $pattern = "/^" . preg_replace("/\\//", "\\\\/", $this->CONF['wwwroot']) . "\\/(editor)\\//";
     if (preg_match($pattern, $this->URI)) {
         $this->in_editor = 1;
     } else {
         $this->in_editor = 0;
     }
     # "in_admin" on true juhul kui ollakse admin keskkonnas:
     # kui URLis leidub admin/
     $pattern = "/^" . preg_replace("/\\//", "\\\\/", $this->CONF['wwwroot']) . "\\/(admin)\\//";
     if (preg_match($pattern, $this->URI)) {
         $this->in_admin = 1;
     } else {
         $this->in_admin = 0;
     }
     # for compability with old ver 3: is_admin = treu if we are in admin/ or editor/ area
     if ($this->in_editor || $this->in_admin) {
         $this->admin = 1;
     } else {
         $this->admin = 0;
     }
     #################################################
     # force HTTPS for editor
     if ($this->in_editor && $this->CONF['force_https_for_editing'] && empty($_SERVER['HTTPS'])) {
         header('Location: https://' . $this->CONF['hostname'] . $this->CONF['wwwroot'] . '/editor/index.php');
         exit;
     }
     # / force HTTPS for editor
     #################################################
     #################################################
     # force HTTPS for admin
     if ($this->in_admin && $this->CONF['force_https_for_admin'] && empty($_SERVER['HTTPS'])) {
         header('Location: https://' . $this->CONF['hostname'] . $_SERVER['REQUEST_URI']);
         exit;
     }
     # / force HTTPS for editor
     #################################################
     $this->debug->msg("MC RUNTIME " . get_magic_quotes_runtime());
     $this->debug->msg("MC CONF " . get_magic_quotes_gpc());
     $this->debug->msg("Session id = " . session_id());
     #####################
     # $this->user
     $this->create_user();
     //$this->update_wwwroot();
     ##############################
     # get object classes
     $result = new SQL('select * from tyyp order by tyyp_id');
     while ($row = $result->fetch('ASSOC')) {
         $this->object_classes[$row['tyyp_id']] = $row;
         $this->object_tyyp_id_klass[$row['tyyp_id']] =& $this->object_classes[$row['tyyp_id']]['klass'];
         $this->object_tyyp_id_nimi[$row['tyyp_id']] =& $this->object_classes[$row['tyyp_id']]['nimi'];
     }
     # / get object classes
     ##############################
     #####################
     # global cookies (used through the site)
     # 1) save cookie
     if ($this->fdat['group_id']) {
         setcookie("scms_group_id", $this->fdat['group_id']);
     } else {
         $this->fdat['group_id'] = $_COOKIE["scms_group_id"];
     }
     # 3) if group_id is still empty then get  top parent group id (Everybody)
     if (!$this->fdat['group_id']) {
         $this->fdat['group_id'] = get_topparent_group(array("site" => $this));
     }
     # Kalendri kuup???eva "meelde j???tmine"
     if ($this->fdat['start_date'] && $this->fdat['end_date']) {
         $scms_calendar_date[] = "start_date=" . $this->fdat['start_date'] . "&end_date=" . $this->fdat['end_date'];
     }
     if ($this->fdat['week']) {
         $scms_calendar_date[] = "week=" . $this->fdat['week'];
     }
     if ($this->fdat['day'] && $this->fdat['month'] && $this->fdat['year']) {
         $scms_calendar_date[] = "day=" . $this->fdat['day'] . "&month=" . $this->fdat['month'] . "&year=" . $this->fdat['year'];
     }
     if (is_array($scms_calendar_date)) {
         $_COOKIE['scms_calendar_date'] = htmlentities(urlencode(join("&", $scms_calendar_date)));
         setcookie("scms_calendar_date", $_COOKIE['scms_calendar_date']);
     }
     # Get calendar date cookie
     if ($_COOKIE['scms_calendar_date']) {
         $calendar_date = urldecode($_COOKIE['scms_calendar_date']);
         $calendar_date = split("&", $calendar_date);
         foreach ($calendar_date as $value) {
             $result = split("=", $value);
             $cookie_calendar_date[$result[0]] = $result[1];
         }
     }
     if ($cookie_calendar_date && !$this->fdat['start_date'] && !$this->fdat['end_date']) {
         $this->fdat['start_date'] = $cookie_calendar_date['start_date'];
         $this->fdat['end_date'] = $cookie_calendar_date['end_date'];
     }
     if ($cookie_calendar_date && !$this->fdat['week']) {
         $this->fdat['week'] = $cookie_calendar_date['week'];
     }
     if ($cookie_calendar_date && !$this->fdat['day'] && !$this->fdat['month'] && !$this->fdat['year']) {
         $this->fdat['day'] = $cookie_calendar_date['day'];
         $this->fdat['month'] = $cookie_calendar_date['month'];
         $this->fdat['year'] = $cookie_calendar_date['year'];
     }
     # // Get calendar date cookie
     # / global cookies (used through the site)
     #####################
     #######################
     # leia saidi p???himallid - lehemall ja sisumall
     $this->get_master_tpl();
     # leitakse $this->master_tpl, $this->master_cont_tpl
     #######################
     # leia k???igi objektit??????pide p???himallid
     $this->get_objtype_tpl();
     # leitakse $this->objtype_tpl
 }
function print_users_toolbar(){

	global $site;
	global $class_path;
	
	global $group; # selected 1 group info
	global $user; # selected 1 user info

?>

  <!-- Toolbar -->
  <tr>
	<td class="scms_toolbar">
	<?
	################################
	# FUNCTION BAR TABLE
	?>
	<TABLE cellpadding=0 cellspacing=0 border=0>
	  <?
		############# detail buttons activity
		# when no group is selected then buttons are in inactive mode (non-clickable)
			if(!$site->fdat['group_id'] && !$site->fdat['user_id']) {
				$in_active = '_inactive';			
			} else {
				$in_active = '';			
			}
		  # popup window name
		  if($site->fdat['user_id']) {
			  $user_selected = 1;
			  $popup_href = $site->CONF['wwwroot'].$site->CONF['adm_path']."/edit_user.php?user_id=".$site->fdat['user_id']."&tab=user";
			  $popup_name = 'user';
		  }
		  else {
			  $user_selected = 0;
			  $popup_href = $site->CONF['wwwroot'].$site->CONF['adm_path']."/edit_group.php?group_id=".$site->fdat['group_id']."&tab=group";
			  $popup_name = 'group';
		  }
		  # if everybody group is selected, make delete button inactive
		  if ($site->fdat['group_id']==get_topparent_group(array("site" => &$site)) && !$site->fdat['user_id']) {
			$everybody_group = 1;
		  }

		  # if superuser is selected, make delete button inactive
		  if ($site->fdat['user_id'] && $user->all['is_predefined']) {
			$is_superuser = 1;
		  }

	  ############# / detail buttons activity
	  ?>
        <TR> 
			<?############ new buttons ###########?>

				<TD nowrap><a href="javascript:void(openpopup('<?=$site->CONF['wwwroot'].$site->CONF['adm_path']?>/edit_user.php?tab=user&op=new&group_id=<?=$site->fdat['group_id']?>','user','366','450'))" ><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/users/user.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="pt">&nbsp;<?=$site->sys_sona(array(sona => "user", tyyp=>"kasutaja"))?></A></TD>
				<TD  nowrap><a href="javascript:void(openpopup('<?=$site->CONF['wwwroot'].$site->CONF['adm_path']?>/edit_group.php?tab=group&op=new&group_id=<?=$site->fdat['group_id']?>','group','366','450'))"><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/users/group.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="pt"><?=$site->sys_sona(array(sona => "group", tyyp=>"kasutaja"))?></A></TD>
			<?############ edit button ###########?>

				<TD nowrap><?if(!$in_active){?><a href="javascript:void(openpopup('<?=$popup_href?>&op=edit','<?=$popup_name?>','366','450'))"><?}?><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/edit.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="pt"> <?=$site->sys_sona(array(sona => "muuda", tyyp=>"editor"))?><?if(!$in_active){?></a><?}?></TD>

			<?############ delete button (inactive for Everybody group)###########?>
				<TD><?if(!$in_active && !$everybody_group)	{?><a href="javascript:void(openpopup('<?=$popup_href?>&op=delete','<?=$popup_name?>','413','108'))"><?} else{?>&nbsp;<?}?><img src="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/delete<?=($in_active || $everybody_group ? '_inactive' : '')?>.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="po"><?if(!$in_active && !$everybody_group){?></a><?}?></TD>

			<?############ duplicate button : inactive for everybody group ###########?>
				<TD><?if(!$in_active && !$everybody_group){?><a href="javascript:void(openpopup('<?=$popup_href?>&op=copy','<?=$popup_name?>','413','108'))"><?} else{?>&nbsp;<?}?><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/editcopy<?=($in_active || $everybody_group ? '_inactive' : '')?>.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="po"><?if(!$in_active && !$everybody_group){?></a><?}?></TD>

				<TD><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/general/s_toolbar_divider.gif" WIDTH="14" HEIGHT="20" BORDER="0" ALT="" id="po"></TD>

			<?############ save as CSV button ###########?>
				<TD nowrap><a href="export2csv.php?op=users"><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/filesave.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="pt"> <?=$site->sys_sona(array(sona => "salvesta", tyyp=>"editor"))?> CSV</a></TD>
				<TD><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/general/s_toolbar_divider.gif" WIDTH="14" HEIGHT="20" BORDER="0" ALT="" id="po"></TD>
				
			<?############ print button ###########?>
			<!--
				<TD><a href="#"><IMG 
				SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/fileprint.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="po"></a></TD>
			-->

			<?############ lock button : only for users ###########?>

			<TD><?if(!$in_active && $site->fdat['user_id']){?><a href="javascript:void(openpopup('<?=$site->CONF['wwwroot'].$site->CONF['adm_path']?>/edit_user.php?user_id=<?=$site->fdat['user_id']?>&op=lock','lock','413','108'))"><?}?><img src="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/<?=(!$site->fdat['user_id'] || $user->all['is_locked']?'lock':'unlock')?><?=($in_active || !$site->fdat['user_id'] ? "_inactive" :'')?>.png" alt="<?=($user->all['is_locked']?'Unlock':'Lock')?>" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" id="po"><?if(!$in_active && $site->fdat['user_id']){?></a><?}?></TD>

			<?############ view ###########?>

				<?
					/*
					 * Check if is favorite 
					*/
					if($site->fdat['user_id']) {
						$is_favorite = $site->user->is_favorite(array(
							user_id => $site->fdat['user_id'],
						));
					} else {
						$is_favorite = $site->user->is_favorite(array(
							group_id => $site->fdat['group_id'],
						));
					}
				?>
				<TD><a href="<?= $site->self ?>?user_id=<?= $site->fdat['user_id'] ?>&group_id=<?= $site->fdat['group_id'] ?>&bookmark=1" class="scms_button_img"><IMG SRC="<?=$site->CONF['wwwroot'].$site->CONF['styles_path']?>/gfx/icons/16x16/actions/bookmark<?= ($is_favorite?'':'_inactive') ?>.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" align=absmiddle></a></TD>
				<td width="100%">&nbsp;</td>
				<td><?=$site->sys_sona(array(sona=>'Role', tyyp=>'kasutaja'))?>:&nbsp;</td>
				<td style="padding-right: 10px;">
						<!-- Role filter -->
						<?############### ROLE selectbox 
						$sqltmp = $site->db->prepare("SELECT * FROM roles ORDER BY name");
						$sthtmp = new SQL($sqltmp);				
						?>
						<SELECT NAME="tmp_flt_role" class="scms_flex_input" style="width:160px" onchange="javascript:document.getElementById('searchbox').value='';document.getElementById('searchform_flt_role').value=this.options[this.selectedIndex].value;document.searchform.submit();">
						<option value=""> -- <?=$site->sys_sona(array(sona => "vali", tyyp=>"admin"))?> -- </option>
						<?	while($role = $sthtmp->fetch() ){ ?>
							<option value="<?=$role['role_id']?>" <?=($site->fdat['flt_role']==$role['role_id']?' selected':'')?>><?=$role['name']?></option>
						<?} ?>

						</SELECT>
						<!-- //Role filter -->
				</td>
			</TR>
            </TR>
          </TABLE>
	<?
	# / FUNCTION BAR TABLE
	################################
	?>	  
		  </td>
      </tr>
  <!-- //Toolbar -->
<?
}