427b07e8ecc9670d93894db929148e1d02dd2759
[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 `users`DB row
30          * as an associative array if authentication was successful
31          */
32         public function login($username, $password)
33         {
34                 $this->load->helper('email');
35                 
36                 // User logs with e-mail address.
37                 if (! valid_email($username))
38                         $cond_user = "username = '$username'";
39                 else
40                         $cond_user = "email = '$username'";
41                 
42                 $enc_password = sha1($password);
43                 
44                 $query = $this->db->query("SELECT u.*, a.activation_code
45                         FROM `users` u LEFT JOIN `users_unactivated` a ON (u.id = a.user_id)
46                         WHERE $cond_user
47                                 AND (auth_src = 'ldap' OR password = '$enc_password')");
48                 
49                 // It is possible that the user has a LDAP account but he's
50                 // authenticating here for the first time so it does not have an entry
51                 // in `users` table.
52                 if ($query->num_rows() === 0)
53                 {
54                         $ldap_userdata = $this->ldap_login($username, $password);
55                         if ($ldap_userdata === FALSE)
56                                 return FALSE;
57                         $userdata = $this->convert_ldap_userdata($ldap_userdata);
58                         $this->register($userdata);
59                         
60                         $user = $this->login($username, $password);
61                         $user['import'] = TRUE;
62                         return $user;
63                 }
64                 
65                 $user = $query->row_array();
66                 
67                 // Authenticate with LDAP.
68                 if ($user['auth_src'] == 'ldap'
69                                 && ! $this->ldap_login($username, $password))
70                         return FALSE; 
71                 
72                 if (empty($user['username']) || empty($user['email'])
73                                 || empty($user['first_name']) || empty($user['last_name'])
74                                 || empty($user['country']))
75                         $user['import'] = TRUE;
76                 
77                 // Update last login time.
78                 $this->db->query("UPDATE `users`
79                         SET last_login = UTC_TIMESTAMP()
80                         WHERE username = '$username'");
81                 
82                 // If we are here internal authentication has successful.
83                 return $user;
84         }
85         
86         /**
87          * Begin the OpenID login by redirecting user to the OP to authenticate.
88          * 
89          * @param string $openid 
90          */
91         public function openid_begin_login($openid)
92         {
93                 $this->lang->load('openid');
94                 $this->load->library('openid');
95
96                 $request_to = site_url('user/check_openid_login');
97
98                 $req = array('nickname');
99                 $opt = array('fullname', 'email', 'dob', 'country');
100                 $policy = site_url('user/openid_policy');
101
102                 $ax_attributes[] = Auth_OpenID_AX_AttrInfo::make(
103                                 'http://axschema.org/contact/email', 1, TRUE);
104                 $ax_attributes[] = Auth_OpenID_AX_AttrInfo::make(
105                                 'http://axschema.org/namePerson/first', 1, TRUE);
106                 $ax_attributes[] = Auth_OpenID_AX_AttrInfo::make(
107                                 'http://axschema.org/namePerson/last', 1, TRUE);
108                 $ax_attributes[] = Auth_OpenID_AX_AttrInfo::make(
109                                 'http://axschema.org/contact/country', 1, TRUE);
110
111                 $this->openid->set_request_to($request_to);
112                 $this->openid->set_trust_root(base_url());
113                 $this->openid->set_sreg(TRUE, $req, $opt, $policy);
114                 $this->openid->set_ax(TRUE, $ax_attributes);
115
116                 // Redirection to OP site will follow.
117                 $this->openid->authenticate($openid);
118         }
119         
120         /**
121          * Finalize the OpenID login. Register user if is here for the first time.
122          * 
123          * @return mixed returns a `users` DB row as an associative array if
124          * authentication was successful or Auth_OpenID_CANCEL/_FAILURE if it was
125          * unsuccessful.
126          */
127         public function openid_complete_login()
128         {
129                 $this->lang->load('openid');
130                 $this->load->library('openid');
131                 
132                 $request_to = site_url('user/check_openid_login');
133                 $this->openid->set_request_to($request_to);
134
135                 $response = $this->openid->get_response();
136                 
137                 if ($response->status === Auth_OpenID_CANCEL
138                                 || $response->status === Auth_OpenID_FAILURE)
139                         return $response->status;
140
141                 // Auth_OpenID_SUCCESS
142                 $openid = $response->getDisplayIdentifier();
143                 //$esc_openid = htmlspecialchars($openid, ENT_QUOTES);
144
145                 // Get user_id to see if it's the first time the user logs in with
146                 // OpenID.
147                 $query = $this->db->query("SELECT * from `users_openid`
148                         WHERE openid_url = '$openid'");
149                 $import = FALSE;
150                 
151                 // First time with OpenID => register user
152                 if ($query->num_rows() === 0)
153                 {
154                         $user_id = $this->openid_register($response);
155                         $import = TRUE;
156                 }
157                 // Not first time with OpenID.
158                 else
159                         $user_id = $query->row()->user_id;
160                 
161                 // Login
162                 $query = $this->db->query("SELECT * FROM `users`
163                         WHERE id = $user_id");
164                 $userdata = $query->row_array();
165                 $userdata['import'] = $import;
166                 
167                 if (empty($userdata['username']) || empty($userdata['email'])
168                                 || empty($userdata['first_name'])
169                                 || empty($userdata['last_name'])
170                                 || empty($userdata['country']))
171                         $userdata['import'] = TRUE;
172                 
173                 // Update last login time.
174                 $this->db->query("UPDATE `users`
175                         SET last_login = UTC_TIMESTAMP()
176                         WHERE id = $user_id");
177
178                 return $userdata;               
179         }
180         
181         /**
182          * Register an user that logged in with OpenID for the first time.
183          * 
184          * @param object $op_response object returned by Janrain 
185          * Consumer::complete method.
186          * @return mixed the user_id inserted or FALSE on error
187          */
188         public function openid_register($op_response)
189         {
190                 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($op_response);
191                 $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($op_response);
192
193                 // E-mail
194                 $email = $ax_resp->get('http://axschema.org/contact/email');
195                 if (empty($email) || is_a($email, 'Auth_OpenID_AX_Error'))
196                         $data['email'] = $sreg_resp->get('email', '');
197                 else
198                         $data['email'] = $email[0];
199                 
200                 // First Name
201                 $first_name = $ax_resp->get('http://axschema.org/namePerson/first');
202                 if (empty($first_name) || is_a($first_name, 'Auth_OpenID_AX_Error'))
203                         $data['first_name'] = '';
204                 else
205                         $data['first_name'] = $first_name[0];
206                 
207                 // Sur Name
208                 $last_name = $ax_resp->get('http://axschema.org/namePerson/last');
209                 if (empty($last_name) || is_a($last_name, 'Auth_OpenID_AX_Error'))
210                         $data['last_name'] = '';
211                 else
212                         $data['last_name'] = $last_name[0];
213                 
214                 // First Name and Last Name
215                 if (empty($data['first_name']) || empty($data['last_name']))
216                 {
217                         $fullname = $sreg_resp->get('fullname');
218                         
219                         if ($fullname)
220                         {
221                                 if (empty($data['first_name']))
222                                         $data['first_name'] = substr(
223                                                         $fullname, 0, strrpos($fullname, ' '));
224                                 if (empty($data['last_name']))
225                                         $data['last_name'] = substr(
226                                                         $fullname, strrpos($fullname, ' ') + 1);
227                         }
228                 }
229                 
230                 // Username
231                 $data['username'] = $sreg_resp->get('nickname');
232                 if (!$data['username'])
233                 {
234                         if (!empty($data['email']))
235                         {
236                                 $data['email'] = strtolower($data['email']);
237                                 $data['username'] = substr($data['email'],
238                                                 0, strpos($data['email'], '@'));
239                                 $data['username'] = preg_replace(array('/[^a-z0-9\._]*/'),
240                                                 array(''), $data['username']);
241                         }
242                         else if(!empty($data['first_name']) || !empty($data['last_name']))
243                         {
244                                 $data['username'] = $data['first_name'] . '_'
245                                                 . $data['last_name'];
246                                 $data['username'] = substr($data['username'], 0, 32);
247                         }
248                         else
249                                 $data['username'] = $this->gen_username();
250                 }
251                 if ($this->get_userdata($data['username']))
252                 {
253                         $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
254                         $len_chars = strlen($chars);
255                         $data['username'] .= '_';
256                         do
257                         {
258                                 $data['username'] .= $chars[ mt_rand(0, $len_chars - 1) ];
259                         } while($this->get_userdata($data['username']));
260                 }
261                 
262                 // Country
263                 $country = $ax_resp->get('http://axschema.org/contact/country');
264                 if (empty($country) || is_a($country, 'Auth_OpenID_AX_Error'))
265                         $data['country'] = $sreg_resp->get('country', '');
266                 else
267                         $data['country'] = $country[0];
268                 
269                 // Birth Date
270                 $data['birth_date'] = $sreg_resp->get('dob', NULL);
271                 
272                 // OpenID
273                 $data['auth_src'] = 'openid';
274                 
275 //              print_r($data);
276                 
277                 if (!$this->register($data, $op_response->getDisplayIdentifier()))
278                         return FALSE;
279                 
280                 $query = $this->db->query("SELECT id from `users`
281                         WHERE username = '{$data['username']}'");
282                 return $query->row()->id;
283         }
284         
285         /**
286          * Converts an array returned by LDAP login to an array which contains
287          * user data ready to be used in `users` DB.
288          * 
289          * @param array $ldap_userdata
290          * @return array
291          */
292         public function convert_ldap_userdata($ldap_userdata)
293         {
294                 $userdata['username'] = $ldap_userdata['uid'][0];
295                 $userdata['email'] = $ldap_userdata['mail'][0];
296                 $userdata['first_name'] = $ldap_userdata['givenname'][0];
297                 $userdata['last_name'] = $ldap_userdata['sn'][0];
298                 
299                 $userdata['auth_src'] = 'ldap';
300                 
301                 return $userdata;
302         }
303         
304         /**
305         * Login with LDAP.
306         *
307         * @param string $username
308         * @param string $password
309         * @return boolean
310         * @author  Alex HeriÈ™anu, Răzvan Deaconescu, Călin-Andrei Burloiu
311         */
312         public function ldap_login($username, $password)
313         {
314                 $this->config->load('ldap');
315                 
316                 // First connection: binding.
317                 // TODO exception
318                 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server.\n");
319                 if (!@ldap_bind($ds, $this->config->item('ldap_bind_user'),
320                         $this->config->item('ldap_bind_password'))) 
321                 {
322                         ldap_close($ds);
323                         die("Can't connect to ".$this->config->item('ldap_server')."\n");
324                         return FALSE;
325                 }
326                 $sr = ldap_search($ds, "dc=cs,dc=curs,dc=pub,dc=ro", "(uid=" . $username . ")");
327                 if (ldap_count_entries($ds, $sr) > 1)
328                 die("Multiple entries with the same uid in LDAP database??");
329                 if (ldap_count_entries($ds, $sr) < 1) {
330                         ldap_close($ds);
331                         return FALSE;
332                 }
333                 
334                 $info = ldap_get_entries($ds, $sr);
335                 $dn = $info[0]["dn"];
336                 ldap_close($ds);
337                 
338                 // Second connection: connect with user's credentials.
339                 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server\n");
340                 if (!@ldap_bind($ds, $dn, $password) or $password == '') {
341                         ldap_close($ds);
342                         return FALSE;
343                 }
344                 
345                 // Verifify if DN belongs to the requested OU.
346                 $info[0]['ou_ok'] = $this->ldap_dn_belongs_ou( $dn, $this->config->item('ldap_req_ou') );
347                 
348                 // Set authentication source.
349                 $info[0]['auth_src'] = 'ldap_first_time';
350                 
351                 return $info[0];
352         }
353         
354         /**
355         * Verify if a user belongs to a group.
356         * 
357         * @param string $dn = "ou=Student,ou=People..."
358         * @param array $ou = array ("Student", etc
359         * @return TRUE or FALSE
360         * @author  Răzvan HeriÈ™anu, Răzvan Deaconescu, Călin-Andrei Burloiu
361         */
362         public function ldap_dn_belongs_ou($dn, $ou)
363         {
364                 if (!is_array($ou))
365                         $ou = array ($ou);
366                 
367                 $founded = FALSE;
368                 $words = explode(',', $dn);
369                 foreach ($words as $c) {
370                         $parts = explode("=", $c);
371                         $key = $parts[0];
372                         $value = $parts[1];
373                 
374                         if (strtolower($key) == "ou" && in_array($value, $ou) )
375                                 $founded = TRUE;
376                 }
377                 
378                 return $founded;
379         }
380         
381         /**
382          * Adds a new user to DB.
383          * Do not add join_date and last_login column, they will be automatically
384          * added.
385          * Provide an 'openid' with the OpenID as value in order to register users
386          * logging in this way.
387          * 
388          * @param array $data   corresponds to DB columns
389          */
390         public function register($data, $openid = NULL)
391         {
392                 $this->load->helper('array');
393                 
394                 // TODO verify mandatory data existance
395                 
396                 // Process data.
397                 if (isset($data['password']))
398                         $data['password'] = sha1($data['password']);
399                 
400                 if (empty($data['birth_date']))
401                         $data['birth_date'] = NULL;
402                 
403                 $cols = '';
404                 $vals = '';
405                 foreach ($data as $col=> $val)
406                 {
407                         if ($val === NULL)
408                         {
409                                 $cols .= "$col, ";
410                                 $vals .= "NULL, ";
411                                 continue;
412                         }
413                                 
414                         $cols .= "$col, ";
415                         if (is_int($val))
416                                 $vals .= "$val, ";
417                         else if (is_string($val))
418                                 $vals .= "'$val', ";
419                 }
420                 $cols = substr($cols, 0, -2);
421                 $vals = substr($vals, 0, -2);
422                 
423                 $query = $this->db->query("INSERT INTO `users`
424                         ($cols, registration_date, last_login)
425                         VALUES ($vals, utc_timestamp(), utc_timestamp())");
426                 if ($query === FALSE)
427                         return FALSE;
428                 
429                 // If registered with OpenID insert a row in `users_openid`.
430                 if ($openid)
431                 {
432                         // Find user_id.
433                         $query = $this->db->query("SELECT id from `users`
434                                 WHERE username = '{$data['username']}'");
435                         if ($query->num_rows() === 0)
436                                 return FALSE;
437                         $user_id = $query->row()->id;
438                         
439                         // Insert row in `users_openid`.
440                         $query = $this->db->query("INSERT INTO `users_openid`
441                                 (openid_url, user_id)
442                                 VALUES ('$openid', $user_id)");
443                         if (!$query)
444                                 return FALSE;
445                 }
446                 
447                 // If registered with internal authentication it needs to activate
448                 // the account.
449                 if ($data['auth_src'] == 'internal')
450                 {
451                         $activation_code = Users_model::gen_activation_code($data['username']);
452                         $user_id = $this->get_user_id($data['username']);
453                         $query = $this->db->query("INSERT INTO `users_unactivated`
454                                 (user_id, activation_code)
455                                 VALUES ($user_id, '$activation_code')");
456                         $this->send_activation_email($user_id, $data['email'],
457                                 $activation_code, $data['username']);
458                 }
459                 
460                 // TODO exception on failure
461                 return $query;
462         }
463         
464         public function get_user_id($username)
465         {
466                 $query = $this->db->query("SELECT id FROM `users`
467                         WHERE username = '$username'");
468                 
469                 if ($query->num_rows() === 0)
470                         return FALSE;
471                 
472                 return $query->row()->id;
473         }
474         
475         // TODO cleanup account activation
476         public function cleanup_account_activation()
477         {
478                 
479         }
480         
481         /**
482          * Activated an account for an user having $user_id with $activation_code.
483          * 
484          * @param int $user_id
485          * @param string $activation_code       hexa 16 characters string
486          * @return returns TRUE if activation was successful and FALSE otherwise
487          */
488         public function activate_account($user_id, $activation_code)
489         {
490                 $query = $this->db->query("SELECT * FROM `users_unactivated`
491                         WHERE user_id = $user_id
492                                 AND activation_code = '$activation_code'");
493                 
494                 if ($query->num_rows() === 0)
495                         return FALSE;
496                 
497                 $this->db->query("DELETE FROM `users_unactivated`
498                         WHERE user_id = $user_id");
499                 
500                 return TRUE;
501         }
502         
503         public function send_activation_email($user_id, $email = NULL,
504                         $activation_code = NULL, $username = NULL)
505         {
506                 if (!$activation_code || !$email || !$username)
507                 {
508                         if (!$email)
509                                 $cols = 'email, ';
510                         else
511                                 $cols = '';
512                         
513                         $userdata = $this->get_userdata($user_id,
514                                         $cols. "a.activation_code, username");
515                         $activation_code =& $userdata['activation_code'];
516                         
517                         if (!$email)
518                                 $email =& $userdata['email'];
519                         $username =& $userdata['username'];
520                 }
521                 
522                 if ($activation_code === NULL)
523                         return TRUE;
524                 
525                 $subject = '['. $this->config->item('site_name')
526                                 . '] Account Activation';
527                 $activation_url =
528                                 site_url("user/activate/$user_id/code/$activation_code"); 
529                 $msg = sprintf($this->lang->line('user_activation_email_content'),
530                         $username, $this->config->item('site_name'), site_url(),
531                         $activation_url, $activation_code);
532                 $headers = "From: ". $this->config->item('noreply_email');
533                 
534                 return mail($email, $subject, $msg, $headers);
535         }
536         
537         public function recover_password($username, $email)
538         {
539                 $userdata = $this->get_userdata($username, 'email, username, id');
540                 
541                 if (strcmp($userdata['email'], $email) !== 0)
542                         return FALSE;
543                 
544                 $recovered_password = Users_model::gen_password();
545                 
546                 $this->set_userdata(intval($userdata['id']), array('password'=> 
547                                 $recovered_password));
548                 
549                 $subject = '['. $this->config->item('site_name')
550                 . '] Password Recovery';
551                 $msg = sprintf($this->lang->line('user_password_recovery_email_content'),
552                         $username, $this->config->item('site_name'), site_url(),
553                         $recovered_password);
554                 $headers = "From: ". $this->config->item('noreply_email');
555                 
556                 mail($email, $subject, $msg, $headers);
557                 
558                 return TRUE;
559         }
560         
561         /**
562          * Returns data from `users` table. If $user is int it is used as an
563          * id, if it is string it is used as an username.
564          * 
565          * @param mixed $user
566          * @param string $table_cols    (optional) string with comma separated
567          * `users` table column names. Use a.activation_code to check user's
568          * account activation_code. If this value is NULL than the account is
569          * active.
570          * @return array        associative array with userdata from DB
571          */
572         public function get_userdata($user, $table_cols = '*')
573         {
574                 if (is_int($user))
575                         $cond = "id = $user";
576                 else
577                         $cond = "username = '$user'";
578                 
579                 $query = $this->db->query("SELECT $table_cols
580                         FROM `users` u LEFT JOIN `users_unactivated` a
581                                 ON (u.id = a.user_id)
582                         WHERE $cond");
583                 
584                 if ($query->num_rows() === 0)
585                         return FALSE;
586                 
587                 $userdata = $query->row_array();
588                 
589                 // Post process userdata.
590                 if (isset($userdata['picture']))
591                 {
592                         $userdata['picture_thumb'] = site_url(
593                                 "data/user_pictures/{$userdata['picture']}-thumb.jpg");
594                         $userdata['picture'] = site_url(
595                                 "data/user_pictures/{$userdata['picture']}");
596                 } 
597                 
598                 return $userdata;
599         }
600         
601         /**
602          * Modifies data from `users` table for user with $user_id.
603          * 
604          * @param int $user_id
605          * @param array $data   key-value pairs with columns and new values to be
606          * modified
607          * @return boolean      returns TRUE on success and FALSE otherwise
608          */
609         public function set_userdata($user_id, $data)
610         {
611                 // TODO verify mandatory data existance
612                 
613                 // Process data.
614                 if (isset($data['password']))
615                         $data['password'] = sha1($data['password']);
616                 // TODO picture data: save, convert, make it thumbnail
617                 
618                 if (empty($data['birth_date']))
619                         $data['birth_date'] = NULL;
620                 
621                 $set = '';
622                 foreach ($data as $col => $val)
623                 {
624                         if ($val === NULL)
625                         {
626                                 $set .= "$col = NULL, ";
627                                 continue;
628                         }
629                         
630                         if (is_int($val))
631                                 $set .= "$col = $val, ";
632                         else if (is_string($val))
633                                 $set .= "$col = '$val', ";
634                 }
635                 $set = substr($set, 0, -2);
636                 
637                 $query_str = "UPDATE `users`
638                         SET $set WHERE id = $user_id";
639                 //echo "<p>$query_str</p>";
640                 $query = $this->db->query($query_str);
641                 
642                 // TODO exception
643                 return $query;
644         }
645         
646         public static function gen_activation_code($str = '')
647         {
648                 $ci =& get_instance();
649                 
650                 $activation_code = substr(
651                         sha1(''. $str. $ci->config->item('encryption_key')
652                                 . mt_rand()),
653                         0,
654                         16);
655                 
656                 return $activation_code;
657         }
658         
659         public static function gen_password()
660         {
661                 $ci =& get_instance();
662                 $length = 16;
663                 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!_-';
664                 $len_chars = strlen($chars);
665                 $enc_key = $ci->config->item('encryption_key');
666                 $len_enc_key = strlen($enc_key);
667                 $password = '';
668                 
669                 for ($p = 0; $p < $length; $p++) 
670                 {
671                         $i = (mt_rand(1, 100) * ord($enc_key[ mt_rand(0, $len_enc_key-1) ]))
672                                 % $len_chars;
673                         $password .= $chars[$i];
674                 }
675                 
676                 return $password;
677         }
678         
679         public static function gen_username()
680         {
681                 $chars = 'abcdefghijklmnopqrstuvwxyz0123456789._';
682                 $len_chars = strlen($chars);
683                 $len = 8;
684                 $username = '';
685                 
686                 for ($i = 0; $i < $len; $i++)
687                         $username .= $chars[ mt_rand(0, $len_chars - 1) ];
688                 
689                 return $username;
690         }
691         
692         public static function roles_to_string($roles)
693         {
694                 $ci =& get_instance();
695                 $ci->lang->load('user');
696                 
697                 if ($roles == USER_ROLE_STANDARD)
698                         return $ci->lang->line('user_role_standard');
699                 else
700                 {
701                         $str_roles = '';
702                         
703                         if ($roles & USER_ROLE_ADMIN)
704                                 $str_roles .= $ci->lang->line('user_role_admin') . '; ';
705                 }
706                 
707                 return $str_roles;
708         }
709 }
710
711 /* End of file users_model.php */
712 /* Location: ./application/models/users_model.php */