8046ed3f50461d2bd8eb9d58cf23042ca2b31a78
[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                         }
247                         else
248                                 $data['username'] = $this->gen_username();
249                 }
250                 $data['username'] = substr($data['username'], 0, 24);
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                 $data['username'] = 'autogen_' . $data['username'];
262                 
263                 // Country
264                 $country = $ax_resp->get('http://axschema.org/contact/country');
265                 if (empty($country) || is_a($country, 'Auth_OpenID_AX_Error'))
266                         $data['country'] = $sreg_resp->get('country', '');
267                 else
268                         $data['country'] = $country[0];
269                 
270                 // Birth Date
271                 $data['birth_date'] = $sreg_resp->get('dob', NULL);
272                 
273                 // OpenID
274                 $data['auth_src'] = 'openid';
275                 
276 //              print_r($data);
277                 
278                 if (!$this->register($data, $op_response->getDisplayIdentifier()))
279                         return FALSE;
280                 
281                 $query = $this->db->query("SELECT id from `users`
282                         WHERE username = '{$data['username']}'");
283                 return $query->row()->id;
284         }
285         
286         /**
287          * Converts an array returned by LDAP login to an array which contains
288          * user data ready to be used in `users` DB.
289          * 
290          * @param array $ldap_userdata
291          * @return array
292          */
293         public function convert_ldap_userdata($ldap_userdata)
294         {
295                 $userdata['username'] = $ldap_userdata['uid'][0];
296                 $userdata['email'] = $ldap_userdata['mail'][0];
297                 $userdata['first_name'] = $ldap_userdata['givenname'][0];
298                 $userdata['last_name'] = $ldap_userdata['sn'][0];
299                 
300                 $userdata['auth_src'] = 'ldap';
301                 
302                 return $userdata;
303         }
304         
305         /**
306         * Login with LDAP.
307         *
308         * @param string $username
309         * @param string $password
310         * @return boolean
311         * @author  Alex HeriÈ™anu, Răzvan Deaconescu, Călin-Andrei Burloiu
312         */
313         public function ldap_login($username, $password)
314         {
315                 $this->config->load('ldap');
316                 
317                 // First connection: binding.
318                 // TODO exception
319                 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server.\n");
320                 if (!@ldap_bind($ds, $this->config->item('ldap_bind_user'),
321                         $this->config->item('ldap_bind_password'))) 
322                 {
323                         ldap_close($ds);
324                         die("Can't connect to ".$this->config->item('ldap_server')."\n");
325                         return FALSE;
326                 }
327                 $sr = ldap_search($ds, "dc=cs,dc=curs,dc=pub,dc=ro", "(uid=" . $username . ")");
328                 if (ldap_count_entries($ds, $sr) > 1)
329                 die("Multiple entries with the same uid in LDAP database??");
330                 if (ldap_count_entries($ds, $sr) < 1) {
331                         ldap_close($ds);
332                         return FALSE;
333                 }
334                 
335                 $info = ldap_get_entries($ds, $sr);
336                 $dn = $info[0]["dn"];
337                 ldap_close($ds);
338                 
339                 // Second connection: connect with user's credentials.
340                 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server\n");
341                 if (!@ldap_bind($ds, $dn, $password) or $password == '') {
342                         ldap_close($ds);
343                         return FALSE;
344                 }
345                 
346                 // Verifify if DN belongs to the requested OU.
347                 $info[0]['ou_ok'] = $this->ldap_dn_belongs_ou( $dn, $this->config->item('ldap_req_ou') );
348                 
349                 // Set authentication source.
350                 $info[0]['auth_src'] = 'ldap_first_time';
351                 
352                 return $info[0];
353         }
354         
355         /**
356         * Verify if a user belongs to a group.
357         * 
358         * @param string $dn = "ou=Student,ou=People..."
359         * @param array $ou = array ("Student", etc
360         * @return TRUE or FALSE
361         * @author  Răzvan HeriÈ™anu, Răzvan Deaconescu, Călin-Andrei Burloiu
362         */
363         public function ldap_dn_belongs_ou($dn, $ou)
364         {
365                 if (!is_array($ou))
366                         $ou = array ($ou);
367                 
368                 $founded = FALSE;
369                 $words = explode(',', $dn);
370                 foreach ($words as $c) {
371                         $parts = explode("=", $c);
372                         $key = $parts[0];
373                         $value = $parts[1];
374                 
375                         if (strtolower($key) == "ou" && in_array($value, $ou) )
376                                 $founded = TRUE;
377                 }
378                 
379                 return $founded;
380         }
381         
382         /**
383          * Adds a new user to DB.
384          * Do not add join_date and last_login column, they will be automatically
385          * added.
386          * Provide an 'openid' with the OpenID as value in order to register users
387          * logging in this way.
388          * 
389          * @param array $data   corresponds to DB columns
390          */
391         public function register($data, $openid = NULL)
392         {
393                 $this->load->helper('array');
394                 
395                 // TODO verify mandatory data existance
396                 
397                 // Process data.
398                 if (isset($data['password']))
399                         $data['password'] = sha1($data['password']);
400                 
401                 if (empty($data['birth_date']))
402                         $data['birth_date'] = NULL;
403                 
404                 $cols = '';
405                 $vals = '';
406                 foreach ($data as $col=> $val)
407                 {
408                         if ($val === NULL)
409                         {
410                                 $cols .= "$col, ";
411                                 $vals .= "NULL, ";
412                                 continue;
413                         }
414                                 
415                         $cols .= "$col, ";
416                         if (is_int($val))
417                                 $vals .= "$val, ";
418                         else if (is_string($val))
419                                 $vals .= "'$val', ";
420                 }
421                 $cols = substr($cols, 0, -2);
422                 $vals = substr($vals, 0, -2);
423                 
424                 $query = $this->db->query("INSERT INTO `users`
425                         ($cols, registration_date, last_login)
426                         VALUES ($vals, utc_timestamp(), utc_timestamp())");
427                 if ($query === FALSE)
428                         return FALSE;
429                 
430                 // If registered with OpenID insert a row in `users_openid`.
431                 if ($openid)
432                 {
433                         // Find user_id.
434                         $query = $this->db->query("SELECT id from `users`
435                                 WHERE username = '{$data['username']}'");
436                         if ($query->num_rows() === 0)
437                                 return FALSE;
438                         $user_id = $query->row()->id;
439                         
440                         // Insert row in `users_openid`.
441                         $query = $this->db->query("INSERT INTO `users_openid`
442                                 (openid_url, user_id)
443                                 VALUES ('$openid', $user_id)");
444                         if (!$query)
445                                 return FALSE;
446                 }
447                 
448                 // If registered with internal authentication it needs to activate
449                 // the account.
450                 if ($data['auth_src'] == 'internal')
451                 {
452                         $activation_code = Users_model::gen_activation_code($data['username']);
453                         $user_id = $this->get_user_id($data['username']);
454                         $query = $this->db->query("INSERT INTO `users_unactivated`
455                                 (user_id, activation_code)
456                                 VALUES ($user_id, '$activation_code')");
457                         $this->send_activation_email($user_id, $data['email'],
458                                 $activation_code, $data['username']);
459                 }
460                 
461                 // TODO exception on failure
462                 return $query;
463         }
464         
465         public function get_user_id($username)
466         {
467                 $query = $this->db->query("SELECT id FROM `users`
468                         WHERE username = '$username'");
469                 
470                 if ($query->num_rows() === 0)
471                         return FALSE;
472                 
473                 return $query->row()->id;
474         }
475         
476         // TODO cleanup account activation
477         public function cleanup_account_activation()
478         {
479                 
480         }
481         
482         /**
483          * Activated an account for an user having $user_id with $activation_code.
484          * 
485          * @param int $user_id
486          * @param string $activation_code       hexa 16 characters string
487          * @return returns TRUE if activation was successful and FALSE otherwise
488          */
489         public function activate_account($user_id, $activation_code)
490         {
491                 $query = $this->db->query("SELECT * FROM `users_unactivated`
492                         WHERE user_id = $user_id
493                                 AND activation_code = '$activation_code'");
494                 
495                 if ($query->num_rows() === 0)
496                         return FALSE;
497                 
498                 $this->db->query("DELETE FROM `users_unactivated`
499                         WHERE user_id = $user_id");
500                 
501                 return TRUE;
502         }
503         
504         public function send_activation_email($user_id, $email = NULL,
505                         $activation_code = NULL, $username = NULL)
506         {
507                 if (!$activation_code || !$email || !$username)
508                 {
509                         if (!$email)
510                                 $cols = 'email, ';
511                         else
512                                 $cols = '';
513                         
514                         $userdata = $this->get_userdata($user_id,
515                                         $cols. "a.activation_code, username");
516                         $activation_code =& $userdata['activation_code'];
517                         
518                         if (!$email)
519                                 $email =& $userdata['email'];
520                         $username =& $userdata['username'];
521                 }
522                 
523                 if ($activation_code === NULL)
524                         return TRUE;
525                 
526                 $subject = '['. $this->config->item('site_name')
527                                 . '] Account Activation';
528                 $activation_url =
529                                 site_url("user/activate/$user_id/code/$activation_code"); 
530                 $msg = sprintf($this->lang->line('user_activation_email_content'),
531                         $username, $this->config->item('site_name'), site_url(),
532                         $activation_url, $activation_code);
533                 $headers = "From: ". $this->config->item('noreply_email');
534                 
535                 return mail($email, $subject, $msg, $headers);
536         }
537         
538         public function recover_password($username, $email)
539         {
540                 $userdata = $this->get_userdata($username, 'email, username, id');
541                 
542                 if (strcmp($userdata['email'], $email) !== 0)
543                         return FALSE;
544                 
545                 $recovered_password = Users_model::gen_password();
546                 
547                 $this->set_userdata(intval($userdata['id']), array('password'=> 
548                                 $recovered_password));
549                 
550                 $subject = '['. $this->config->item('site_name')
551                 . '] Password Recovery';
552                 $msg = sprintf($this->lang->line('user_password_recovery_email_content'),
553                         $username, $this->config->item('site_name'), site_url(),
554                         $recovered_password);
555                 $headers = "From: ". $this->config->item('noreply_email');
556                 
557                 mail($email, $subject, $msg, $headers);
558                 
559                 return TRUE;
560         }
561         
562         /**
563          * Returns data from `users` table. If $user is int it is used as an
564          * id, if it is string it is used as an username.
565          * 
566          * @param mixed $user
567          * @param string $table_cols    (optional) string with comma separated
568          * `users` table column names. Use a.activation_code to check user's
569          * account activation_code. If this value is NULL than the account is
570          * active.
571          * @return array        associative array with userdata from DB
572          */
573         public function get_userdata($user, $table_cols = '*')
574         {
575                 if (is_int($user))
576                         $cond = "id = $user";
577                 else
578                         $cond = "username = '$user'";
579                 
580                 $query = $this->db->query("SELECT $table_cols
581                         FROM `users` u LEFT JOIN `users_unactivated` a
582                                 ON (u.id = a.user_id)
583                         WHERE $cond");
584                 
585                 if ($query->num_rows() === 0)
586                         return FALSE;
587                 
588                 $userdata = $query->row_array();
589                 
590                 // Post process userdata.
591                 if (isset($userdata['picture']))
592                 {
593                         $userdata['picture_thumb'] = site_url(
594                                 "data/user_pictures/{$userdata['picture']}-thumb.jpg");
595                         $userdata['picture'] = site_url(
596                                 "data/user_pictures/{$userdata['picture']}");
597                 } 
598                 
599                 return $userdata;
600         }
601         
602         /**
603          * Modifies data from `users` table for user with $user_id.
604          * 
605          * @param int $user_id
606          * @param array $data   key-value pairs with columns and new values to be
607          * modified
608          * @return boolean      returns TRUE on success and FALSE otherwise
609          */
610         public function set_userdata($user_id, $data)
611         {
612                 // TODO verify mandatory data existance
613                 
614                 // Process data.
615                 if (isset($data['password']))
616                         $data['password'] = sha1($data['password']);
617                 // TODO picture data: save, convert, make it thumbnail
618                 
619                 if (empty($data['birth_date']))
620                         $data['birth_date'] = NULL;
621                 
622                 $set = '';
623                 foreach ($data as $col => $val)
624                 {
625                         if ($val === NULL)
626                         {
627                                 $set .= "$col = NULL, ";
628                                 continue;
629                         }
630                         
631                         if (is_int($val))
632                                 $set .= "$col = $val, ";
633                         else if (is_string($val))
634                                 $set .= "$col = '$val', ";
635                 }
636                 $set = substr($set, 0, -2);
637                 
638                 $query_str = "UPDATE `users`
639                         SET $set WHERE id = $user_id";
640                 //echo "<p>$query_str</p>";
641                 $query = $this->db->query($query_str);
642                 
643                 // TODO exception
644                 return $query;
645         }
646         
647         public static function gen_activation_code($str = '')
648         {
649                 $ci =& get_instance();
650                 
651                 $activation_code = substr(
652                         sha1(''. $str. $ci->config->item('encryption_key')
653                                 . mt_rand()),
654                         0,
655                         16);
656                 
657                 return $activation_code;
658         }
659         
660         public static function gen_password()
661         {
662                 $ci =& get_instance();
663                 $length = 16;
664                 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!_-';
665                 $len_chars = strlen($chars);
666                 $enc_key = $ci->config->item('encryption_key');
667                 $len_enc_key = strlen($enc_key);
668                 $password = '';
669                 
670                 for ($p = 0; $p < $length; $p++) 
671                 {
672                         $i = (mt_rand(1, 100) * ord($enc_key[ mt_rand(0, $len_enc_key-1) ]))
673                                 % $len_chars;
674                         $password .= $chars[$i];
675                 }
676                 
677                 return $password;
678         }
679         
680         public static function gen_username()
681         {
682                 $chars = 'abcdefghijklmnopqrstuvwxyz0123456789._';
683                 $len_chars = strlen($chars);
684                 $len = 8;
685                 $username = '';
686                 
687                 for ($i = 0; $i < $len; $i++)
688                         $username .= $chars[ mt_rand(0, $len_chars - 1) ];
689                 
690                 return $username;
691         }
692         
693         public static function roles_to_string($roles)
694         {
695                 $ci =& get_instance();
696                 $ci->lang->load('user');
697                 
698                 if ($roles == USER_ROLE_STANDARD)
699                         return $ci->lang->line('user_role_standard');
700                 else
701                 {
702                         $str_roles = '';
703                         
704                         if ($roles & USER_ROLE_ADMIN)
705                                 $str_roles .= $ci->lang->line('user_role_admin') . '; ';
706                 }
707                 
708                 return $str_roles;
709         }
710 }
711
712 /* End of file users_model.php */
713 /* Location: ./application/models/users_model.php */