<?php
include_once "../../tools/inc.php";
$page = include("../common.php");
include("../tools/function.string.php");
include("../tools/function.sql.php");
$n=$settings["rec_count"];
$table="users".$config["table_prefix"];
$table_a="access".$config["table_prefix"];
$table_ua="user_access".$config["table_prefix"];
$table_n="users_newsletter".$config["table_prefix"];
$table_news="newsletters".$config["table_prefix"];
$table_g="users_mailing_groups".$config["table_prefix"];
$table_groups="mailing_groups".$config["table_prefix"];
$table_p="users_permissions".$config["table_prefix"];
$table_ps="users_permissions_smtp".$config["table_prefix"];
$table_smtp="smtp_accounts".$config["table_prefix"];
$access=check_level("Users");
$IMG="users.gif";

$sort=(in_array($sort, array("login", "name", "mail")) ? $sort : "login");
$sort_d=(isset($sort_d) ? 1 : 0);

$search_link=new Link($link->path);
$search_link->add("sort");
$search_link->add("sort_d");

$link->add("keywords");
$sort_link=new Link($link->get());
$link->add("sort");
$link->add("sort_d");
$filter_link=new Link($link->get());
$offset_link=new Link($link->get());
$link->add("offset");

$message_list=array(
        1 => "{rs:MSG_USERS_PROFILE} {rs:MSG_CREATED}",
        2 => "{rs:MSG_USERS_PROFILE} {rs:MSG_UPDATED}",
        3 => "{rs:MSG_USERS_PROFILE} {rs:MSG_DELETED}",
);

$system_status_list=array(
        0 => "{rs:USER_LEVEL_0}",
        1 => "{rs:USER_LEVEL_1}",
);

function get_access_list() {
        global $db, $config, $table_a;
        $res=array();
        $sql="select * from $table_a group by title order by title";
        $rs=$db->select($sql);
        for ($i=0; $i<count($rs); $i++) $res[]=$rs[$i]["title"];
        return $res;
}

function put_permissions($user_id, $list, $array=NULL) {
        global $db, $page, $config, $table_ua, $table_a;
        $list=(is_array($list) ? $list : array());
	if (isset($array)) $array=(is_array($array) ? $array : array());
        $sql="select * from modules".$config["table_prefix"]." order by title";
        $rs=$db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
                $_page = new Template("templates/users/permission_line.tpl");
                $_page->dictionary("common/dict.ru");
                $_page->assign(array("PATH" => $PATH));
                for ($j=0; $j<count($list); $j++) {
                        $id=get_val($table_a, "id", "where module_id='".$rs[$i]["id"]."' and title='".$list[$j]."'");
                        $_page->addrow("LINE", array(
                                "id"            => $id,
                                "p_id"          => $j,
                                "checked"       => (isset($array) ? (isset($array[$j]) ? in_array($id, $array[$j]) : false) : is_val($table_ua, "where user_id='$user_id' and access_id='$id'")),
                                "class"         => ($i%2),
                        ));
                }
                $page->addrow("LINE", array(
                        "module"        => $rs[$i]["title"],
                        "line"          => $_page->evaluate(),
                        "class"         => ($i%2),
                ));
        }
}
$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if (isset($del) and (isset($access["delete"]) or isset($access["admin"]))) {
	$del=(is_array($del) ? $del : array($del));
	if (!in_array($ui['id'], $del)) {
        	$del=implode(', ', $del);
	        $sql=array();
      	  	$sql[]="delete from $table where id in ($del)";
      	  	$sql[]="delete from $table_ua where user_id in ($del)";
      	  	$sql[]="delete from settings".$config["table_prefix"]." where owner_id in ($del)";
		$sql[]="delete from $table_p where user_id in ($del)";
		$sql[]="delete from $table_ps where user_id in ($del)";
		$sql[]="delete from $table_n where user_id in ($del)";
		$sql[]="delete from $table_g where user_id in ($del)";
      	  	$db->execute_all($sql);
       		$link->add("_r", "3");
		$db->close();
		header("Location: ".$link->get());
		exit;
	} else $error->add('{rs:ERROR_DELETE_ADMIN}');
}

