<?
/*
Auth/User/Group management
*/

class auth {

	var $db;
	var $currentUser = array();


	function login($username, $password) {
		global $db, $config, $settings;
		
		$username = strtolower($username);
		//$password = strtolower($password);
		
		if ($config->settings['suspend'] && $username != "admin") {
			$this->error = "Afian suspended.";
			return "afiansuspend";
		} else {
		$completeUserInfo = $db->GetRow("
SELECT 
users.suspended AS groupSuspend, 
auth.password, 
users.suspended AS userSuspend, 
users.id, 
users.lastlogin, 
users.previouslogin

FROM 

".$settings->config['users_tablename']." AS users,
".$settings->config['groups_tablename']." AS groups,
".$settings->config['interauth_tablename']." AS interauth,
".$settings->config['auth_tablename']." AS auth 

WHERE 

auth.username=interauth.username 
AND 
interauth.username='".$username."' 
AND 
users.id=interauth.id 
AND 
users.gid=groups.id

",false);


		//debug($completeUserInfo);
		if ($completeUserInfo) {
				if ($completeUserInfo['password'] == $password) {
					if ($completeUserInfo['userSuspend'] == "") {
						if ($completeUserInfo['groupSuspend'] == "1") {
							$this->error = "User suspended.";
							return "suspend";
						}
					} elseif ($completeUserInfo['userSuspend'] == "1") {
						$this->error = "User suspended.";
						return "suspend";
					}
					$_SESSION['username'] = $username;
					$_SESSION['password'] = md5($password);
					
					/* cookies ... */
					setcookie("username", $username, time()+31536000);
					setcookie("password", md5($password), time()+31536000);
					
					$_SESSION['lastLoginAfterLogin'] = $completeUserInfo['lastlogin'];
					
					
					
					//debug($completeUserInfo);
					$this->updateUser($completeUserInfo['id'], array("lastlogin"=>time(), "previouslogin"=>$completeUserInfo['lastlogin']));
					return "ok";
				} else {
					$this->error = "Incorect login.";
					return "wrongpass";
				}
			} else {
				$this->error = "Incorect login.";
				return "nouser";
			}
		}
	}


	function logged() {
		global $db, $settings;
				
		if ($_SESSION['username'] || $_COOKIE['username'] || $_SERVER['PHP_AUTH_USER']) {
		
		
		if ($_SESSION['username']) {
			$username = $_SESSION['username'];
			$password = $_SESSION['password'];
		} else if ($_COOKIE['username']) {
			$username = $_COOKIE['username'];
			$password = $_COOKIE['password'];
		} else {
			$username = $_SERVER['PHP_AUTH_USER'];
			$password = md5($_SERVER['PHP_AUTH_PW']);
		}

		
		if (!$_SESSION['username']) {
			$_SESSION['username'] = $username;
		}
		
		if (!$_SESSION['password']) {
			$_SESSION['password'] = $password;
		}
		$rs = $db->GetRow("
SELECT 

* 

FROM 

".$settings->config['auth_tablename']." AS auth, 
".$settings->config['interauth_tablename']." AS interauth, 
".$settings->config['users_tablename']." AS users , 
".$settings->config['optinfo_tablename']." AS optional_info

WHERE 

auth.username=interauth.username 
AND 
interauth.id=users.id 
AND 
interauth.username='".$username."' 
AND 
optional_info.uid=users.id 

");
//echo "/*".$rs['password']." - ".md5($rs['password'])." - ".$_SESSION['password']."*/";

			if($rs != false && md5($rs['password']) == $password) {
				if ($rs['suspended'] == "1") {
					$this->errorCode = 14;
					$this->error = "account suspended";
					return false;
				} else {
					$this->currentUserInfo = $rs;
					$this->loggedOk = true;
					return true;
				}
			} else {
				$this->errorCode = 13;
				$this->error = "password is no longer valid";
				return false;
			}
		} else {
			return false;
		}
	}


	function username2id($username) {
		global $db, $settings;
		$rs = $db->GetOne("SELECT id FROM ".$settings->config['interauth_tablename']." WHERE username='".$username."'",false);
		return $rs;
	}


	function id2username($id) {
		global $db, $settings;
		$rs = $db->GetOne("SELECT username FROM ".$settings->config['interauth_tablename']." WHERE id='".$id."'",false);
		return $rs;
	}


	function logout() {
		if ($this->loggedOk) {
			$_SESSION['username'] = "";
			$_SESSION['password'] = "";
			/* cookies ... */
			setcookie("username", "", time() - 3600);
			setcookie("password", "", time() - 3600);
			setcookie("AfianLastFolder", "", time()-3600);
			$this->loggedOk = false;
		}
	}


	function getUserInfoById($id) {
		global $db, $settings;	
		$rs = $db->GetRow("SELECT * FROM ".$settings->config['users_tablename'].",".$settings->config['interauth_tablename'].",".$settings->config['auth_tablename'].",".$settings->config['optinfo_tablename']." WHERE ".$settings->config['interauth_tablename'].".id='".$id."' AND ".$settings->config['interauth_tablename'].".username=".$settings->config['auth_tablename'].".username AND ".$settings->config['interauth_tablename'].".id=".$settings->config['users_tablename'].".id AND ".$settings->config['optinfo_tablename'].".uid=".$settings->config['interauth_tablename'].".id",false);
		if ($rs) {
			return $rs;
		} else {
			return false;
		}
	}

	function getUserInfoByUsername($username) {
		global $db, $settings;	
		$rs = $db->GetRow("SELECT * FROM ".$settings->config['users_tablename'].",".$settings->config['interauth_tablename'].",".$settings->config['auth_tablename'].",".$settings->config['optinfo_tablename']." WHERE ".$settings->config['interauth_tablename'].".username='".$username."' AND ".$settings->config['interauth_tablename'].".username=".$settings->config['auth_tablename'].".username AND ".$settings->config['interauth_tablename'].".id=".$settings->config['users_tablename'].".id AND ".$settings->config['optinfo_tablename'].".uid=".$settings->config['interauth_tablename'].".id",false);
		if ($rs) {
			return $rs;
		} else {
			return false;
		}
	}


	function delUser($uid) {
		global $sys, $fm, $settings, $db;
		$userinfo = $this->getUserInfoById($uid);
		$trash = gluePath((($settings->config['trashpath'])?$settings->config['trashpath']:gluePath($sys['root'], "/system/data/trash/")),$userinfo['username']);
		$fm->deleteDir($trash);
		
		
		/* deleting public info + gallery options */
		/*
		$rs = $db->query("SELECT * FROM ".$settings->config['flags_tablename'].", ".$settings->config['public_info_tablename']." WHERE ".$settings->config['public_info_tablename'].".fid=".$settings->config['flags_tablename'].".id AND uid='".$uid."'");
		if ($rs->RecordCount() > 0) {
			while (!$rs->EOF) {
				if ($rs->fields['public']) {
				$rs = $db->query("DELETE FROM ".$settings->config['public_info_tablename']." WHERE fid='".$rs->fields['fid']."'");
				$rs = $db->query("DELETE FROM ".$settings->config['gallery_options_tablename']." WHERE fid='".$rs->fields['fid']."'");
				}
				$rs->MoveNext();
			}
		}
		*/

		/*clear share info*/
		$rs = $db->query("DELETE FROM ".$settings->config['share_info_tablename']." WHERE to_uid='".$uid."'");

		/* clear users' custom gallery templates */
		/*
		$rs = $db->query("SELECT * FROM ".$settings->config['gallery_tpl_groups_tablename']." WHERE uid='".$uid."'");
		if ($rs->RecordCount() > 0) {
			while (!$rs->EOF) {
				$rs = $db->query("DELETE FROM ".$settings->config['gallery_tpl_tablename']." WHERE id='".$rs->fields['main_tplid']."'");
				$rs = $db->query("DELETE FROM ".$settings->config['gallery_tpl_tablename']." WHERE id='".$rs->fields['enlarge_tplid']."'");
				$rs->MoveNext();
			}
		}
		$rs = $db->query("DELETE FROM ".$settings->config['gallery_tpl_groups_tablename']." WHERE uid='".$uid."'");
		*/
		
		/*clear flags*/
		$rs = $db->query("DELETE FROM ".$settings->config['flags_tablename']." WHERE uid='".$uid."'");

		/*clear trash data*/
		$rs = $db->query("DELETE FROM ".$settings->config['trash_tablename']." WHERE uid='".$uid."'");
		/*clear user data*/
		$rs = $db->query("DELETE FROM ".$settings->config['users_tablename']." WHERE id='".$uid."'");
		$rs = $db->query("DELETE FROM ".$settings->config['auth_tablename']." WHERE username='".$userinfo['username']."'");
		$rs = $db->query("DELETE FROM ".$settings->config['interauth_tablename']." WHERE id='".$uid."'");
		$rs = $db->query("DELETE FROM ".$settings->config['last_uploads_tablename']." WHERE uid='".$uid."'");
		$rs = $db->query("DELETE FROM ".$settings->config['activity_logs_tablename']." WHERE uid='".$uid."'");
		$rs = $db->query("DELETE FROM ".$settings->config['optinfo_tablename']." WHERE uid='".$uid."'");
		return true;
	}


	function addUser($data) {
		global $sys, $fm, $db, $settings;
		//$db->debug=1;
		if (!$this->getUserInfoByUsername($data['username'])) {
			$rs = $db->query("SELECT * FROM ".$settings->config['users_tablename']."
 WHERE id = ''");
			$insertSQL = $db->GetInsertSQL($rs, $data);
			$rs = $db->query($insertSQL);

			$uid = $db->Insert_ID();
			/* aici e nevoie de cod pt db care nu suporta functia asta */

			$this->lastInsertId = $uid;

			$interauth_data['username'] = $data['username'];
			$interauth_data['id'] = $uid;
			$rs = $db->query("SELECT * FROM ".$settings->config['interauth_tablename']."
 WHERE id = ''");
			$insertSQL = $db->GetInsertSQL($rs, $interauth_data);
			$rs = $db->query($insertSQL);

			$auth_data['username'] = $data['username'];
			$auth_data['password'] = $data['password'];
			$rs = $db->query("SELECT * FROM ".$settings->config['auth_tablename']."
 WHERE username = ''");
			$insertSQL = $db->GetInsertSQL($rs, $auth_data);
			$rs = $db->query($insertSQL);
//$db->debug=0;


			$optinfo['uid'] = $uid;
			$optinfo['firstname'] = $data['firstname'];
			$optinfo['lastname'] = $data['lastname'];
			$optinfo['email'] = $data['email'];
			$optinfo['company'] = $data['company'];
			$sql = "SELECT * FROM ".$settings->config['optinfo_tablename']." WHERE uid = '".$uid."'"; 
			$rs = $db->query($sql);
			$insertSQL = $db->GetInsertSQL($rs, $optinfo);
			$rs = $db->query($insertSQL);

			$optinfo['uid'] = $uid;
			$sql = "SELECT * FROM ".$settings->config['history_tablename']." WHERE uid = '".$uid."'"; 
			$rs = $db->query($sql);
			$insertSQL = $db->GetInsertSQL($rs, $optinfo);
			$rs = $db->query($insertSQL);


				$trash = gluePath((($settings->config['trashpath'])?$settings->config['trashpath']:gluePath($sys['root'], "/system/data/trash/")), $data['username']);
				if (!is_dir($trash)) {
					if (!@mkdir($trash, 0777)) {
					$this->error .= "Failed to create trash folder for this user.";
					}
				}
				return true;
		} else {
			$this->error = "Username already in use.";
			return false;
		}
	}

	function updateUser($uid, $updatedData = array()) {
		global $db, $settings;
		$rs = $db->AutoExecute($settings->config['users_tablename'], $updatedData, "UPDATE", "id = '".$uid."'");
		if ($rs) {
			return true;
		} else {
			$this->error = "Failed to update db record.";
			return false;
		}
	}

	function updateUserOptInfo($uid, $updatedData = array()) {
		global $db, $settings;
		$rs = $db->query("UPDATE ".$settings->config['optinfo_tablename']." SET `firstname`='".addslashes($updatedData['firstname'])."', `lastname`='".addslashes($updatedData['lastname'])."', `email`='".addslashes($updatedData['email'])."', `company`='".addslashes($updatedData['company'])."' where uid='".$uid."'");
		if ($rs) {
			return true;
		} else {
			$this->error = "Failed to update db record.";
			return false;
		}
	}

	function updateUserPass($username, $newpass) {
		global $db, $settings;
		$updatedData['password'] = $newpass;
		$rs = $db->AutoExecute($settings->config['auth_tablename'], $updatedData, "UPDATE", "username = '".$username."'");
		if ($rs) {
			return true;
		} else {
			$this->error = "Failed to update db record.";
			return false;
		}
	}

	function createGroup($data) {
		global $sys, $db, $settings;
		if (!$this->groupNameInUse($data['name'])) {
			$rs = $db->query("SELECT * FROM ".$settings->config['groups_tablename']." WHERE id='' LIMIT 1");
			$insertSql = $db->GetInsertSQL($rs, $data);
			$db->query($insertSql);
			return true;
		} else {
			$this->error = "Group name in use.";
			return false;
		}
	}
	
	function groupNameInUse($name) {
		global $db, $settings;
		return $db->GetOne("SELECT COUNT(*) FROM ".$settings->config['groups_tablename']." WHERE name='".$name."'");
	}
	
	function getGroupInfo($id) {
		global $db, $settings;
		return $db->GetRow("SELECT * FROM ".$settings->config['groups_tablename']." WHERE id='".$id."'",false);
	}
	
	function getGroupInfoByName($name) {
		global $db, $settings;
		return $db->GetRow("SELECT * FROM ".$settings->config['groups_tablename']." WHERE name='".$name."'",false);
	}
	
	

	function transferUser($uid, $gid) {
		return $this->updateUser($uid, array("gid"=>$gid));
	}

	function updateGroup($gid, $updatedData = array()) {
		global $db, $settings;
		
		$rs = $db->query("UPDATE ".$settings->config['groups_tablename']." SET NAME='".addslashes($updatedData['name'])."', PATH='".addslashes($updatedData['path'])."',
 READONLY='".addslashes($updatedData['readonly'])."', 
 UPLOAD='".addslashes($updatedData['upload'])."', 
 DOWNLOAD='".addslashes($updatedData['download'])."', 
SENDBYEMAIL='".addslashes($updatedData['sendbyemail'])."', 
UPLOADNOTICE='".addslashes($updatedData['uploadnotice'])."', 
DOWNLOADNOTICE='".addslashes($updatedData['downloadnotice'])."', 
SHARING='".addslashes($updatedData['sharing'])."', 
SPACEQUOTA='".addslashes($updatedData['spacequota'])."', 
TRAFFICQUOTA='".addslashes($updatedData['trafficquota'])."', 
SHAREACCESS='".addslashes($updatedData['shareaccess'])."', 
VIEW_OTHERS='".addslashes($updatedData['view_others'])."', 
UI_TYPE='".addslashes($updatedData['ui_type'])."', 
UI_HAS_TREE='".addslashes($updatedData['ui_has_tree'])."' WHERE id = '".$gid."'");
		if ($rs) {
			return true;
		} else {
			$this->error = "Failed to update db record.";
			return false;
		}
	}
	
	function countAllUsers() {
		global $db, $settings;
		return $db->GetOne("SELECT COUNT(id) from ".$settings->config['users_tablename']."");
	}
	
	function gid2name($gid) {
		global $db, $settings;
		$rs = $db->GetOne("SELECT name FROM ".$settings->config['groups_tablename']." WHERE id='".$gid."'",false);
		return $rs;
	}
}

?>