Advertisement
Guest User

Untitled

a guest
Nov 26th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.52 KB | None | 0 0
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed.');
  2.  
  3. /**
  4.  * Admins_Model Class
  5.  *
  6.  * Handles the database actions for admin users management.
  7.  *
  8.  * Data Structure:
  9.  *      'fist_name'
  10.  *      'last_name' (required)
  11.  *      'email' (required)
  12.  *      'mobile_number'
  13.  *      'phone_number' (required)
  14.  *      'address'
  15.  *      'city'
  16.  *      'state'
  17.  *      'zip_code'
  18.  *      'notes'
  19.  *      'id_roles'
  20.  *      'settings' >>> array that contains user settings (username, password etc)
  21.  */
  22. class Admins_Model extends CI_Model {
  23.     /**
  24.      * Class Constructor
  25.      */
  26.     public function __construct() {
  27.         parent::__construct();
  28.     }
  29.    
  30.     /**
  31.      * Add (insert or update) an admin user record into database.
  32.      *
  33.      * @param array $admin Contains the admin user data.
  34.      * @return int Returns the record id.
  35.      * @throws Exception When the admin data are invalid (see validate() method).
  36.      */
  37.     public function add($admin) {
  38.         $this->validate($admin);
  39.        
  40.         if ($this->exists($admin) && !isset($admin['id'])) {
  41.             $admin['id'] = $this->find_record_id($admin);
  42.         }
  43.        
  44.         if (!isset($admin['id'])) {
  45.             $admin['id'] = $this->insert($admin);
  46.         } else {
  47.             $admin['id'] = $this->update($admin);
  48.         }
  49.        
  50.         return intval($admin['id']);
  51.     }
  52.    
  53.     /**
  54.      * Check whether a particular admin record exists in the database.
  55.      *
  56.      * @param array $admin Contains the admin data. The 'email' value is required to be present
  57.      * at the moment.
  58.      * @return bool Returns whether the record exists or not.
  59.      * @throws Exception When the 'email' value is not present on the $admin argument.
  60.      */
  61.     public function exists($admin) {
  62.         if (!isset($admin['email'])) {
  63.             throw new Exception('Admin email is not provided: ' . print_r($admin, TRUE));
  64.         }
  65.        
  66.         // This method shouldn't depend on another method of this class.
  67.         $num_rows = $this->db
  68.                 ->select('*')
  69.                 ->from('ea_users')
  70.                 ->join('ea_roles', 'ea_roles.id = ea_users.id_roles', 'inner')
  71.                 ->where('ea_users.email', $admin['email'])
  72.                 ->where('ea_roles.slug', DB_SLUG_ADMIN)
  73.                 ->get()->num_rows();
  74.        
  75.         return ($num_rows > 0) ? TRUE : FALSE;
  76.     }
  77.    
  78.     /**
  79.      * Insert a new admin record into the database.
  80.      *
  81.      * @param array $admin Contains the admin data.
  82.      * @return int Returns the new record id.
  83.      * @throws Exception When the insert operation fails.
  84.      */
  85.     public function insert($admin) {
  86.         $this->load->helper('general');
  87.        
  88.         $admin['id_roles'] = $this->get_admin_role_id();
  89.         $settings = $admin['settings'];
  90.         unset($admin['settings']);
  91.        
  92.         $this->db->trans_begin();        
  93.        
  94.         if (!$this->db->insert('ea_users', $admin)) {
  95.             throw new Exception('Could not insert admin into the database.');
  96.         }
  97.        
  98.         $admin['id'] = intval($this->db->insert_id());
  99.         $settings['id_users'] = $admin['id'];
  100.         $settings['salt'] = generate_salt();
  101.         $settings['password'] = hash_password($settings['salt'], $settings['password']);
  102.        
  103.         // Insert admin settings.
  104.         if (!$this->db->insert('ea_user_settings', $settings)) {
  105.             $this->db->trans_rollback();
  106.             throw new Exception('Could not insert admin settings into the database.');
  107.         }
  108.        
  109.         $this->db->trans_complete();
  110.        
  111.         return $admin['id'];
  112.     }  
  113.    
  114.     /**
  115.      * Update an existing admin record in the database.
  116.      *
  117.      * @param array $admin Contains the admin record data.
  118.      * @return int Retuns the record id.
  119.      * @throws Exception When the update operation fails.
  120.      */
  121.     public function update($admin) {
  122.         $this->load->helper('general');
  123.        
  124.         $settings = $admin['settings'];
  125.         unset($admin['settings']);
  126.         $settings['id_users'] = $admin['id'];
  127.        
  128.         if (isset($settings['password'])) {
  129.             $salt = $this->db->get_where('ea_user_settings', array('id_users' => $admin['id']))->row()->salt;
  130.             $settings['password'] = hash_password($salt, $settings['password']);
  131.         }
  132.        
  133.         $this->db->where('id', $admin['id']);
  134.         if (!$this->db->update('ea_users', $admin)) {
  135.             throw new Exception('Could not update admin record.');
  136.         }
  137.        
  138.         $this->db->where('id_users', $settings['id_users']);
  139.         if (!$this->db->update('ea_user_settings', $settings)) {
  140.             throw new Exception('Could not update admin settings.');
  141.         }
  142.        
  143.         return intval($admin['id']);
  144.     }
  145.    
  146.     /**
  147.      * Find the database record id of an admin user.
  148.      *
  149.      * @param array $admin Contains the admin data. The 'email' value is required in order to
  150.      * find the record id.
  151.      * @return int Returns the record id
  152.      * @throws Exception When the 'email' value is not present on the $admin array.
  153.      */
  154.     public function find_record_id($admin) {
  155.         if (!isset($admin['email'])) {
  156.             throw new Exception('Admin email was not provided: ' . print_r($admin, TRUE));
  157.         }
  158.        
  159.         $result = $this->db
  160.                 ->select('ea_users.id')
  161.                 ->from('ea_users')
  162.                 ->join('ea_roles', 'ea_roles.id = ea_users.id_roles', 'inner')
  163.                 ->where('ea_users.email', $admin['email'])
  164.                 ->where('ea_roles.slug', DB_SLUG_ADMIN)
  165.                 ->get();
  166.        
  167.         if ($result->num_rows() == 0) {
  168.             throw new Exception('Could not find admin record id.');
  169.         }
  170.        
  171.         return intval($result->row()->id);
  172.     }
  173.    
  174.     /**
  175.      * Validate admin user data before add() operation is executed.
  176.      *
  177.      * @param array $admin Contains the admin user data.
  178.      * @return bool Returns the validation result.
  179.      *
  180.      * @throws Exception When data are invalid.
  181.      */
  182.     public function validate($admin) {
  183.         $this->load->helper('data_validation');
  184.  
  185.         // If a record id is provided then check whether the record exists in the database.
  186.         if (isset($admin['id'])) {
  187.             $num_rows = $this->db->get_where('ea_users', array('id' => $admin['id']))
  188.                     ->num_rows();
  189.             if ($num_rows == 0) {
  190.                 throw new Exception('Given admin id does not exist in database: ' . $admin['id']);
  191.             }
  192.         }
  193.  
  194.         // Validate required fields integrity.
  195.         if (!isset($admin['last_name'])
  196.                 || !isset($admin['email'])
  197.                 || !isset($admin['phone_number'])) {
  198.             throw new Exception('Not all required fields are provided : ' . print_r($admin, TRUE));
  199.         }
  200.  
  201.         // Validate admin email address.
  202.         if (!filter_var($admin['email'], FILTER_VALIDATE_EMAIL)) {
  203.             throw new Exception('Invalid email address provided : ' . $admin['email']);
  204.         }
  205.        
  206.         // Check if username exists.
  207.         if (isset($admin['settings']['username'])) {
  208.             $user_id = (isset($admin['id'])) ? $admin['id'] : '';
  209.             if (!$this->validate_username($admin['settings']['username'], $user_id)) {
  210.                 throw new Exception ('Username already exists. Please select a different '
  211.                         . 'username for this record.');
  212.             }
  213.         }
  214.  
  215.         // Validate admin password
  216.         if (isset($admin['settings']['password'])) {
  217.             if (strlen($admin['settings']['password']) < MIN_PASSWORD_LENGTH) {
  218.                 throw new Exception('The user password must be at least '
  219.                         . MIN_PASSWORD_LENGTH . ' characters long.');
  220.             }
  221.         }
  222.        
  223.         // When inserting a record the email address must be unique.
  224.         $admin_id = (isset($admin['id'])) ? $admin['id'] : '';
  225.        
  226.         $num_rows = $this->db
  227.                 ->select('*')
  228.                 ->from('ea_users')
  229.                 ->join('ea_roles', 'ea_roles.id = ea_users.id_roles', 'inner')
  230.                 ->where('ea_roles.slug', DB_SLUG_ADMIN)
  231.                 ->where('ea_users.email', $admin['email'])
  232.                 ->where('ea_users.id <>', $admin_id)
  233.                 ->get()
  234.                 ->num_rows();
  235.        
  236.         if ($num_rows > 0) {
  237.             throw new Exception('Given email address belongs to another admin record. '
  238.                     . 'Please use a different email.');
  239.         }
  240.            
  241.         return TRUE; // Operation completed successfully.
  242.     }
  243.    
  244.     /**
  245.      * Delete an existing admin record from the database.
  246.      *
  247.      * @param numeric $admin_id The admin record id to be deleted.
  248.      * @return bool Returns the delete operation result.
  249.      * @throws Exception When the $admin_id is not a valid numeric value.
  250.      * @throws Exception When the record to be deleted is the only one admin user left on
  251.      * the system.
  252.      */
  253.     public function delete($admin_id) {
  254.         if (!is_numeric($admin_id)) {
  255.             throw new Exception('Invalid argument type $admin_id : ' . $admin_id);
  256.         }
  257.        
  258.         // There must be always at least one admin user. If this is the only admin
  259.         // the system, it cannot be deleted.
  260.         $admin_count = $this->db->get_where('ea_users',
  261.                 array('id_roles' => $this->get_admin_role_id()))->num_rows();
  262.         if ($admin_count == 1) {
  263.             throw new Exception('Record could not be deleted. The system requires at least '
  264.                     . 'one admin user.');
  265.         }
  266.        
  267.         $num_rows = $this->db->get_where('ea_users', array('id' => $admin_id))->num_rows();
  268.         if ($num_rows == 0) {
  269.             return FALSE; // Record does not exist in database.
  270.         }
  271.        
  272.         return $this->db->delete('ea_users', array('id' => $admin_id));
  273.     }
  274.    
  275.     /**
  276.      * Get a specific admin record from the database.
  277.      *
  278.      * @param numeric $admin_id The id of the record to be returned.
  279.      * @return array Returns an array with the admin user data.
  280.      * @throws Exception When the $admin_id is not a valid numeric value.
  281.      */
  282.     public function get_row($admin_id) {
  283.         if (!is_numeric($admin_id)) {
  284.             throw new Exception('$admin_id argument is not a valid numeric value: ' . $admin_id);
  285.         }
  286.  
  287.         // Check if record exists
  288.         if ($this->db->get_where('ea_users', array('id' => $admin_id))->num_rows() == 0) {
  289.             throw new Exception('The given admin id does not match a record in the database.');
  290.         }
  291.        
  292.         $admin = $this->db->get_where('ea_users', array('id' => $admin_id))->row_array();
  293.        
  294.         $admin['settings'] = $this->db->get_where('ea_user_settings',
  295.                 array('id_users' => $admin_id))->row_array();
  296.         unset($admin['settings']['id_users']);
  297.        
  298.        
  299.         return $admin;
  300.     }
  301.    
  302.     /**
  303.      * Get a specific field value from the database.
  304.      *
  305.      * @param string $field_name The field name of the value to be returned.
  306.      * @param numeric $admin_id Record id of the value to be returned.
  307.      * @return string Returns the selected record value from the database.
  308.      * @throws Exception When the $field_name argument is not a valid string.
  309.      * @throws Exception When the $admin_id is not a valid numeric.
  310.      * @throws Exception When the admin record does not exist in the database.
  311.      * @throws Exception When the selected field value is not present on database.
  312.      */
  313.     public function get_value($field_name, $admin_id) {
  314.         if (!is_string($field_name)) {
  315.             throw new Exception('$field_name argument is not a string : ' . $field_name);
  316.         }
  317.        
  318.         if (!is_numeric($admin_id)) {
  319.             throw new Exception('$admin_id argument is not a valid numeric value: ' . $admin_id);
  320.         }
  321.        
  322.         // Check whether the admin record exists.
  323.         $result = $this->db->get_where('ea_users', array('id' => $admin_id));
  324.         if ($result->num_rows() == 0) {
  325.             throw new Exception('The record with the given id does not exist in the '
  326.                     . 'database : ' . $admin_id);
  327.         }
  328.        
  329.         // Check if the required field name exist in database.
  330.         $provider = $result->row_array();
  331.         if (!isset($provider[$field_name])) {
  332.             throw new Exception('The given $field_name argument does not exist in the '
  333.                     . 'database: ' . $field_name);
  334.         }
  335.        
  336.         return $provider[$field_name];
  337.     }
  338.    
  339.     /**
  340.      * Get all, or specific admin records from database.
  341.      *
  342.      * @param string|array $where_clause (OPTIONAL) The WHERE clause of the query to be executed.
  343.      * Use this to get specific admin records.
  344.      * @return array Returns an array with admin records.
  345.      */
  346.     public function get_batch($where_clause = '') {
  347.         $role_id = $this->get_admin_role_id();
  348.        
  349.         if ($where_clause != '') {
  350.             $this->db->where($where_clause);
  351.         }
  352.        
  353.         $batch = $this->db->get_where('ea_users', array('id_roles' => $role_id))->result_array();
  354.        
  355.         // Get every admin settings.
  356.         foreach ($batch as &$admin) {
  357.             $admin['settings'] = $this->db->get_where('ea_user_settings',
  358.                     array('id_users' => $admin['id']))->row_array();
  359.             unset($admin['settings']['id_users']);
  360.         }
  361.        
  362.         return $batch;
  363.     }
  364.    
  365.     /**
  366.      * Get the admin users role id.
  367.      *
  368.      * @return int Returns the role record id.
  369.      */
  370.     public function get_admin_role_id()
  371.     {
  372.         $result = intval($this->db->get_where('ea_roles', array('slug' => DB_SLUG_ADMIN))->row()->id);
  373.         print_r($result);
  374.         return $result;
  375.     }
  376.    
  377.     /**
  378.      * Validate Records Username
  379.      *
  380.      * @param string $username The provider records username.
  381.      * @param numeric $user_id The user record id.
  382.      * @return bool Returns the validation result.
  383.      */
  384.     public function validate_username($username, $user_id) {
  385.         $num_rows = $this->db->get_where('ea_user_settings',
  386.                 array('username' => $username, 'id_users <> ' => $user_id))->num_rows();
  387.         return ($num_rows > 0) ? FALSE : TRUE;
  388.     }
  389. }
  390.  
  391. /* End of file admins_model.php */
  392. /* Location: ./application/models/admins_model.php */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement