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)
218 else if (is_string($val))
221 $cols = substr($cols, 0, -2);
222 $vals = substr($vals, 0, -2);
224 $query = $this->db->query("INSERT INTO `users`
225 ($cols, registration_date, last_login)
226 VALUES ($vals, utc_timestamp(), utc_timestamp())");
227 if ($query === FALSE)
230 // If registered with internal authentication it needs to activate
232 $activation_code = Users_model::gen_activation_code($data['username']);
233 $user_id = $this->get_user_id($data['username']);
234 $query = $this->db->query("INSERT INTO `users_unactivated`
235 (user_id, activation_code)
236 VALUES ($user_id, '$activation_code')");
237 $this->send_activation_email($user_id, $data['email'],
238 $activation_code, $data['username']);
240 // TODO exception on failure
244 public function get_user_id($username)
246 $query = $this->db->query("SELECT id FROM `users`
247 WHERE username = '$username'");
249 if ($query->num_rows() === 0)
252 return $query->row()->id;
255 // TODO cleanup account activation
256 public function cleanup_account_activation()
262 * Activated an account for an user having $user_id with $activation_code.
264 * @param int $user_id
265 * @param string $activation_code hexa 16 characters string
266 * @return returns TRUE if activation was successful and FALSE otherwise
268 public function activate_account($user_id, $activation_code)
270 $query = $this->db->query("SELECT * FROM `users_unactivated`
271 WHERE user_id = $user_id
272 AND activation_code = '$activation_code'");
274 if ($query->num_rows() === 0)
277 $this->db->query("DELETE FROM `users_unactivated`
278 WHERE user_id = $user_id");
283 public function send_activation_email($user_id, $email = NULL,
284 $activation_code = NULL, $username = NULL)
286 if (!$activation_code || !$email || !$username)
293 $userdata = $this->get_userdata($user_id,
294 $cols. "a.activation_code, username");
295 $activation_code =& $userdata['activation_code'];
298 $email =& $userdata['email'];
299 $username =& $userdata['username'];
302 if ($activation_code === NULL)
305 $subject = '['. $this->config->item('site_name')
306 . '] Account Activation';
308 site_url("user/activate/$user_id/code/$activation_code");
309 $msg = sprintf($this->lang->line('user_activation_email_content'),
310 $username, $this->config->item('site_name'), site_url(),
311 $activation_url, $activation_code);
312 $headers = "From: ". $this->config->item('noreply_email');
314 return mail($email, $subject, $msg, $headers);
317 public function recover_password($username, $email)
319 $userdata = $this->get_userdata($username, 'email, username, id');
321 if (strcmp($userdata['email'], $email) !== 0)
324 $recovered_password = Users_model::gen_password();
326 $this->set_userdata(intval($userdata['id']), array('password'=>
327 $recovered_password));
329 $subject = '['. $this->config->item('site_name')
330 . '] Password Recovery';
331 $msg = sprintf($this->lang->line('user_password_recovery_email_content'),
332 $username, $this->config->item('site_name'), site_url(),
333 $recovered_password);
334 $headers = "From: ". $this->config->item('noreply_email');
336 mail($email, $subject, $msg, $headers);
342 * Returns data from `users` table. If $user is int it is used as an
343 * id, if it is string it is used as an username.
346 * @param string $table_cols (optional) string with comma separated
347 * `users` table column names. Use a.activation_code to check user's
348 * account activation_code. If this value is NULL than the account is
350 * @return array associative array with userdata from DB
352 public function get_userdata($user, $table_cols = '*')
355 $cond = "id = $user";
357 $cond = "username = '$user'";
359 $query = $this->db->query("SELECT $table_cols
360 FROM `users` u LEFT JOIN `users_unactivated` a
361 ON (u.id = a.user_id)
364 if ($query->num_rows() === 0)
367 $userdata = $query->row_array();
369 // Post process userdata.
370 if (isset($userdata['picture']))
372 $userdata['picture_thumb'] = site_url(
373 "data/user_pictures/{$userdata['picture']}-thumb.jpg");
374 $userdata['picture'] = site_url(
375 "data/user_pictures/{$userdata['picture']}");
382 * Modifies data from `users` table for user with $user_id.
384 * @param int $user_id
385 * @param array $data key-value pairs with columns and new values to be
387 * @return boolean returns TRUE on success and FALSE otherwise
389 public function set_userdata($user_id, $data)
391 // TODO verify mandatory data existance
394 if (isset($data['password']))
395 $data['password'] = sha1($data['password']);
396 // TODO picture data: save, convert, make it thumbnail
399 foreach ($data as $col => $val)
402 $set .= "$col = $val, ";
403 else if (is_string($val))
404 $set .= "$col = '$val', ";
405 else if (is_null($var))
406 $set .= "$col = NULL, ";
408 $set = substr($set, 0, -2);
410 $query_str = "UPDATE `users`
411 SET $set WHERE id = $user_id";
412 //echo "<p>$query_str</p>";
413 $query = $this->db->query($query_str);
419 public static function gen_activation_code($str = '')
421 $ci =& get_instance();
423 $activation_code = substr(
424 sha1(''. $str. $ci->config->item('encryption_key')
429 return $activation_code;
432 public static function gen_password()
434 $ci =& get_instance();
436 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!_-';
437 $len_chars = strlen($chars);
438 $enc_key = $ci->config->item('encryption_key');
439 $len_enc_key = strlen($enc_key);
442 for ($p = 0; $p < $length; $p++)
444 $i = (mt_rand(1, 100) * ord($enc_key[ mt_rand(0, $len_enc_key-1) ]))
446 $password .= $chars[$i];
452 public static function roles_to_string($roles)
454 $ci =& get_instance();
455 $ci->lang->load('user');
457 if ($roles == USER_ROLE_STANDARD)
458 return $ci->lang->line('user_role_standard');
463 if ($roles & USER_ROLE_ADMIN)
464 $str_roles .= $ci->lang->line('user_role_admin') . '; ';
471 /* End of file users_model.php */
472 /* Location: ./application/models/users_model.php */