<?php

/*======================================================================*\
|| #################################################################### ||
|| # Drag'nDrop Shop 1.8                                              # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright 2014 JAKWEB All Rights Reserved.                       # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| #   ----------- Drag'nDrop Shop IS NOT FREE SOFTWARE -----------   # ||
|| #                      http://www.jakweb.ch                        # ||
|| #################################################################### ||
\*======================================================================*/

// Check if the file is accessed only via index.php if not stop the script from running
if (!defined('JAK_ADMIN_PREVENT_ACCESS')) die('You cannot access this file directly.');

// Check if the user has access to this file
if (!JAK_USERID || !JAK_ADMINACCESS) jak_redirect(BASE_URL);


// All the tables we need for this plugin
$errors = array();
$jaktable = DB_PREFIX.'user';
$lsfield = 'username';

// Now start with the plugin use a switch to access all pages
switch ($page1) {

	// Create new user
	case 'newuser':
	
		if (!$JAK_SPECIALACCESS) {
			jak_redirect(BASE_URL);
		}
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		    $defaults = $_POST;
		
		    if (empty($defaults['jak_name'])) {
		        $errors['e1'] = $tl['error']['e7'];
		    }
		    
		    if ($defaults['jak_email'] == '' || !filter_var($defaults['jak_email'], FILTER_VALIDATE_EMAIL)) {
		        $errors['e2'] = $tl['error']['e3'];
		    }
		    
		    if (!preg_match('/^([a-zA-Z0-9\-_])+$/', $defaults['jak_username'])) {
		    	$errors['e3'] = $tl['error']['e8'];
		    }
		    
		    if (jak_field_not_exist(strtolower($defaults['jak_username']),$jaktable,$lsfield)) {
		        $errors['e4'] = $tl['error']['e9'];
		    }
		     
		    if ($defaults['jak_password'] != $defaults['jak_confirm_password']) {
		    	$errors['e5'] = $tl['error']['e10'];
		    } elseif (strlen($defaults['jak_password']) <= '5') {
		    	$errors['e6'] = $tl['error']['e11'];
		    } else {
		    	$updatepass = '1';
		    }
		    
		    if (count($errors) == 0) {
		    
		    if ($updatepass) { $insert .= 'password = "'.hash_hmac('sha256', $defaults['jak_password'], DB_PASS_HASH).'",'; }
		
			$result = $jakdb->query('INSERT INTO '.$jaktable.' SET 
			username = "'.smartsql($defaults['jak_username']).'",
			name = "'.smartsql($defaults['jak_name']).'",
			email = "'.smartsql($defaults['jak_email']).'",
			access = '.$defaults['jak_access'].',
			'.$insert.'
			time = NOW()');
			
			$row1['id'] = $jakdb->jak_last_id();
		
		if (!$result) {
		    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {
		        jak_redirect(BASE_URL.'index.php?p=success');
		    }
		 } else {
		    
		   	$errors['e'] = $tl['error']['e'];
		    $errors = $errors;
		    }
		}
		
		// Call the template
		$template = 'newuser.php';
		
	break;
	case 'lock':
	
		$sql = 'UPDATE '.$jaktable.' SET access = IF (access = 1, 0, 1) WHERE id = '.smartsql($page2).'';
		$result = $jakdb->query($sql);
		    	
		if (!$result) {
			jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
		} else {
		    jak_redirect(BASE_URL.'index.php?p=success');
		}
		 		
	break;
	case 'delete':
		 
		// Check if user exists and can be deleted
		if (jak_user_exist_deletable($page2)) {
		        
			// Now check how many languages are installed and do the dirty work
			$sql = 'DELETE FROM '.$jaktable.' WHERE id = '.smartsql($page2).'';
			$result = $jakdb->query($sql);
		
			if (!$result) {
		    	jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
			} else {
		        jak_redirect(BASE_URL.'index.php?p=success');
		    }
		    
		} else {
		   	jak_redirect(BASE_URL.'index.php?p=error&sp=user-no-delete');
		}
		
	break;
	case 'edit':
	
		if (!$JAK_SPECIALACCESS && $page2 != JAK_USERID) {
			jak_redirect(BASE_URL);
		}
	
		// Check if the user exists
		if (is_numeric($page2) && jak_row_exist($page2,$jaktable)) {
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		    $defaults = $_POST;
		
		    if (empty($defaults['jak_name'])) {
		        $errors['e1'] = $tl['error']['e7'];
		    }
		    
		    if ($defaults['jak_email'] == '' || !filter_var($defaults['jak_email'], FILTER_VALIDATE_EMAIL)) {
		        $errors['e2'] = $tl['error']['e3'];
		    }
		    
		    if (!preg_match('/^([a-zA-Z0-9\-_])+$/', $defaults['jak_username'])) {
		    	$errors['e3'] = $tl['error']['e8'];
		    }
		    
		    if (jak_field_not_exist_id($defaults['jak_username'],$page2,$jaktable,$lsfield)) {
		        $errors['e4'] = $tl['error']['e9'];
		    }
		    
		    if (!empty($defaults['jak_password']) || !empty($defaults['jak_confirm_password'])) {    
		    if ($defaults['jak_password'] != $defaults['jak_confirm_password']) {
		    	$errors['e5'] = $tl['error']['e10'];
		    } elseif (strlen($defaults['jak_password']) <= '5') {
		    	$errors['e6'] = $tl['error']['e11'];
		    } else {
		    	$updatepass = '1';
		    }
		    }
		    
		    if (count($errors) == 0) {
		    
		    if (!isset($defaults['jak_access'])) $defaults['jak_access'] = '1';
		    
		    if ($updatepass) $insert .= 'password = "'.hash_hmac('sha256', $defaults['jak_password'], DB_PASS_HASH).'",';
		    
		    // We cant deny access for superadmin
		    $useridarray = explode(',', JAK_SUPERADMIN);
		    
		    if (!in_array($page2, $useridarray)) {
		    	
		    	$insert .= 'access = "'.$defaults['jak_access'].'",';
		    }
		
			$result = $jakdb->query('UPDATE '.$jaktable.' SET 
			username = "'.smartsql(trim($defaults['jak_username'])).'",
			name = "'.smartsql(trim($defaults['jak_name'])).'",
			'.$insert.'
			email = "'.filter_var($defaults['jak_email'], FILTER_SANITIZE_EMAIL).'"
			WHERE id = '.$page2);
		
		if (!$result) {
		    jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
		} else {
		    jak_redirect(BASE_URL.'index.php?p=success');
		}
		
		// Output the errors
		} else {
		    
		   	$errors['e'] = $tl['error']['e'];
		    $errors = $errors;
		}
		}
		
			$JAK_FORM_DATA = jak_get_data($page2,$jaktable);
			$template = 'edituser.php';
		
		} else {
		    
		   	jak_redirect(BASE_URL.'index.php?p=error&sp=not-exist');
		}
		
		break;
		default:
		
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['jak_delete_user'])) {
			    $defaults = $_POST;
			    
			    if (isset($defaults['lock'])) {
			    
			    $lockuser = $defaults['jak_delete_user'];
			    $useridarray = explode(',', JAK_SUPERADMIN);
			
			        for ($i = 0; $i < count($lockuser); $i++) {
			            $locked = $lockuser[$i];
			            
			            if (!in_array($locked, $useridarray)) {
				        	$sql = 'UPDATE '.$jaktable.' SET access = IF (access = 1, 0, 1) WHERE id = '.$locked.'';
				        	$result = $jakdb->query($sql);
						}
			        }
			  
			 	if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			    
			    }
			    
			    if (isset($defaults['delete'])) {
			    
			    $lockuser = $defaults['jak_delete_user'];
			    $useridarray = explode(',', JAK_SUPERADMIN);
			
			        for ($i = 0; $i < count($lockuser); $i++) {
			            $locked = $lockuser[$i];
			            
			            if (!in_array($locked, $useridarray)) {
			            
			            
			        	$jakdb->query('DELETE FROM '.$jaktable.' WHERE id = '.$locked.'');
			        	
			        	// Update Attachements to guest
			        	$jakdb->query('UPDATE '.DB_PREFIX.'attach SET userid = 0 WHERE userid = '.$locked.'');
			        	
						}
						
						$result = 1;
			        }
			  
			 	if (!$result) {
					jak_redirect(BASE_URL.'index.php?p=error&sp=mysql');
				} else {
			        jak_redirect(BASE_URL.'index.php?p=success');
			    }
			    
			    }
			
			    
			 }
			 
			if ($JAK_SPECIALACCESS) {
				$JAK_USER_ALL = jak_get_user_all($jaktable, '');		
			} else {
				$JAK_USER_ALL = jak_get_user_all($jaktable, JAK_USERID);
			}
			
			// Call the template
			$template = 'user.php';
}
?>