working at video comments
[living-lab-site.git] / application / models / users_model.php
1 <?php
2
3 /**
4  * Class Users_model models user information from DB
5  * 
6  * @category    Model
7  * @author              calinburloiu
8  *
9  */
10 class Users_model extends CI_Model {
11         public $db = NULL;
12
13         public function __construct()
14         {
15                 parent::__construct();
16
17                 if ($this->db === NULL)
18                 {
19                         $this->load->library('singleton_db');
20                         $this->db = $this->singleton_db->connect();
21                 }
22         }
23
24         /**
25          * Check authentication credentials. $username can be username or e-mail.
26          * 
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:
35          * <ul>
36          *   <li>'internal' or 'ldap': a DB row</li>
37          *   <li>'ldap_first_time': LDAP user information</li>
38          * </ul>
39          */
40         public function login($username, $password)
41         {
42                 $this->load->helper('email');
43                 
44                 // User logs with e-mail address.
45                 if (! valid_email($username))
46                         $cond_user = "username = '$username'";
47                 else
48                         $cond_user = "email = '$username'";
49                 
50                 $enc_password = sha1($password);
51                 
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)
55                         WHERE $cond_user
56                                 AND (auth_src = 'ldap' OR password = '$enc_password')");
57                 
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
60                 // in `users` table.
61                 if ($query->num_rows() === 0)
62                 {
63                         $ldap_userdata = $this->ldap_login($username, $password);
64                         if ($ldap_userdata === FALSE)
65                                 return FALSE;
66                         $userdata = $this->convert_ldap_userdata($ldap_userdata);
67                         $this->register($userdata);
68                         
69                         $user = $this->login($username, $password);
70                         $user['import'] = TRUE;
71                         return $user;
72                 }
73                 
74                 $user = $query->row_array();
75                 
76                 // Authenticate with LDAP.
77                 if ($user['auth_src'] == 'ldap'
78                                 && ! $this->ldap_login($username, $password))
79                         return FALSE; 
80                 
81                 // Update last login time.
82                 $this->db->query("UPDATE `users`
83                         SET last_login = UTC_TIMESTAMP()
84                         WHERE username = '$username'");
85                 
86                 // If we are here internal authentication has successful.
87                 return $user;
88         }
89         
90         /**
91          * Converts an array returned by LDAP login to an array which contains
92          * user data ready to be used in `users` DB.
93          * 
94          * @param array $ldap_userdata
95          * @return array
96          */
97         public function convert_ldap_userdata($ldap_userdata)
98         {
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];
103                 
104                 $userdata['auth_src'] = 'ldap';
105                 
106                 return $userdata;
107         }
108         
109         /**
110         * Login with LDAP.
111         *
112         * @param string $username
113         * @param string $password
114         * @return boolean
115         * @author  Alex Herișanu, Răzvan Deaconescu, Călin-Andrei Burloiu
116         */
117         public function ldap_login($username, $password)
118         {
119                 $this->config->load('ldap');
120                 
121                 // First connection: binding.
122                 // TODO exception
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'))) 
126                 {
127                         ldap_close($ds);
128                         die("Can't connect to ".$this->config->item('ldap_server')."\n");
129                         return FALSE;
130                 }
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) {
135                         ldap_close($ds);
136                         return FALSE;
137                 }
138                 
139                 $info = ldap_get_entries($ds, $sr);
140                 $dn = $info[0]["dn"];
141                 ldap_close($ds);
142                 
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 == '') {
146                         ldap_close($ds);
147                         return FALSE;
148                 }
149                 
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') );
152                 
153                 // Set authentication source.
154                 $info[0]['auth_src'] = 'ldap_first_time';
155                 
156                 return $info[0];
157         }
158         
159         /**
160         * Verify if a user belongs to a group.
161         * 
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
166         */
167         public function ldap_dn_belongs_ou($dn, $ou)
168         {
169                 if (!is_array($ou))
170                         $ou = array ($ou);
171                 
172                 $founded = FALSE;
173                 $words = explode(',', $dn);
174                 foreach ($words as $c) {
175                         $parts = explode("=", $c);
176                         $key = $parts[0];
177                         $value = $parts[1];
178                 
179                         if (strtolower($key) == "ou" && in_array($value, $ou) )
180                                 $founded = TRUE;
181                 }
182                 
183                 return $founded;
184         }
185         
186         /**
187          * Adds a new user to DB.
188          * Do not add join_date and last_login column, they will be automatically
189          * added.
190          * 
191          * @param array $data   corresponds to DB columns
192          */
193         public function register($data)
194         {
195                 $this->load->helper('array');
196                 
197                 // TODO verify mandatory data existance
198                 
199                 // Process data.
200                 if (isset($data['password']))
201                         $data['password'] = sha1($data['password']);
202                 // TODO picture data: save, convert, make it thumbnail
203                 
204                 $cols = '';
205                 $vals = '';
206                 foreach ($data as $col=> $val)
207                 {
208                         if ($val === NULL)
209                         {
210                                 $cols .= "$col, ";
211                                 $vals .= "NULL, ";
212                                 continue;
213                         }
214                                 
215                         $cols .= "$col, ";
216                         if (is_int($val))
217                                 $vals .= "$val, ";
218                         else if (is_string($val))
219                                 $vals .= "'$val', ";
220                 }
221                 $cols = substr($cols, 0, -2);
222                 $vals = substr($vals, 0, -2);
223                 
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)
228                         return FALSE;
229                 
230                 // If registered with internal authentication it needs to activate
231                 // the account.
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']);
239                 
240                 // TODO exception on failure
241                 return $query;
242         }
243         
244         public function get_user_id($username)
245         {
246                 $query = $this->db->query("SELECT id FROM `users`
247                         WHERE username = '$username'");
248                 
249                 if ($query->num_rows() === 0)
250                         return FALSE;
251                 
252                 return $query->row()->id;
253         }
254         
255         // TODO cleanup account activation
256         public function cleanup_account_activation()
257         {
258                 
259         }
260         
261         /**
262          * Activated an account for an user having $user_id with $activation_code.
263          * 
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
267          */
268         public function activate_account($user_id, $activation_code)
269         {
270                 $query = $this->db->query("SELECT * FROM `users_unactivated`
271                         WHERE user_id = $user_id
272                                 AND activation_code = '$activation_code'");
273                 
274                 if ($query->num_rows() === 0)
275                         return FALSE;
276                 
277                 $this->db->query("DELETE FROM `users_unactivated`
278                         WHERE user_id = $user_id");
279                 
280                 return TRUE;
281         }
282         
283         public function send_activation_email($user_id, $email = NULL,
284                         $activation_code = NULL, $username = NULL)
285         {
286                 if (!$activation_code || !$email || !$username)
287                 {
288                         if (!$email)
289                                 $cols = 'email, ';
290                         else
291                                 $cols = '';
292                         
293                         $userdata = $this->get_userdata($user_id,
294                                         $cols. "a.activation_code, username");
295                         $activation_code =& $userdata['activation_code'];
296                         
297                         if (!$email)
298                                 $email =& $userdata['email'];
299                         $username =& $userdata['username'];
300                 }
301                 
302                 if ($activation_code === NULL)
303                         return TRUE;
304                 
305                 $subject = '['. $this->config->item('site_name')
306                                 . '] Account Activation';
307                 $activation_url =
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');
313                 
314                 return mail($email, $subject, $msg, $headers);
315         }
316         
317         public function recover_password($username, $email)
318         {
319                 $userdata = $this->get_userdata($username, 'email, username, id');
320                 
321                 if (strcmp($userdata['email'], $email) !== 0)
322                         return FALSE;
323                 
324                 $recovered_password = Users_model::gen_password();
325                 
326                 $this->set_userdata(intval($userdata['id']), array('password'=> 
327                                 $recovered_password));
328                 
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');
335                 
336                 mail($email, $subject, $msg, $headers);
337                 
338                 return TRUE;
339         }
340         
341         /**
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.
344          * 
345          * @param mixed $user
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
349          * active.
350          * @return array        associative array with userdata from DB
351          */
352         public function get_userdata($user, $table_cols = '*')
353         {
354                 if (is_int($user))
355                         $cond = "id = $user";
356                 else
357                         $cond = "username = '$user'";
358                 
359                 $query = $this->db->query("SELECT $table_cols
360                         FROM `users` u LEFT JOIN `users_unactivated` a
361                                 ON (u.id = a.user_id)
362                         WHERE $cond");
363                 
364                 if ($query->num_rows() === 0)
365                         return FALSE;
366                 
367                 $userdata = $query->row_array();
368                 
369                 // Post process userdata.
370                 if (isset($userdata['picture']))
371                 {
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']}");
376                 } 
377                 
378                 return $userdata;
379         }
380         
381         /**
382          * Modifies data from `users` table for user with $user_id.
383          * 
384          * @param int $user_id
385          * @param array $data   key-value pairs with columns and new values to be
386          * modified
387          * @return boolean      returns TRUE on success and FALSE otherwise
388          */
389         public function set_userdata($user_id, $data)
390         {
391                 // TODO verify mandatory data existance
392                 
393                 // Process data.
394                 if (isset($data['password']))
395                         $data['password'] = sha1($data['password']);
396                 // TODO picture data: save, convert, make it thumbnail
397                 
398                 $set = '';
399                 foreach ($data as $col => $val)
400                 {
401                         if (is_int($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, ";
407                 }
408                 $set = substr($set, 0, -2);
409                 
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);
414                 
415                 // TODO exception
416                 return $query;
417         }
418         
419         public static function gen_activation_code($str = '')
420         {
421                 $ci =& get_instance();
422                 
423                 $activation_code = substr(
424                         sha1(''. $str. $ci->config->item('encryption_key')
425                                 . mt_rand()),
426                         0,
427                         16);
428                 
429                 return $activation_code;
430         }
431         
432         public static function gen_password()
433         {
434                 $ci =& get_instance();
435                 $length = 16;
436                 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!_-';
437                 $len_chars = strlen($chars);
438                 $enc_key = $ci->config->item('encryption_key');
439                 $len_enc_key = strlen($enc_key);
440                 $password = '';
441                 
442                 for ($p = 0; $p < $length; $p++) 
443                 {
444                         $i = (mt_rand(1, 100) * ord($enc_key[ mt_rand(0, $len_enc_key-1) ]))
445                                 % $len_chars;
446                         $password .= $chars[$i];
447                 }
448                 
449                 return $password;
450         } 
451         
452         public static function roles_to_string($roles)
453         {
454                 $ci =& get_instance();
455                 $ci->lang->load('user');
456                 
457                 if ($roles == USER_ROLE_STANDARD)
458                         return $ci->lang->line('user_role_standard');
459                 else
460                 {
461                         $str_roles = '';
462                         
463                         if ($roles & USER_ROLE_ADMIN)
464                                 $str_roles .= $ci->lang->line('user_role_admin') . '; ';
465                 }
466                 
467                 return $str_roles;
468         }
469 }
470
471 /* End of file users_model.php */
472 /* Location: ./application/models/users_model.php */