unactivated users CLI cleanup; user management bugs fixed; working at CAPTCHA
[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                 if ($ax_resp)
194                 {
195                         $ax_email = $ax_resp->get('http://axschema.org/contact/email');
196                         $ax_first_name = $ax_resp->get(
197                                         'http://axschema.org/namePerson/first');
198                         $ax_last_name = $ax_resp->get('http://axschema.org/namePerson/last');
199                         $ax_country = $ax_resp->get('http://axschema.org/contact/country');
200                 }
201                 else
202                 {
203                         $ax_email = '';
204                         $ax_first_name = '';
205                         $ax_last_name = '';
206                         $ax_country = '';
207                 }
208                 
209                 if ($sreg_resp)
210                 {
211                         $sreg_email = $sreg_resp->get('email', '');
212                         $sreg_fullname = $sreg_resp->get('fullname', '');
213                         $sreg_nickname = $sreg_resp->get('nickname', '');
214                         $sreg_country = $sreg_resp->get('country', '');
215                         $sreg_dob = $sreg_resp->get('dob', NULL);
216                 }
217                 else
218                 {
219                         $sreg_email = $sreg_fullname = $sreg_nickname = $sreg_country = '';
220                         $sreg_dob = NULL;
221                 }
222
223                 // E-mail
224                 if (empty($ax_email) || is_a($ax_email, 'Auth_OpenID_AX_Error'))
225                         $data['email'] = $sreg_email;
226                 else
227                         $data['email'] = $ax_email[0];
228                 $data['email'] = strtolower($data['email']);
229                 
230                 // First Name
231                 if (empty($ax_first_name)
232                                 || is_a($ax_first_name, 'Auth_OpenID_AX_Error'))
233                         $data['first_name'] = '';
234                 else
235                         $data['first_name'] = $ax_first_name[0];
236                 
237                 // Sur Name
238                 if (empty($ax_last_name) || is_a($ax_last_name, 'Auth_OpenID_AX_Error'))
239                         $data['last_name'] = '';
240                 else
241                         $data['last_name'] = $ax_last_name[0];
242                 
243                 // First Name and Last Name
244                 if (empty($data['first_name']) || empty($data['last_name']))
245                 {
246                         if ($sreg_fullname)
247                         {
248                                 if (empty($data['first_name']))
249                                         $data['first_name'] = substr(
250                                                         $sreg_fullname, 0, strrpos($sreg_fullname, ' '));
251                                 if (empty($data['last_name']))
252                                         $data['last_name'] = substr(
253                                                         $sreg_fullname, strrpos($sreg_fullname, ' ') + 1);
254                         }
255                 }
256                 
257                 // Username
258                 $data['username'] = $sreg_nickname;
259                 if (!$data['username'])
260                 {
261                         // Generate username from email
262                         if (!empty($data['email']))
263                         {
264                                 $data['username'] = substr($data['email'],
265                                                 0, strpos($data['email'], '@'));
266                                 $data['username'] = preg_replace(array('/[^a-z0-9\._]*/'),
267                                                 array(''), $data['username']);
268                         }
269                         // Generate username from first name and sur name
270                         else if(!empty($data['first_name']) || !empty($data['last_name']))
271                         {
272                                 $data['username'] = $data['first_name'] . '_'
273                                                 . $data['last_name'];
274                         }
275                         // Generate a random username
276                         else
277                                 $data['username'] = $this->gen_username();
278                 }
279                 // Limit username to 24 characters because a prefix of 8 characters
280                 // will be added: 'autogen_'.
281                 $data['username'] = substr($data['username'], 0, 24);
282                 // Append a random character to the username each time it still exists.
283                 if ($this->get_userdata($data['username']))
284                 {
285                         $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
286                         $len_chars = strlen($chars);
287                         $data['username'] .= '_';
288                         do
289                         {
290                                 $data['username'] .= $chars[ mt_rand(0, $len_chars - 1) ];
291                         } while($this->get_userdata($data['username']));
292                 }
293                 // Usernames autogenerated have 'autogen_' prefix and can be changed
294                 // by the user from the account section. After this process it cannot
295                 // be changed anymore.
296                 $data['username'] = 'autogen_' . $data['username'];
297                 
298                 // Country
299                 if (empty($ax_country) || is_a($ax_country, 'Auth_OpenID_AX_Error'))
300                         $data['country'] = $sreg_country;
301                 else
302                         $data['country'] = $ax_country[0];
303                 
304                 // Birth Date
305                 $data['birth_date'] = $sreg_dob;
306                 
307                 // OpenID
308                 $data['auth_src'] = 'openid';
309                 
310                 if (!$this->register($data, $op_response->getDisplayIdentifier()))
311                         return FALSE;
312                 
313                 $query = $this->db->query("SELECT id from `users`
314                         WHERE username = '{$data['username']}'");
315                 return $query->row()->id;
316         }
317         
318         /**
319          * Converts an array returned by LDAP login to an array which contains
320          * user data ready to be used in `users` DB.
321          * 
322          * @param array $ldap_userdata
323          * @return array
324          */
325         public function convert_ldap_userdata($ldap_userdata)
326         {
327                 $userdata['username'] = $ldap_userdata['uid'][0];
328                 $userdata['email'] = $ldap_userdata['mail'][0];
329                 $userdata['first_name'] = $ldap_userdata['givenname'][0];
330                 $userdata['last_name'] = $ldap_userdata['sn'][0];
331                 
332                 $userdata['auth_src'] = 'ldap';
333                 
334                 return $userdata;
335         }
336         
337         /**
338         * Login with LDAP.
339         *
340         * @param string $username
341         * @param string $password
342         * @return boolean
343         * @author  Alex HeriÈ™anu, Răzvan Deaconescu, Călin-Andrei Burloiu
344         */
345         public function ldap_login($username, $password)
346         {
347                 $this->config->load('ldap');
348                 
349                 // First connection: binding.
350                 // TODO exception
351                 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server.\n");
352                 if (!@ldap_bind($ds, $this->config->item('ldap_bind_user'),
353                         $this->config->item('ldap_bind_password'))) 
354                 {
355                         ldap_close($ds);
356                         die("Can't connect to ".$this->config->item('ldap_server')."\n");
357                         return FALSE;
358                 }
359                 $sr = ldap_search($ds, "dc=cs,dc=curs,dc=pub,dc=ro", "(uid=" . $username . ")");
360                 if (ldap_count_entries($ds, $sr) > 1)
361                 die("Multiple entries with the same uid in LDAP database??");
362                 if (ldap_count_entries($ds, $sr) < 1) {
363                         ldap_close($ds);
364                         return FALSE;
365                 }
366                 
367                 $info = ldap_get_entries($ds, $sr);
368                 $dn = $info[0]["dn"];
369                 ldap_close($ds);
370                 
371                 // Second connection: connect with user's credentials.
372                 $ds = ldap_connect($this->config->item('ldap_server')) or die("Can't connect to ldap server\n");
373                 if (!@ldap_bind($ds, $dn, $password) or $password == '') {
374                         ldap_close($ds);
375                         return FALSE;
376                 }
377                 
378                 // Verifify if DN belongs to the requested OU.
379                 $info[0]['ou_ok'] = $this->ldap_dn_belongs_ou( $dn, $this->config->item('ldap_req_ou') );
380                 
381                 // Set authentication source.
382                 $info[0]['auth_src'] = 'ldap_first_time';
383                 
384                 return $info[0];
385         }
386         
387         /**
388         * Verify if a user belongs to a group.
389         * 
390         * @param string $dn = "ou=Student,ou=People..."
391         * @param array $ou = array ("Student", etc
392         * @return TRUE or FALSE
393         * @author  Răzvan HeriÈ™anu, Răzvan Deaconescu, Călin-Andrei Burloiu
394         */
395         public function ldap_dn_belongs_ou($dn, $ou)
396         {
397                 if (!is_array($ou))
398                         $ou = array ($ou);
399                 
400                 $founded = FALSE;
401                 $words = explode(',', $dn);
402                 foreach ($words as $c) {
403                         $parts = explode("=", $c);
404                         $key = $parts[0];
405                         $value = $parts[1];
406                 
407                         if (strtolower($key) == "ou" && in_array($value, $ou) )
408                                 $founded = TRUE;
409                 }
410                 
411                 return $founded;
412         }
413         
414         /**
415          * Adds a new user to DB.
416          * Do not add join_date and last_login column, they will be automatically
417          * added.
418          * Provide an $openid with the OpenID as value in order to register users
419          * logging in this way.
420          * 
421          * @param array $data   corresponds to DB columns
422          */
423         public function register($data, $openid = NULL)
424         {
425                 $this->load->helper('array');
426                 
427                 // TODO verify mandatory data existance
428                 
429                 // Process data.
430                 if (isset($data['password']))
431                         $data['password'] = sha1($data['password']);
432                 
433                 if (empty($data['birth_date']))
434                         $data['birth_date'] = NULL;
435                 
436                 $cols = '';
437                 $vals = '';
438                 foreach ($data as $col=> $val)
439                 {
440                         if ($val === NULL)
441                         {
442                                 $cols .= "$col, ";
443                                 $vals .= "NULL, ";
444                                 continue;
445                         }
446                                 
447                         $cols .= "$col, ";
448                         if (is_int($val))
449                                 $vals .= "$val, ";
450                         else if (is_string($val))
451                                 $vals .= "'$val', ";
452                 }
453                 $cols = substr($cols, 0, -2);
454                 $vals = substr($vals, 0, -2);
455                 
456                 $query = $this->db->query("INSERT INTO `users`
457                         ($cols, registration_date, last_login)
458                         VALUES ($vals, utc_timestamp(), utc_timestamp())");
459                 if ($query === FALSE)
460                         return FALSE;
461                 
462                 // If registered with OpenID insert a row in `users_openid`.
463                 if ($openid)
464                 {
465                         // Find user_id.
466                         $query = $this->db->query("SELECT id from `users`
467                                 WHERE username = '{$data['username']}'");
468                         if ($query->num_rows() === 0)
469                                 return FALSE;
470                         $user_id = $query->row()->id;
471                         
472                         // Insert row in `users_openid`.
473                         $query = $this->db->query("INSERT INTO `users_openid`
474                                 (openid_url, user_id)
475                                 VALUES ('$openid', $user_id)");
476                         if (!$query)
477                                 return FALSE;
478                 }
479                 
480                 // If registered with internal authentication it needs to activate
481                 // the account.
482                 if ($data['auth_src'] == 'internal')
483                 {
484                         $activation_code = Users_model::gen_activation_code($data['username']);
485                         $user_id = $this->get_user_id($data['username']);
486                         $query = $this->db->query("INSERT INTO `users_unactivated`
487                                 (user_id, activation_code)
488                                 VALUES ($user_id, '$activation_code')");
489                         $this->send_activation_email($user_id, $data['email'],
490                                 $activation_code, $data['username']);
491                 }
492                 
493                 // TODO exception on failure
494                 return $query;
495         }
496         
497         public function get_user_id($username)
498         {
499                 $query = $this->db->query("SELECT id FROM `users`
500                         WHERE username = '$username'");
501                 
502                 if ($query->num_rows() === 0)
503                         return FALSE;
504                 
505                 return $query->row()->id;
506         }
507         
508         /**
509          * Removes users that didn't activated their account within $days_to_expire
510          * days inclusively.
511          * 
512          * @param int $days_to_expire 
513          */
514         public function cleanup_unactivated_users($days_to_expire)
515         {
516                 // Get user_id-s with expired activation period.
517                 $query = $this->db->query("SELECT u.id
518                         FROM `users` u, `users_unactivated` a
519                         WHERE u.id = a.user_id
520                                 AND DATEDIFF(CURRENT_DATE(), u.registration_date) > $days_to_expire");
521                 
522                 if ($query->num_rows() > 0)
523                 {
524                         $str_user_ids = '';
525                         $results = $query->result();
526                         foreach ($results as $result)
527                                 $str_user_ids .= "{$result->id}, ";
528                         $str_user_ids = substr($str_user_ids, 0, -2);
529                 }
530                 else
531                         return FALSE;
532                 
533                 // Delete from `users` table.
534                 $ret = $this->db->query("DELETE FROM `users`
535                         WHERE id IN ($str_user_ids)");
536                 if (!$ret)
537                         return FALSE;
538                 
539                 // Delete from `users_unactivated table.
540                 $ret = $this->db->query("DELETE FROM `users_unactivated`
541                         WHERE user_id IN ($str_user_ids)");
542                 if (!$ret)
543                         return FALSE;
544                 
545                 // Success
546                 return TRUE;
547         }
548         
549         /**
550          * Activated an account for an user having $user_id with $activation_code.
551          * 
552          * @param int $user_id
553          * @param string $activation_code       hexa 16 characters string
554          * @return returns TRUE if activation was successful and FALSE otherwise
555          */
556         public function activate_account($user_id, $activation_code)
557         {
558                 $query = $this->db->query("SELECT * FROM `users_unactivated`
559                         WHERE user_id = $user_id
560                                 AND activation_code = '$activation_code'");
561                 
562                 if ($query->num_rows() === 0)
563                         return FALSE;
564                 
565                 $this->db->query("DELETE FROM `users_unactivated`
566                         WHERE user_id = $user_id");
567                 
568                 return TRUE;
569         }
570         
571         public function send_activation_email($user_id, $email = NULL,
572                         $activation_code = NULL, $username = NULL)
573         {
574                 if (!$activation_code || !$email || !$username)
575                 {
576                         if (!$email)
577                                 $cols = 'email, ';
578                         else
579                                 $cols = '';
580                         
581                         $userdata = $this->get_userdata($user_id,
582                                         $cols. "a.activation_code, username");
583                         $activation_code =& $userdata['activation_code'];
584                         
585                         if (!$email)
586                                 $email =& $userdata['email'];
587                         $username =& $userdata['username'];
588                 }
589                 
590                 if ($activation_code === NULL)
591                         return TRUE;
592                 
593                 $subject = '['. $this->config->item('site_name')
594                                 . '] Account Activation';
595                 $activation_url =
596                                 site_url("user/activate/$user_id/code/$activation_code"); 
597                 $msg = sprintf($this->lang->line('user_activation_email_content'),
598                         $username, $this->config->item('site_name'), site_url(),
599                         $activation_url, $activation_code);
600                 $headers = "From: ". $this->config->item('noreply_email');
601                 
602                 return mail($email, $subject, $msg, $headers);
603         }
604         
605         public function recover_password($username, $email)
606         {
607                 $userdata = $this->get_userdata($username, 'email, username, id');
608                 
609                 if (strcmp($userdata['email'], $email) !== 0)
610                         return FALSE;
611                 
612                 $recovered_password = Users_model::gen_password();
613                 
614                 $this->set_userdata(intval($userdata['id']), array('password'=> 
615                                 $recovered_password));
616                 
617                 $subject = '['. $this->config->item('site_name')
618                 . '] Password Recovery';
619                 $msg = sprintf($this->lang->line('user_password_recovery_email_content'),
620                         $username, $this->config->item('site_name'), site_url(),
621                         $recovered_password);
622                 $headers = "From: ". $this->config->item('noreply_email');
623                 
624                 mail($email, $subject, $msg, $headers);
625                 
626                 return TRUE;
627         }
628         
629         /**
630          * Returns data from `users` table. If $user is int it is used as an
631          * id, if it is string it is used as an username.
632          * 
633          * @param mixed $user
634          * @param string $table_cols    (optional) string with comma separated
635          * `users` table column names. Use a.activation_code to check user's
636          * account activation_code. If this value is NULL than the account is
637          * active.
638          * @return array        associative array with userdata from DB
639          */
640         public function get_userdata($user, $table_cols = '*')
641         {
642                 if (is_int($user))
643                         $cond = "id = $user";
644                 else
645                         $cond = "username = '$user'";
646                 
647                 $query = $this->db->query("SELECT $table_cols
648                         FROM `users` u LEFT JOIN `users_unactivated` a
649                                 ON (u.id = a.user_id)
650                         WHERE $cond");
651                 
652                 if ($query->num_rows() === 0)
653                         return FALSE;
654                 
655                 $userdata = $query->row_array();
656                 
657                 // Post process userdata.
658                 if (isset($userdata['picture']))
659                 {
660                         $userdata['picture_thumb'] = site_url(
661                                 "data/user_pictures/{$userdata['picture']}-thumb.jpg");
662                         $userdata['picture'] = site_url(
663                                 "data/user_pictures/{$userdata['picture']}");
664                 } 
665                 
666                 return $userdata;
667         }
668         
669         /**
670          * Modifies data from `users` table for user with $user_id.
671          * 
672          * @param int $user_id
673          * @param array $data   key-value pairs with columns and new values to be
674          * modified
675          * @return boolean      returns TRUE on success and FALSE otherwise
676          */
677         public function set_userdata($user_id, $data)
678         {
679                 // TODO verify mandatory data existance
680                 
681                 // Process data.
682                 if (isset($data['password']))
683                         $data['password'] = sha1($data['password']);
684                 // TODO picture data: save, convert, make it thumbnail
685                 
686                 if (empty($data['birth_date']))
687                         $data['birth_date'] = NULL;
688                 
689                 $set = '';
690                 foreach ($data as $col => $val)
691                 {
692                         if ($val === NULL)
693                         {
694                                 $set .= "$col = NULL, ";
695                                 continue;
696                         }
697                         
698                         if (is_int($val))
699                                 $set .= "$col = $val, ";
700                         else if (is_string($val))
701                                 $set .= "$col = '$val', ";
702                 }
703                 $set = substr($set, 0, -2);
704                 
705                 $query_str = "UPDATE `users`
706                         SET $set WHERE id = $user_id";
707                 //echo "<p>$query_str</p>";
708                 $query = $this->db->query($query_str);
709                 
710                 // TODO exception
711                 return $query;
712         }
713         
714         public static function gen_activation_code($str = '')
715         {
716                 $ci =& get_instance();
717                 
718                 $activation_code = substr(
719                         sha1(''. $str. $ci->config->item('encryption_key')
720                                 . mt_rand()),
721                         0,
722                         16);
723                 
724                 return $activation_code;
725         }
726         
727         public static function gen_password()
728         {
729                 $ci =& get_instance();
730                 $length = 16;
731                 $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!_-';
732                 $len_chars = strlen($chars);
733                 $enc_key = $ci->config->item('encryption_key');
734                 $len_enc_key = strlen($enc_key);
735                 $password = '';
736                 
737                 for ($p = 0; $p < $length; $p++) 
738                 {
739                         $i = (mt_rand(1, 100) * ord($enc_key[ mt_rand(0, $len_enc_key-1) ]))
740                                 % $len_chars;
741                         $password .= $chars[$i];
742                 }
743                 
744                 return $password;
745         }
746         
747         public static function gen_username()
748         {
749                 $chars = 'abcdefghijklmnopqrstuvwxyz0123456789._';
750                 $len_chars = strlen($chars);
751                 $len = 8;
752                 $username = '';
753                 
754                 for ($i = 0; $i < $len; $i++)
755                         $username .= $chars[ mt_rand(0, $len_chars - 1) ];
756                 
757                 return $username;
758         }
759         
760         public static function roles_to_string($roles)
761         {
762                 $ci =& get_instance();
763                 $ci->lang->load('user');
764                 
765                 if ($roles == USER_ROLE_STANDARD)
766                         return $ci->lang->line('user_role_standard');
767                 else
768                 {
769                         $str_roles = '';
770                         
771                         if ($roles & USER_ROLE_ADMIN)
772                                 $str_roles .= $ci->lang->line('user_role_admin') . '; ';
773                 }
774                 
775                 return $str_roles;
776         }
777 }
778
779 /* End of file users_model.php */
780 /* Location: ./application/models/users_model.php */