KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.4.41 (Ubuntu)
System : Linux vmi1525618.contaboserver.net 5.4.0-105-generic #119-Ubuntu SMP Mon Mar 7 18:49:24 UTC 2022 x86_64
User : www-data ( 33)
PHP Version : 8.2.12
Disable Function : NONE
Directory :  /var/www/parasoffline.edukrypt.in/application/modules/admin/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //var/www/parasoffline.edukrypt.in/application/modules/admin/controllers/User.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata');

class User extends Admin_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('User_model');
		$this->load->library(array('parser', 'form_builder'));
	}

	public function index()
	{
		$this->mViewData['p_type']  = "list";
		$this->mViewData['message'] = $this->session->flashdata('upload_success');

		$admin_id = $this->session->userdata('user_id');

		$query_c  = $this->db->where('admin_id', $admin_id)->order_by('id', 'asc')->get('tags');
		if ($query_c->num_rows() > 0) {
			$tags  = $query_c->result();
		}

		$this->mViewData['tags'] = $tags;
		$this->mTitle .= 'Users';
		$this->render('user/user_list');
	}

	// Tags
	public function get_tags($value)
	{
		$Query = $this->db->where_in('id', explode(',', $value))->get('tags');
		if ($Query->num_rows() > 0) {
			$rows = $Query->result();
			$tags = [];
			foreach ($rows as $row) {
				$tg = $row->tag;
				$tags[] = "<button class='btn btn-xs btn-github'>$tg</button>";
			}
			return implode("<br>", $tags);
		}
		return "";
	}


	// Ajax
	public function check_posts()
	{
		$columns = array(
			0 => 'id',
			1 => 'id',
			2 => 'registration_code',
			3 => 'tag_id',
			4 => 'username',
			5 => 'password',
			6 => 'email',
			7 => 'aadharno',
			8 => 'registered',
			9 => 'active'
		);

		if ($this->session->userdata('user_id') == 1) {
			$admin_id = null;
		} else {
			$admin_id = $this->session->userdata('user_id');
		}

		$user_id    = $this->input->post('user_id');
		$tag_id    = $this->input->post('tag_id');

		print_r($this->input->get('user_id'));

		$limit = $this->input->post('length');
		$start = $this->input->post('start');
		$order = $columns[$this->input->post('order')[0]['column']];
		$dir   = $this->input->post('order')[0]['dir'];

		$totalData     = $this->User_model->check_permission_posts_count($user_id, $admin_id, $tag_id);
		$totalFiltered = $totalData;

		if (empty($this->input->post('search')['value'])) {
			$posts = $this->User_model->check_permission_posts($limit, $start, $order, $dir, $user_id, $admin_id, $tag_id);
		} else {
			$search = $this->input->post('search')['value'];
			$posts =  $this->User_model->check_permission_posts_search($limit, $start, $search, $order, $dir, $user_id, $admin_id, $tag_id);
			$totalFiltered = $this->User_model->check_permission_posts_search_count($search, $user_id, $admin_id, $tag_id);
		}

		$data = array();

		if (!empty($posts)) {
			$i = 1;

			foreach ($posts as $post) {
				$nestedData['id'] = '<input type="checkbox" class="_check_in" value="' . $post->id . '">';
				$i++;

				$nestedData['user_id']     = '<span style="font-size: 12px;">' . $post->id . '</span>';
				$nestedData['regcode']       = '<span style="font-size: 12px;">' . $post->registration_code . '</span>';

				$nestedData['tag_id'] = '<span style="font-size: 12px;">' . $this->get_tags($post->tag_id) . '</span>';

				$nestedData['username'] = '<span style="font-size: 12px;">' . $post->username . '</span>';
				$nestedData['password'] = '<span style="font-size: 12px;">' . $post->password . '</span>';
				$nestedData['aadharno']         = '<span style="font-size: 12px;">' . $post->aadharno . '</span>';
				$nestedData['email']        = '<span style="font-size: 12px;">' . $post->email . '</span><br><span style="font-size: 12px;">' . $post->phone . '</span>';
				// $nestedData['phone']       = '<span style="font-size: 12px;">' . $post->phone . '</span>';

				// Registered =============
				$reg = '';
				if ($post->registered) {
					$reg = 'checked';
				}
				$_switch = '<label class="switch"><input data-user_id=' . $post->id . ' class="change_status" data-col="registered" name="registered" ' . $reg . ' type="checkbox"><span class="slider round"></span></label>';
				$nestedData['registered'] = $_switch;

				// Active / inactive ================
				$active = '';
				if ($post->active) {
					$active = 'checked';
				}
				$_active = '<label class="switch"><input data-user_id=' . $post->id . ' data-col="active" class="change_status" name="active" ' . $active . ' type="checkbox"><span class="slider round"></span></label>';
				$nestedData['active'] = $_active;

				// $nestedData['created_on']       = '<span style="font-size: 12px;">' . $post->created_on . '</span>';

				// $nestedData['first_name']       = '<span style="font-size: 12px;">' . $post->first_name . '</span>';
				// $nestedData['last_name']       = '<span style="font-size: 12px;">' . $post->last_name . '</span>';
				// $nestedData['admission_code']       = '<span style="font-size: 12px;">' . $post->admission_code . '</span>';
				// $nestedData['company']       = '<span style="font-size: 12px;">' . $post->company . '</span>';

				// $nestedData['token']       = '<span style="font-size: 12px;">' . $post->token . '</span>';

				$nestedData['actions'] = "<a class='btn btn-success btn-sm' href='" . base_url('admin/user/edit_client/' . $post->id) . "'><i class='fa fa-pencil-square-o'></i></a><a class='btn btn-danger btn-sm delete' href='" . base_url('admin/user/delete/' . $post->id) . "' title='Delete'><i class='fa fa-trash-o'></i></a>";

				$data[] = $nestedData;
			}
		}

		$json_data = array(
			"draw"            => intval($this->input->post('draw')),
			"recordsTotal"    => intval($totalData),
			"recordsFiltered" => intval($totalFiltered),
			"data"            => $data
			// "data"            => $this->db->last_query()
		);

		echo json_encode($json_data);
	}

	// Change Status
	public function change_status()
	{
		$col = $this->input->post('col');
		$value = $this->input->post('value');
		$user_id = $this->input->post('user_id');

		$_value = 0;
		if ($value == 'true') {
			$_value = 1;
		}

		$data = array(
			"$col" => $_value
		);
		$this->db->where('id', $user_id);
		$this->db->update('users', $data);

		// echo $this->db->last_query();
		// exit;

		$arr = array();

		if ($this->db->affected_rows() > 0) {
			if ($col == 'registered') {
				if ($_value)
					$msg = "<div class='alert alert-warning' role='alert'>$user_id ID Set To Active!</div>";
				else
					$msg = "<div class='alert alert-success' role='alert'>$user_id ID Set To Reset!</div>";
			}
			if ($col == 'active') {
				if ($_value)
					$msg = "<div class='alert alert-success' role='alert'>$user_id ID Actived Now!</div>";
				else
					$msg = "<div class='alert alert-warning' role='alert'>$user_id ID de-actived Now!</div>";
			}

			$arr['status']      = 1;
			$arr['message']     = $msg;
			$arr['redirect_to'] = base_url('admin/user/index');
		} else {
			$msg = "<div class='alert alert-danger' role='alert'>Something went wrong, please try again!</div>";
			$arr['status']      = 0;
			$arr['message']     = $msg;
			$arr['redirect_to'] = base_url('admin/user/index');
		}
		echo json_encode($arr);
	}

	// delete
	public function delete($client_id)
	{
		$this->db->where('id', $client_id);
		$this->db->delete('users');

		if ($this->db->affected_rows() > 0) {
			$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">User deleted successfully!</div>');
		} else {
			$this->session->set_flashdata('message', '<div class="alert alert-info" role="alert">Something went wrong, Please try again.</div>');
		}
		redirect('admin/user/index');
	}

	public function popup()
	{
		$crud = $this->generate_crud('popups');
		$crud->columns('id', 'name', 'sort', 'image', 'isactive');
		$crud->set_field_upload('image', 'uploads');
		$this->unset_crud_fields('created');
		$this->mTitle = 'Users/Popups';
		$this->render_crud();
	}



	public function csvupdate()
	{
		if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_FILES['csv']['error'] == 0) {
			$csv = array();
			$err_csv = array();
			// $name = $_FILES['csv']['name'];
			// $type = $_FILES['csv']['type'];
			$tmpName = $_FILES['csv']['tmp_name'];

			// check the file is a csv
			if (($handle = fopen($tmpName, 'r')) !== FALSE) {
				// necessary if a large csv file
				set_time_limit(0);
				$row = 0;

				while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {

					$val1 = (isset($data[0]) && !empty(trim($data[0]))) ? trim($data[0]) : NULL;
					$val2 = (isset($data[1]) && !empty(trim($data[1]))) ? trim($data[1]) : NULL;
					$val3 = (isset($data[2]) && !empty(trim($data[2]))) ? trim($data[2]) : NULL;
					$val4 = (isset($data[3]) && !empty(trim($data[3]))) ? trim($data[3]) : NULL;
					$val5 = (isset($data[4]) && !empty(trim($data[4]))) ? trim($data[4]) : NULL;

					// get the values from the csv
					if (!empty($val1) && !empty($val2) && !empty($val3) && !empty($val4) && !empty($val5)) {
						//print_r($data);
						// number of fields in the csv
						$csv[$row]['col1'] = $val1;
						$csv[$row]['col2'] = $val2;
						$csv[$row]['col3'] = $val3;
						$csv[$row]['col4'] = $val4;
						$csv[$row]['col5'] = $val5;
					} else {
						$err_csv[$row]['col1'] = $val1;
						$err_csv[$row]['col2'] = $val2;
						$err_csv[$row]['col3'] = $val3;
						$err_csv[$row]['col4'] = $val4;
						$err_csv[$row]['col5'] = $val5;
					}
					// inc the row
					$row++;
				}
				fclose($handle);
			}



			if (count($csv) > 200) {
				$this->session->set_flashdata('e_message', '<div class="alert alert-danger"> Only 200 rows allowed in single CSV.</div>');
				redirect('admin/user/csvupdate');
			}

			if (count($err_csv) > 0) {
				$this->session->set_flashdata('e_message', '<div class="alert alert-danger">' . count($err_csv) . ' row has blank fields!, please fix it before upload.</div>');
				$this->session->set_flashdata('err_csv', $err_csv);
				//$this->mViewData['err_csv'] = $err_csv;
				redirect('admin/user/csvupdate');
			}



			if (count($csv) >= 2) {
				$updateArray = array();
				$i = 1;
				foreach ($csv as $cv) {
					if (!empty($cv['col1']) && !empty($cv['col2']) && !empty($cv['col3']) && !empty($cv['col4']) && !empty($cv['col5'])) {
						if ($i > 1) {
							$updateArray[] = array(
								"id"                => $cv['col1'],
								"username"          => $cv['col2'],
								'email'             => $cv['col3'],
								'phone'             => $cv['col4'],
								'aadharno'          => $cv['col5']
							);
						}
					}
					$i++;
				}

				$this->db->update_batch('users', $updateArray, 'id');

				// print_r($this->db->affected_rows());
				// exit;
				// Send Email
				$this->send_mail($updateArray);

				if (!empty($this->db->affected_rows())) {
					$this->session->set_flashdata('e_message', '<div class="alert alert-success">Total ' . $this->db->affected_rows() . ' CSV Records successfully Updated</div>');
				} else {
					$this->session->set_flashdata('e_message', '<div class="alert alert-success">CSV Already Updated!</div>');
				}
				redirect('admin/user/csvupdate');
			} else {
				$this->session->set_flashdata('e_message', '<div class="alert alert-danger">Blank CSV found!</div>');
				redirect('admin/user/csvupdate');
			}
		} else {
			$this->mTitle .= 'Users | CSV Update';
			$this->render('user/csv_update_view');
		}
	}

	public function send_mail($updateArray)
	{
		foreach ($updateArray as $user) {
			$query = $this->db->where('id', $user['id'])->get('users');
			if ($query->num_rows() > 0) { {
					$usersData = $query->row();
					// echo "<pre>";
					// print_r($usersData->email);
					// exit;
					// First, instantiate the SDK with your API credentials
					// $email_template = $this->parser->parse('mail/welcome', $usersData, TRUE);

					// $mgClient = new Mailgun('key-67e3665ae6d39301ffb42237f51e6aa9');
					// $domain = "mg.parasinstitute.com";
					// $result = $mgClient->sendMessage($domain, array(
					//     'from'    => 'ParasInstitute <noreply@parasinstitute.com>',
					//     'to'      => $usersData->email,
					//     //'cc'      => 'Vishal <vishal@globalexcell.co.in>',
					//     'subject' => 'Paras Institute - APP Login Details',
					//     'html'    => $email_template
					// ));
				}
			}
		}
	}

	public function tag()
	{
		$crud = $this->generate_crud('tags');
		$crud->where('admin_id', $this->session->userdata('user_id'));
		$crud->columns('id', 'tag', 'description', 'admin_id', 'created');

		$crud->set_relation('admin_id', 'admin_users', 'username');
		$this->unset_crud_fields('last_login');
		$crud->display_as('admin_id', 'Admin');

		if ($this->session->userdata('user_id') == 1) {
		} else {
			$crud->callback_add_field('admin_id', function () {
				return '<select id="admin_id" name="admin_id" class="chosen-select chzn-done" data-placeholder="Select Course" style="width: 300px; ">
                        <option  value="">--select--</option>
                        <option selected value="' . $this->session->userdata('user_id') . '">' . $this->session->userdata('username') . '</option>

                        </select>';
			});

			$crud->callback_add_field('last_update', function () {
				return '<input name="last_update" type="text" value="' . uniqid() . '" readonly /><br>'
					. '<i style="color:red;">auto generated field plz refresh if its blank!!!</i>';
			});

			$crud->callback_edit_field('last_update', function () {
				return '<input name="last_update" type="text" value="' . uniqid() . '" readonly /><br>'
					. '<i style="color:red;">auto generated field plz refresh if its blank!!!</i>';
			});

			$crud->callback_edit_field('admin_id', function () {
				return '<select id="admin_id" name="admin_id" class="chosen-select chzn-done" data-placeholder="Select Course" style="width: 300px; ">
                        <option  value="">--select--</option>
                        <option selected value="' . $this->session->userdata('user_id') . '">' . $this->session->userdata('username') . '</option>
                        </select>';
			});
			$crud->callback_before_insert(array($this, 'course_callback'));
		}

		$this->mTitle = 'Users/Tags';
		$this->render_crud();
	}

	public function course_callback($post_array)
	{
		$post_array['admin_id'] = $post_array['admin_id'];
		return $post_array;
	}

	// Frontend User CRUD
	public function idgenerator()
	{

		if (!empty($_POST)) {
			$len = $this->input->post('noofid');
			for ($i = 1; $i <= $len; $i++) {
				$additional_data = array(

					'admin_id' => $this->input->post('admin'),
					'ip_address' => $this->input->post('ipaddress'),
					'username' => $this->input->post('username') . $i,
					'password' => '12345',
					'salt' => $this->input->post('salt'),
					'email' => $this->input->post('emailid'),
					'registration_code' => uniqid(),
					'created_on' => date("Y-m-d h:i:sa"),
					'registered' => 0,
					'active' => 1,
					'first_name' => $this->input->post('fname'),
					'last_name' => $this->input->post('lname'),
					'company' => $this->input->post('company'),
					'phone' => $this->input->post('phone'),
				);

				$this->db->insert('users', $additional_data);

				$additional_data1 = array(
					'user_id' => $this->db->insert_id(),
					'group_id' => 3,
				);

				$this->db->insert('users_groups', $additional_data1);
				sleep(1);
			}
		}

		$this->mViewData['admins'] = $this->User_model->getadmin();

		$form = $this->form_builder->create_form();

		//$this->mViewData['groups'] = $groups;
		$this->mTitle .= 'Create Admin User';

		$this->mViewData['form'] = $form;
		$this->mTitle = 'ID Generator';
		$this->render('user/idgenerator');
	}
	// Frontend User CRUD
	public function all()
	{
		$crud = $this->generate_crud('users');
		$crud->columns('id', 'username', 'email', 'password', 'first_name', 'salt', 'active', 'registered', 'registration_code', 'admin_id', 'token');

		$crud->set_relation('admin_id', 'admin_users', 'username');
		$this->unset_crud_fields('last_login');
		$crud->display_as('admin_id', 'Admin');
		//$crud->feild_type('username','User Name','required');

		$crud->set_rules('admin_id', 'admin', 'required');
		$crud->set_rules('salt', 'salt', 'required');
		$crud->set_rules('username', 'User Name', 'required');
		$crud->set_rules('email', 'Email ID', 'valid_email|required');
		$crud->set_rules('first_name', 'First Name', 'required');
		$crud->set_rules('last_name', 'Last Name', 'required');
		$crud->set_rules('company', 'Company Name', 'required');
		$crud->set_rules('active', 'active/inactive', 'required');
		$crud->set_rules('registered', 'active/inactive', 'required');
		$crud->set_rules('phone', 'Phone Number', 'required');
		$crud->set_rules('registration_code', 'registration Number', 'required');

		//$crud->set_rules('Groups','Groups','required');

		$crud->field_type('id', 'readonly');
		$crud->field_type('ip_address', 'readonly');

		// only webmaster and admin can change member groups
		if ($crud->getState() == 'list' || $this->ion_auth->in_group(array('webmaster', 'admin'))) {
			$crud->set_relation_n_n('Groups', 'users_groups', 'groups', 'user_id', 'group_id', 'name');
		}

		// only webmaster and admin can reset user password
		if ($this->ion_auth->in_group(array('webmaster', 'admin'))) {
			$crud->add_action('Reset Password', '', 'admin/user/reset_password', 'fa fa-repeat');
		}
		// disable direct create / delete Frontend User
		//$crud->unset_add();
		//$crud->unset_delete();

		$crud->callback_add_field('registration_code', function () {
			return '<input type="text" name="registration_code" readonly id="registration_code"  value="' . uniqid() . '" /><br>'
				. '<i style="color:red;">auto generated field plz refresh if its blank!!!</i>';
		});

		$crud->callback_add_field('salt', function () {
			$qry = $this->db->where('admin_group_id', 2)->get('admin_users');
			$red = '<option value="" selected>-select-salt-</option>';
			foreach ($qry->result() as $rw) {
				$red .= "<option value=" . $rw->salt . ">" . $rw->username . "</option>";
			}
			return '<select  name="salt" id="salt"  />' . $red . '</select>';
		});

		$crud->callback_add_field('ip_address', function () {
			return '<input type="text" name="ip_address" id="ip_address" readonly value="' . $_SERVER['REMOTE_ADDR'] . '" />';
		});

		$crud->callback_before_insert(array($this, 'user_callback'));
		//$crud->callback_before_update(array($this, 'reset_token'));

		$this->mTitle = 'Users/Clients';
		$this->render_crud();
	}

	public function user_callback($post_array)
	{
		$post_array['registration_code'] = $post_array['registration_code'];
		$post_array['ip_address'] = $post_array['ip_address'];
		$post_array['salt'] = $post_array['salt'];
		return $post_array;
	}

	// public function index()
	// {
	// 	$crud = $this->generate_crud('users');
	// 	$crud->where('admin_id', $this->session->userdata('user_id'));
	// 	$crud->columns('id', 'tag_id', 'registration_code', 'username', 'email', 'password', 'aadharno', 'token', 'registered', 'active');
	// 	$this->unset_crud_fields('ip_address', 'last_login', 'admin_id', 'type', 'serialno', 'exp_date');

	// 	$crud->set_rules('username', 'User Name', 'required');
	// 	$crud->set_rules('email', 'Email ID', 'required');
	// 	$crud->set_rules('first_name', 'First Name', 'required');
	// 	$crud->set_rules('last_name', 'Last Name', 'required');
	// 	$crud->set_rules('company', 'Company Name', 'required');
	// 	$crud->set_rules('phone', 'Phone Number', 'required');

	// 	//$crud->set_rules('active', 'Active/Deactive', 'numeric|required');
	// 	$crud->set_rules('admin_id', 'Admin ID', 'numeric|required');

	// 	$crud->field_type('registration_code', 'readonly');
	// 	$crud->field_type('salt', 'readonly');
	// 	$crud->field_type('id', 'readonly');

	// 	$state = $crud->getState();

	// 	if ($state === 'add') {
	// 		$crud->field_type('admin_id', 'hidden', $this->mUser->id);
	// 		$this->unset_crud_fields('status');
	// 	}

	// 	$crud->add_action('Edit', '', 'admin/user/edit_client', 'edit-icon');

	// 	// only webmaster and admin can reset user password
	// 	if ($this->ion_auth->in_group(array('webmaster', 'admin'))) {
	// 		$crud->add_action('Reset Password', '', 'admin/user/reset_password', 'fa fa-repeat');
	// 	}
	// 	$crud->callback_column('tag_id', array($this, 'tags_field_add_callback'));
	// 	$crud->callback_before_update(array($this, 'reset_token'));
	// 	$crud->unset_add();
	// 	$crud->unset_edit();

	// 	$this->mTitle = 'Users';
	// 	$this->render_crud();
	// }

	function tags_field_add_callback($value, $row)
	{
		$Query = $this->db->where_in('id', explode(',', $value))->get('tags');
		if ($Query->num_rows() > 0) {
			$rows = $Query->result();
			$tags = [];
			foreach ($rows as $row) {
				$tags[] = $row->tag;
			}
			return implode(",<br>", $tags);
		}
		return "";
	}

	// function reset_token($post_array)
	// {
	//     print_r($post_array);exit;
	//     if ($post_array[registered]) { } else {
	//         $post_array['token'] = uniqid();
	//     }
	//     return $post_array;
	// }

	public function edit_client($client_id = null)
	{
		if (empty($client_id)) {
			redirect('admin/user/index', 'refresh');
		}

		if ($this->session->userdata('user_id') == 1) {
			$admin_id = null;
		} else {
			$admin_id = $this->session->userdata('user_id');
		}

		$registered_old = 0;
		$this->db->where('users.id', $client_id);
		$query = $this->db->get('users');

		if ($query->num_rows() > 0) {
			$res = $query->result();
			$registered_old = $res[0]->registered;
		}

		if (isset($_POST) && !empty($_POST)) {
			//print_r($_POST);exit;
			$username = $this->input->post('username');
			$email = $this->input->post('email');
			$registered = ($this->input->post('registered')) ? $this->input->post('registered') : 0;
			$active = ($this->input->post('active')) ? $this->input->post('active') : 0;
			$first_name = $this->input->post('first_name');
			$last_name = $this->input->post('last_name');
			$admission_code = $this->input->post('admission_code');
			$phone = $this->input->post('phone');
			$aadharno = $this->input->post('aadharno');
			$group_id = $this->input->post('user_group');

			$u_data['username'] = $username;
			$u_data['email'] = $email;
			$u_data['active'] = $active;
			$u_data['first_name'] = $first_name;
			$u_data['last_name'] = $last_name;
			$u_data['admission_code'] = $admission_code;
			$u_data['phone'] = $phone;
			$u_data['aadharno'] = $aadharno;
			$u_data['tag_id'] = "";
			if (!empty($group_id)) {
				$u_data['tag_id'] = implode(',', $group_id);
			}

			if ($registered_old != $registered) {
				$u_data['registered'] = $registered;
				$u_data['token'] = uniqid();
			}

			$this->db->where('users.id', $client_id);

			if (!empty($admin_id)) {
				$this->db->where('users.admin_id', $admin_id);
			}

			$this->db->set($u_data);
			$this->db->update('users');

			if ($this->db->affected_rows() > 0) {
				$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Record updated successfully!</div>');
				redirect('admin/user/edit_client/' . $client_id, 'refresh');
			} else {
				$this->session->set_flashdata('message', '<div class="alert alert-info" role="alert">You have made no changes!</div>');
				redirect('admin/user/edit_client/' . $client_id, 'refresh');
			}
		} else {
			$this->db->select('users.*');
			$this->db->where('users.id', $client_id);

			if (!empty($admin_id)) {
				$this->db->where('users.admin_id', $admin_id);
			}

			$query = $this->db->get('users', 1);
			$adminID = $this->session->userdata('user_id');
			$query2 = $this->db->where('admin_id', $adminID)->get('tags');

			if ($query->num_rows() > 0) {
				$this->mViewData['client'] = $query->row();
				$this->mViewData['groups'] = $query2->result();

				$allgroups = $this->mViewData['groups'];
				$groups = array();
				foreach ($allgroups as $group) {
					array_push($groups, $group->id);
				}
				$client = $query->row();

				$selected = explode(',', $client->tag_id);
				$nonselected = array_diff($groups, $selected);

				$this->mViewData['selected_groups'] = $this->get_tags_where_in($selected, $adminID);
				$this->mViewData['non_selected_groups'] = $this->get_tags_where_in($nonselected, $adminID);

				$this->mTitle .= ' | Edit Client';

				$this->render('user/edit_client');
			} else {
				$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Record did not found!</div>');
				redirect('admin/user/index', 'refresh');
			}
		}
	}

	public function get_tags_where_in($tagID, $adminID)
	{
		if (!empty($tagID)) {
			$this->db->where('admin_id', $adminID);
			$this->db->where_in('id', $tagID);
			$query = $this->db->get('tags');
			if ($query->num_rows() > 0) {
				return $query->result();
			}
		}
		return false;
	}

	// Create Frontend User
	public function create()
	{
		$form = $this->form_builder->create_form();

		if ($form->validate()) {
			// passed validation
			$username = $this->input->post('username');
			$email = $this->input->post('email');
			$password = $this->input->post('password');
			$identity = empty($username) ? $email : $username;
			$additional_data = array(
				'first_name' => $this->input->post('first_name'),
				'last_name' => $this->input->post('last_name'),
			);
			$groups = $this->input->post('groups');

			// [IMPORTANT] override database tables to update Frontend Users instead of Admin Users
			$this->ion_auth_model->tables = array(
				'users' => 'users',
				'groups' => 'groups',
				'users_groups' => 'users_groups',
				'login_attempts' => 'login_attempts',

			);

			// proceed to create user
			$user_id = $this->ion_auth->register($identity, $password, $email, $additional_data, $groups);
			if ($user_id) {
				// success
				$messages = $this->ion_auth->messages();
				$this->system_message->set_success($messages);

				// directly activate user
				$this->ion_auth->activate($user_id);
			} else {
				// failed
				$errors = $this->ion_auth->errors();
				$this->system_message->set_error($errors);
			}
			refresh();
		}

		// get list of Frontend user groups
		$this->load->model('group_model', 'groups');

		//$this->mViewData['groups'] = $this->groups->get_all();
		$this->mViewData['admin_users'] = $this->groups->get_admin_users();
		$this->mTitle = 'Create User';

		$this->mViewData['form'] = $form;
		$this->render('user/create');
	}

	// User Groups CRUD
	public function group()
	{
		$crud = $this->generate_crud('groups');
		$this->mTitle = 'User Groups';
		$this->render_crud();
	}

	public function addgroup()
	{
		$admin_id = $this->session->userdata('user_id');
		$tag = $this->session->userdata('group_name');
		$desc = $this->session->userdata('group_description');

		if (empty($admin_id) && empty($tag) && empty($desc)) {
			$msg = validation_errors();
			$code = 400;
			print_r('asdsad');
			exit;
		} else {
			$data = array(
				'admin_id' => $admin_id,
				'tag' => $this->input->post('group_name'),
				'description' => $this->input->post('group_description'),
			);

			$resp = $this->db->insert('tags', $data);

			if ($resp) {
				$msg = 'Tags is added sucessfully!';
				$code = 200;
			} else {
				$msg = 'Something went wrong!';
				$code = 400;
			}
		}

		$arr = array(
			'msg' => $msg,
			'code' => $code,
		);

		echo json_encode($arr);
		//
	}

	// Frontend User Reset Password
	public function reset_password($user_id)
	{
		// only top-level users can reset user passwords
		$this->verify_auth(array('webmaster', 'admin'));

		$form = $this->form_builder->create_form();
		if ($form->validate()) {
			// pass validation
			$data = array('password' => $this->input->post('new_password'));

			// [IMPORTANT] override database tables to update Frontend Users instead of Admin Users
			$this->ion_auth_model->tables = array(
				'users' => 'users',
				'groups' => 'groups',
				'users_groups' => 'users_groups',
				'login_attempts' => 'login_attempts',
			);

			// proceed to change user password
			if ($this->ion_auth->update($user_id, $data)) {
				$messages = $this->ion_auth->messages();
				$this->system_message->set_success($messages);
			} else {
				$errors = $this->ion_auth->errors();
				$this->system_message->set_error($errors);
			}
			refresh();
		}

		$this->load->model('user_model', 'users');
		$target = $this->users->get($user_id);
		$this->mViewData['target'] = $target;

		$this->mViewData['form'] = $form;
		$this->mTitle = 'Reset User Password';
		$this->render('user/reset_password');
	}


	// multiple delete
	public function delete_all()
	{
		$arr = [];

		if (empty($this->session->userdata('user_id'))) {
			$arr['status']      = 0;
			$arr['message']     = '<div class="alert alert-danger" role="alert">You session has expired!,/div>';
			$arr['redirect_to'] = base_url('admin/login');

			goto D_L_A;
		}

		if ($this->session->userdata('user_id') == 1) {
			$admin_id = null;
		} else {
			$admin_id = $this->session->userdata('user_id');
		}

		$user_ids = $this->input->post('user_ids');

		if ($user_ids) {
			$affected_rows = 0;

			foreach ($user_ids as $user_id) {
				$this->db->where('users.id', $user_id);
				$this->db->where('users.admin_id', $admin_id);
				$this->db->delete('users');

				$affected_rows += $this->db->affected_rows();
			}

			if ($affected_rows > 0) {
				$arr['status']      = 1;
				$arr['message']     = '';

				$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">' . $affected_rows . ' user successfully deleted!</div>');

				goto D_L_A;
			}

			$arr['status']      = 0;
			$arr['message']     = '<div class="alert alert-danger" role="alert">Something went wrong!/div>';
		}

		D_L_A:
		echo json_encode($arr);
	}

	// multiple delete
	public function remove_tags()
	{
		$arr = [];

		if (empty($this->session->userdata('user_id'))) {
			$arr['status']      = 0;
			$arr['message']     = '<div class="alert alert-danger" role="alert">You session has expired!,/div>';
			$arr['redirect_to'] = base_url('admin/login');

			goto D_L_A;
		}

		$user_ids = $this->input->post('user_ids');
		$tag_id = $this->input->post('tag_id');

		$affected_rows = 0;
		if (!empty($user_ids) && !empty($tag_id)) {

			$usersids = implode(',', $user_ids);
			$SQL = "UPDATE users SET tag_id = replace(replace(tag_id, '$tag_id', ''), ',,', '') WHERE users.id IN($usersids)";
			$this->db->query($SQL);

			$affected_rows += $this->db->affected_rows();

			if ($affected_rows > 0) {
				$arr['status']      = 1;
				$arr['message']     = '';
				$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">' . $affected_rows . ' user tag successfully removed!</div>');

				goto D_L_A;
			}

			$arr['status']      = 0;
			$arr['message']     = '<div class="alert alert-danger" role="alert">Something went wrong!/div>';
		}

		D_L_A:
		echo json_encode($arr);
	}

	public function csv_export()
	{
		$SQL = "SELECT id,tag_id, registration_code, registered, active, username, password, aadharno, email, phone, first_name, last_name, admission_code FROM users";

		if (isset($_GET['tag_id'])) {
			$tag = $_GET['tag_id'];
			$SQL = "SELECT id,tag_id, registration_code, registered, active, username, password, aadharno, email, phone, first_name, last_name, admission_code FROM users WHERE tag_id REGEXP '(^|,)$tag(,|$)'";
		}
		$Query = $this->db->query($SQL);
		// print_r($Query->num_rows());
		// exit;
		if ($Query->num_rows() > 0) {
			$data = $Query->result_array();
			$uid = uniqid();
			header("Content-type: application/csv");
			header("Content-Disposition: attachment; filename=\"$uid" . ".csv\"");
			header("Pragma: no-cache");
			header("Expires: 0");
			$handle = fopen('php://output', 'w');

			// Header
			$header = ['id', 'tag_id', 'registration_code', 'registered', 'active', 'username', 'password', 'aadharno', 'email', 'phone', 'first_name', 'last_name', 'admission_code'];
			fputcsv($handle, $header);
			foreach ($data as $data_array) {
				fputcsv($handle, $data_array);
			}
			fclose($handle);
			exit;
		}
	}
}

Anon7 - 2021