4 * Class Users_model models user information from DB
10 class Users_model extends CI_Model {
13 public function __construct()
15 parent::__construct();
17 if ($this->db === NULL)
19 $this->load->library('singleton_db');
20 $this->db = $this->singleton_db->connect();
25 * Check authentication credentials. $username can be username or e-mail.
27 * @param string $username
28 * @param string $password
29 * @return mixed can return FALSE if authentication failed, a DB row as an
30 * associative array if authentication was succesful or an associative
31 * array with LDAP user information if authentication with LDAP was
32 * successful but the user logged in for the first time and it does not
33 * have an entry in `users` table yet. The key 'auth_src' distinguishes
34 * which associative array was returned:
36 * <li>'internal' or 'ldap': a DB row</li>
37 * <li>'ldap_first_time': LDAP user information</li>
40 public function login($username, $password)
42 $this->load->helper('email');
44 // User logs with e-mail address.
45 if (! valid_email($username))
46 $cond_user = "username = '$username'";
48 $cond_user = "email = '$username'";
50 $enc_password = sha1($password);
52 // TODO select only required fields.
53 $query = $this->db->query("SELECT u.*, a.activation_code
54 FROM `users` u LEFT JOIN `users_unactivated` a ON (u.id = a.user_id)
56 AND (auth_src = 'ldap' OR password = '$enc_password')");
58 // It is possible that the user has a LDAP account but he's
59 // authenticating here for the first time so it does not have an entry
61 if ($query->num_rows() === 0)
63 $ldap_userdata = $this->ldap_login($username, $password);
64 if ($ldap_userdata === FALSE)
66 $userdata = $this->convert_ldap_userdata($ldap_userdata);
67 $this->register($userdata);
69 $user = $this->login($username, $password);
70 $user['import'] = TRUE;
74 $user = $query->row_array();
76 // Authenticate with LDAP.
77 if ($user['auth_src'] == 'ldap'
78 && ! $this->ldap_login($username, $password))
81 // Update last login time.
82 $this->db->query("UPDATE `users`
83 SET last_login = UTC_TIMESTAMP()
84 WHERE username = '$username'");
86 // If we are here internal authentication has successful.
91 * Converts an array returned by LDAP login to an array which contains
92 * user data ready to be used in `users` DB.
94 * @param array $ldap_userdata
97 public function convert_ldap_userdata($ldap_userdata)
99 $userdata['username'] = $ldap_userdata['uid'][0];
100 $userdata['email'] = $ldap_userdata['mail'][0];
101 $userdata['first_name'] = $ldap_userdata['givenname'][0];
102 $userdata['last_name'] = $ldap_userdata['sn'][0];
104 $userdata['auth_src'] = 'ldap';
112 * @param string $username
113 * @param string $password
115 * @author Alex Herișanu, Răzvan Deaconescu, Călin-Andrei Burloiu
117 public function ldap_login($username, $password)
119 $this->config->load('ldap');
121 // First connection: binding.
123 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server.\n");
124 if (!@ldap_bind($ds, $this->config->item('ldap_bind_user'),
125 $this->config->item('ldap_bind_password')))
128 die("Can't connect to ".$this->config->item('ldap_server')."\n");
131 $sr = ldap_search($ds, "dc=cs,dc=curs,dc=pub,dc=ro", "(uid=" . $username . ")");
132 if (ldap_count_entries($ds, $sr) > 1)
133 die("Multiple entries with the same uid in LDAP database??");
134 if (ldap_count_entries($ds, $sr) < 1) {
139 $info = ldap_get_entries($ds, $sr);
140 $dn = $info[0]["dn"];
143 // Second connection: connect with user's credentials.
144 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server\n");
145 if (!@ldap_bind($ds, $dn, $password) or $password == '') {
150 // Verifify if DN belongs to the requested OU.
151 $info[0]['ou_ok'] = $this->ldap_dn_belongs_ou( $dn, $this->config->item('ldap_req_ou') );
153 // Set authentication source.
154 $info[0]['auth_src'] = 'ldap_first_time';
160 * Verify if a user belongs to a group.
162 * @param string $dn = "ou=Student,ou=People..."
163 * @param array $ou = array ("Student", etc
164 * @return TRUE or FALSE
165 * @author Răzvan Herișanu, Răzvan Deaconescu, Călin-Andrei Burloiu
167 public function ldap_dn_belongs_ou($dn, $ou)
173 $words = explode(',', $dn);
174 foreach ($words as $c) {
175 $parts = explode("=", $c);
179 if (strtolower($key) == "ou" && in_array($value, $ou) )
187 * Adds a new user to DB.
188 * Do not add join_date and last_login column, they will be automatically
191 * @param array $data corresponds to DB columns
193 public function register($data)
195 $this->load->helper('array');
197 // TODO verify mandatory data existance
200 if (isset($data['password']))
201 $data['password'] = sha1($data['password']);
202 // TODO picture data: save, convert, make it thumbnail
206 foreach ($data as $col=> $val)
214 $cols = substr($cols, 0, -2);
215 $vals = substr($vals, 0, -2);
217 $query = $this->db->query("INSERT INTO `users`
218 ($cols, registration_date, last_login)
219 VALUES ($vals, utc_timestamp(), utc_timestamp())");
221 if ($query === FALSE)
224 // If the registered with internal authentication it needs to activate
226 $activation_code = Users_model::gen_activation_code();
227 $user_id = $this->get_user_id($data['username']);
228 $query = $this->db->query("INSERT INTO `users_unactivated`
229 (user_id, activation_code)
230 VALUES ($user_id, '$activation_code')");
232 // TODO exception on failure
236 public function get_user_id($username)
238 $query = $this->db->query("SELECT id FROM `users`
239 WHERE username = '$username'");
241 if ($query->num_rows() === 0)
244 return $query->row()->id;
247 // TODO cleanup account activation
248 public function cleanup_account_activation()
254 * Activated an account for an user having $user_id with $activation_code.
256 * @param int $user_id
257 * @param string $activation_code hexa 16 characters string
258 * @return returns TRUE if activation was successful and FALSE otherwise
260 public function activate_account($user_id, $activation_code)
262 $query = $this->db->query("SELECT * FROM `users_unactivated`
263 WHERE user_id = $user_id
264 AND activation_code = '$activation_code'");
266 if ($query->num_rows() === 0)
269 $this->db->query("DELETE FROM `users_unactivated`
270 WHERE user_id = $user_id");
276 * Returns data from `users` table. If $user is int it is used as an
277 * id, if it is string it is used as an username.
281 public function get_userdata($user)
284 $cond = "id = $user";
286 $cond = "username = '$user'";
288 $query = $this->db->query("SELECT * from `users`
291 if ($query->num_rows() === 0)
294 return $query->row_array();
298 * Modifies data from `users` table for user with $user_id.
300 * @param int $user_id
301 * @param array $data key-value pairs with columns and new values to be
304 public function set_userdata($user_id, $data)
306 // TODO verify mandatory data existance
309 if (isset($data['password']))
310 $data['password'] = sha1($data['password']);
311 // TODO picture data: save, convert, make it thumbnail
314 foreach ($data as $col => $val)
317 $set .= "$col = $val, ";
319 $set .= "$col = '$val', ";
321 $set = substr($set, 0, -2);
323 $query_str = "UPDATE `users`
324 SET $set WHERE id = $user_id";
325 //echo "<p>$query_str</p>";
326 $query = $this->db->query($query_str);
332 public static function gen_activation_code($str = '')
334 $ci =& get_instance();
336 $activation_code = substr(
337 sha1(''. $str. $ci->config->item('encryption_key')
342 return $activation_code;
345 public static function roles_to_string($roles)
347 $ci =& get_instance();
348 $ci->lang->load('user');
350 if ($roles == USER_ROLE_STANDARD)
351 return $ci->lang->line('user_role_standard');
356 if ($roles & USER_ROLE_ADMIN)
357 $str_roles .= $ci->lang->line('user_role_admin') . '; ';
364 /* End of file users_model.php */
365 /* Location: ./application/models/users_model.php */