if (isset($edit) and (isset($access["edit"]) or isset($access["view"]) or isset($access["admin"]))) {
        $sql="select * from $table where id='$edit'";
        $rs=$db->select($sql);
        $data=$rs[0];
        if (!isset($data["id"])) {
                $IMG='users_add.gif';
                $edit=0;
                $data["gender"]=1;
                $r["date_created"]=time();
        }
        else {
                $IMG='users_edit.gif';
                $edit=$data["id"];
                $r["date_created"]=$data["date_created"];
        }
        if (isset($save)) {
                $r["login"]=check_string($r["login"], 1);
                $r["password"]=check_string($r["password"], 1);
                $r["password2"]=check_string($r["password2"], 1);
                $r["mail"]=check_string($r["mail"], 1);
                $r["name"]=check_string($r["name"], 1);
                $r["gender"]=($r["gender"] ? 1 : 0);
                $r["phone_h"]=check_string($r["phone_h"], 1);
                $r["phone_w"]=check_string($r["phone_w"], 1);
                $r["phone_c"]=check_string($r["phone_c"], 1);
                $r["modify_user"]=$ui["id"];
                $r["modify_time"]=time();
                if (!$r["login"]) $error->add("{rs:ERROR_LOGIN}");
                if (!$r["password"] && !$edit) $error->add("{rs:ERROR_PASSWORD}");
                if ($r["password"]!=$r["password2"]) $error->add("{rs:ERROR_PASSWORD_CONFIRMATION}");
                if (!check_email($r["mail"])) $error->add("{rs:ERROR_MAIL}");
                if (is_val($table, "where login='".$r["login"]."' and id<>'$edit'")) $error->add("{rs:ERROR_USER_EXIST}");
		if (!$error->count and !isset($access["edit"]) and !isset($access["admin"])) $error->add('{rs:ERROR_ACCESS_RESTRICTED}');
                if (!$error->count) {
                        $r["password"]=($r["password"] ? $r["password"] : $data["password"]);
                        $fields="date_created, system_status, login, password, mail, name, gender, phone_h, phone_w, phone_c, status, modify_user, modify_time";
                        $sql=($edit ? get_sql_update($table, $fields, $r, "where id='$edit'") : get_sql_insert($table, $fields, $r));
                        $db->execute($sql);
                        $link->add("_r", ($edit ? '2' : '1'));
                        if (!$edit) {
                                $edit=mysql_insert_id();

				// Creating main settings for user
				$data=array(
					"mail_mode"		=> 0,
					"mail_from"		=> $r['mail'],
					"mail_from_name"	=> "Mailing List Manager Pro",
					"encoding"		=> "UTF-8",
					"mail_count"		=> get_val('settings'.$config["table_prefix"], 'mail_count', 'limit 1'),
					"is_quick_steps"	=> 1,
					"email_activation"	=> 1,
					"unsubscribe_confirm"	=> 1,
					"show_encoding"		=> 1,
					"owner_id"		=> $edit,
				);
				$fields="mail_mode, autoresponder_smtp, autoresponder_pop3, campaign_schedule_smtp, campaign_schedule_pop3, mail_from, mail_from_name, encoding, mail_count, date_format, is_quick_steps, email_activation, unsubscribe_confirm, show_encoding, owner_id, modify_user, modify_time";
				$sql=get_sql_insert('settings'.$config["table_prefix"], $fields, $data);
				$db->execute($sql);

                                $sql="select id from $table_a";
                                $rs=$db->select($sql);
                                for ($i=0; $i<count($rs); $i++) {
                                        $data=array(
                                                "user_id"       => $edit,
                                                "access_id"     => $rs[$i]['id'],
                                        );
                                        $sql=get_sql_insert($table_ua, 'user_id, access_id', $data);
                                        $db->execute($sql);
                                }
                        }
                        $db->close();
                        header("Location: ".$link->get());
                        exit;
                } else {
                        $r["id"]=$edit;
                        $data=html_string($r, true);
                }
        } else {
                $data=html_string($data);
        }
        $page->section("USERS_EDIT");
        get_row_from_array("SYSTEM_STATUS_SELECT", $system_status_list, $data["system_status"]);
        $data["BACK_LINK"]=$link->get();
        $data["BACK_TITLE"]="{rs:TITLE_USERS}";
	$data["WINDOW_TITLE"]="{rs:EDIT_USERS}";
        $page->assign($data);
} elseif (isset($permission) and (isset($access["permission"]) or isset($access["view"]) or isset($access["admin"]))) {
        $IMG='users_permissions.gif';
        $sql="select * from $table where id='$permission' and system_status=0";
        $rs=$db->select($sql);
        if (isset($rs[0]["id"])) {
		if (isset($save) and !isset($access["permission"]) and !isset($access["admin"])) {
			$error->add('{rs:ERROR_ACCESS_RESTRICTED}');
		} elseif (isset($save)) {
			$r=check_array($r, 'newsletter_html_header, newsletter_html_footer');
			$r['user_id']=$permission;
			$r['newsletter_html_header']=check_string(preg_replace("/<P([^>]*?>.*?)<\/P>/", "<DIV\\1</DIV>", $r['newsletter_html_header']));
			$r['newsletter_text_header']=check_string($r['newsletter_text_header'], 1);
			$r['newsletter_html_footer']=check_string(preg_replace("/<P([^>]*?>.*?)<\/P>/", "<DIV\\1</DIV>", $r['newsletter_html_footer']));
			$r['newsletter_text_footer']=check_string($r['newsletter_text_footer'], 1);
			if ($r['newsletters_type']<0  or $r['newsletters_type']>2) $r['newsletters_type']=0;
			if ($r['groups_type']<0  or $r['groups_type']>2) $r['groups_type']=0;
			if ($r['mailing_smtp_type']<0  or $r['mailing_smtp_type']>2) $r['mailing_smtp_type']=0;
			if ($r['mailing_speed_type']<0  or $r['mailing_speed_type']>1) $r['mailing_speed_type']=0;
			if ($r['account_type']<0  or $r['account_type']>1) $r['account_type']=0;
			if ($r['newsletter_header_type']<0  or $r['newsletter_header_type']>3) $r['newsletter_header_type']=0;
			if ($r['attachments']<0  or $r['attachments']>1) $r['attachments']=0;
			$account_start=check_date($r["account_start"], $settings["date_format"]);
			$account_end=check_date($r["account_end"], $settings["date_format"]);

			if ($r['max_newsletters'] and ($r['max_newsletters']<0 or !validation($r['max_newsletters'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_NEWSLETTERS}\"");
			if ($r['max_groups']<0 and ($r['max_groups']<0 or !validation($r['max_groups'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_MAILING_GROUPS}\"");
			if ($r['max_subscribers'] and ($r['max_subscribers']<0 or !validation($r['max_subscribers'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_SUBSCRIBERS}\"");
			if ($r['max_groups_subscribers'] and ($r['max_groups_subscribers']<0 or !validation($r['max_groups_subscribers'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_SUBSCRIBERS_PER_GROUPS}\"");
			elseif ($r['max_subscribers'] and $r['max_groups_subscribers']>$r['max_subscribers']) $error->add("\"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_SUBSCRIBERS_PER_GROUPS}\" {rs:ERROR_MORE_THEN} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_SUBSCRIBERS}\"");
			if ($r['max_newsletter_size'] and ($r['max_newsletter_size']<0 or !validation($r['max_newsletter_size'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_NEWSLETTER_SIZE}\"");
			if ($r['max_mails_per_month'] and ($r['max_mails_per_month']<0 or !validation($r['max_mails_per_month'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_MAILS_PER_MONTH}\"");
			if ($r['max_mails_per_days'] and ($r['max_mails_per_days']<0 or !validation($r['max_mails_per_days'], 'n'))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_MAILS_PER_DAYS}\"");
			elseif ($r['max_mails_per_month'] and $r['max_mails_per_days']>$r['max_mails_per_month']) $error->add("\"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_MAILS_PER_DAYS}\" {rs:ERROR_MORE_THEN} \"{rs:PERMISSION_USER_LIMITS} / {rs:PERMISSION_USER_LIMITS_MAX_MAILS_PER_MONTH}\"");
			if ($r['mailing_speed_type'] and  ($r['mailing_speed'] and ($r['mailing_speed']<0 or !validation($r['mailing_speed'], 'n')))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_MAILING_SPEED}\"");
			if ($r['account_type']==1 and ((!$account_start and !$account_end) or ($r['account_start'] and !$account_start) or ($r['account_end'] and !$account_end) or ($account_start>$account_end and $account_end))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_ACCOUNT}\"");
			if ($r['attachments'] and ($r['max_attachments_size'] and ($r['max_attachments_size']<0 or !validation($r['max_attachments_size'], 'n')))) $error->add("{rs:ERROR_INVAID} \"{rs:PERMISSION_ATTACHMENTS} / {rs:PERMISSION_ATTACHMENTS_MAX_SIZE}\"");
			if (!$error->count) {
				$r["account_start"]=$account_start;
				$r["account_end"]=$account_end;
	                        $sql=array();
				$fields="user_id, newsletters_type, groups_type, max_newsletters, max_groups, max_subscribers, max_groups_subscribers, max_newsletter_size, max_mails_per_month, max_mails_per_days, mailing_php, mailing_smtp, mailing_smtp_type, mailing_speed_type, mailing_speed, account_type, account_start, account_end, newsletter_html_header, newsletter_text_header, newsletter_html_footer, newsletter_text_footer, attachments, max_attachments_size";
				$sql[]="delete from $table_p where user_id='$permission'";
				$sql[]=get_sql_insert($table_p, $fields, $r);
				$db->execute_all($sql);

				$sql=array();
	                        $sql[]="delete from $table_ua where user_id='$permission'";
	                        $fields="user_id, access_id";
	                        reset($access_id);
	                        $key=key($access_id);
	                        while (isset($key)) {
	                                for ($j=0; $j<count($access_id[$key]); $j++) {
	                                        $data=array(
	                                                "user_id"       => $permission,
	                                                "access_id"     => $access_id[$key][$j],
	                                        );
	                                        $sql[]=get_sql_insert($table_ua, $fields, $data);
	                                }
	                                next($access_id);
	                                $key=key($access_id);
	                        }
	                        $db->execute_all($sql);
				
	                        $sql="delete from $table_n where user_id='$permission'";
	                        $db->execute($sql);
				if (is_array($r["newsletter_id"])) {
		                        $fields="user_id, newsletter_id";
		                        $data=array("user_id" => $permission);
		                        if (in_array(-1, $r["newsletter_id"])) $r["newsletter_id"]=array(-1);
		                        for ($i=0; $i<count($r["newsletter_id"]); $i++) {
		                                if ($r["newsletter_id"][$i]) {
		                                        $data["newsletter_id"]=$r["newsletter_id"][$i];
		                                        $sql=get_sql_insert($table_n, $fields, $data);
		                                        $db->execute($sql);
		                                }
		                        }
				}

	                        $sql="delete from $table_g where user_id='$permission'";
	                        $db->execute($sql);
				if (is_array($r["group_id"])) {
		                        $fields="user_id, group_id";
		                        $data=array("user_id" => $permission);
		                        if (in_array(-1, $r["group_id"])) $r["group_id"]=array(-1);
		                        for ($i=0; $i<count($r["group_id"]); $i++) {
		                                if ($r["group_id"][$i]) {
		                                        $data["group_id"]=$r["group_id"][$i];
		                                        $sql=get_sql_insert($table_g, $fields, $data);
		                                        $db->execute($sql);
		                                }
		                        }
				}

	                        $sql="delete from $table_ps where user_id='$permission'";
	                        $db->execute($sql);
				if (is_array($r["smtp_id"])) {
		                        $fields="user_id, account_id";
		                        $data=array("user_id" => $permission);
		                        if (in_array(-1, $r["smtp_id"])) $r["smtp_id"]=array(-1);
		                        for ($i=0; $i<count($r["smtp_id"]); $i++) {
		                                if ($r["smtp_id"][$i]) {
		                                        $data["account_id"]=$r["smtp_id"][$i];
		                                        $sql=get_sql_insert($table_ps, $fields, $data);
		                                        $db->execute($sql);
		                                }
		                        }
				}
				
	                        $db->close();
	                        $link->add("permission");
	                        $link->add("_r", "2");
	                        header("Location: ".$link->get());
	                        exit;
			} else {
				$r['newsletter_html_header']=stripslashes($r['newsletter_html_header']);
				$r['newsletter_html_footer']=stripslashes($r['newsletter_html_footer']);
				$data=html_string($r, true);
			}
                } else {
			$sql="select * from $table_p where user_id='$permission'";
        		$rs=$db->select($sql);
			$data=$rs[0];
			if (isset($data)) {
				$data['attachments']=($data['attachments'] ? 1 : 0);
				$data['newsletter_id']=$db->get_array($table_n, "newsletter_id", "newsletter_id", "where user_id='$permission'");
				$data['group_id']=$db->get_array($table_g, "group_id", "group_id", "where user_id='$permission'");
				$data['smtp_id']=$db->get_array($table_ps, "account_id", "account_id", "where user_id='$permission'");
				$data['account_start']=($data['account_start'] ? date($settings["date_format"], $data['account_start']) : '');
				$data['account_end']=($data['account_end'] ? date($settings["date_format"], $data['account_end']) : '');
			} else {
				$data['attachments']=1;
				$data['newsletter_id']=array();
				$data['group_id']=array();
				$data['smtp_id']=array();
			}
			$data=html_string($data, false);
		}
                $page->section("USERS_PERMISSION");
                $access_list=get_access_list();
                for ($i=0; $i<count($access_list); $i++)
                        $page->addrow("PERMISSIONS", array(
                                "title" => $access_list[$i],
                                "p_id" => $i,
                        ));
                put_permissions($permission, $access_list, $access_id);
		$sql="select count(*) from $table_news";
		$n_list=($db->count($sql, true)>0);
                $all_news=isset($array['-1']);
                get_row_from_table("NEWSLETTER_SELECT", $table_news, $data['newsletter_id'], "id", "subject");
		$sql="select count(*) from $table_groups";
		$mg_list=($db->count($sql, true)>0);
                $all_groups=isset($array['-1']);
                get_row_from_table("MAILING_GROUPS_SELECT", $table_groups, $data['group_id'], "id", "title");
		$sql="select count(*) from $table_smtp";
		$s_list=($db->count($sql, true)>0);
                $all_smtp=isset($array['-1']);
                get_row_from_table("MAILING_SMTP_SELECT", $table_smtp, $data['smtp_id'], "id", "title");
		
		include("../tools/var.tmp.php");
		get_row_from_array("VAR_LIST", $var_tmp_list);
		$page->assign($data);
                $page->assign(array(
			'newsletter_list'	=> $n_list,
			'mg_list'		=> $mg_list,
			'smtp_list'		=> $s_list,
                        "all_news"      	=> $all_news,
                        "all_groups"   		=> $all_groups,
                        "all_smtp"   		=> $all_smtp,
                        "colspan"       	=> count($access_list)+1,
                        "BACK_LINK"     	=> $link->get(),
                        "BACK_TITLE"    	=> "{rs:TITLE_USERS}",
			"WINDOW_TITLE"		=> "{rs:EDIT_PERMISSION}",
                ));
        } else {
                $db->close();
                header("Location: ".$link->get());
                exit;           
        }
} elseif (isset($access["view"]) or isset($access["admin"])) {
        if (isset($edit) or (isset($del) and !(isset($access["delete"]) or isset($access["admin"]))) or isset($permission)) $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
        $reg=get_search_regular($keywords);
        $where.=($reg ? " where (login regexp '$reg' or mail regexp '$reg' or name regexp '$reg')" : "");
        $page->section("USERS");
        $sql="select count(*) from $table $where";
        $rs=$db->select($sql);
        $count=$rs[0][0];
        $i=ceil($count/$n)-1;
        $offset=(($offset>$i) ? $i : ($offset<0 ? 0 : $offset));
        $sql="select * from $table $where order by $sort ".($sort_d ? "DESC" : "")." limit ".($offset*$n). ", $n";
        $rs = $db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
                $data=$rs[$i];
                $data["disabled"]=(!$data["status"]);
                $page->addrow("LINE", $data);
        }
        $page->assign(array(
                "count"         => $count,
                "offset"        => get_new_offsets($count, $n, $offset_link->get(), $offset),
                "BACK_LINK"     => $PATH,
                "BACK_TITLE"    => "{rs:TITLE_MAIN_MENU}",
		"WINDOW_TITLE"	=> "{rs:TITLE_USERS}",
        ));
} else {
        $page->section("ACCESS_DENIED");
        $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
}
add_to_tree("{rs:TITLE_USERS}", "users/");
$db->close();
$sort_link=$sort_link->get();
$page->assign(array(
        "TITLE"                 => "{rs:TITLE_USERS}",
        "ERROR"                 => ($error->count ? $error->get() : ""),
        "MESSAGE"               => ($message->count ? $message->get() : ""),
        "LINK"                  => $link->get(),
        "SEARCH_LINK"           => $search_link->get(),
        "keywords"              => htmlspecialchars($keywords),
        "sort_by_login"         => $sort_link.($sort_link ? '&' : '?')."sort=login".($sort=="login" ? ($sort_d ? "" : "&sort_d=1") : ""),
        "sort_by_mail"          => $sort_link.($sort_link ? '&' : '?')."sort=mail".($sort=="mail" ? ($sort_d ? "" : "&sort_d=1") : ""),
        "sort_by_name"          => $sort_link.($sort_link ? '&' : '?')."sort=name".($sort=="name" ? ($sort_d ? "" : "&sort_d=1") : ""),
        "sort_login_img"        => ($sort=="login" ? ($sort_d ? "_asc" : "_desc") : ""),
        "sort_mail_img"         => ($sort=="mail" ? ($sort_d ? "_asc" : "_desc") : ""),
        "sort_name_img"         => ($sort=="name" ? ($sort_d ? "_asc" : "_desc") : ""),
        "FILTER_LINK"           => $filter_link->get(),
        "is_users"              => 1,
        "IMG"                   => $IMG,
));
print $page->evaluate();
?>