unactivated users CLI cleanup; user management bugs fixed; working at CAPTCHA
authorCalin-Andrei Burloiu <calin.burloiu@gmail.com>
Thu, 3 Nov 2011 14:49:11 +0000 (16:49 +0200)
committerCalin-Andrei Burloiu <calin.burloiu@gmail.com>
Thu, 3 Nov 2011 14:49:11 +0000 (16:49 +0200)
application/config/captcha.php [new file with mode: 0644]
application/config/form_validation.php
application/controllers/admin.php [deleted file]
application/controllers/admin_cli.php [new file with mode: 0644]
application/controllers/user.php
application/language/english/user_lang.php
application/libraries/Captcha.php [new file with mode: 0644]
application/models/users_model.php
application/views/user/register_view.php

diff --git a/application/config/captcha.php b/application/config/captcha.php
new file mode 100644 (file)
index 0000000..fe117d1
--- /dev/null
@@ -0,0 +1,6 @@
+<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+
+$config['captcha_params'] = array(
+       'img_path' => './img/captcha/',
+       'img_url' => site_url('img/captcha/')
+);
\ No newline at end of file
index b11b331..042d5f7 100644 (file)
@@ -42,7 +42,7 @@ $config = array(
                array(
                        'field'=>'old-password',
                        'label'=>'lang:user_old_password',
-                       'rules'=>'min_length[5]|max_length[32]|callback__valid_old_password[username]'
+                       'rules'=>'min_length[5]|max_length[32]|callback__valid_old_password'
                ),
                array(
                        'field'=>'new-password',
@@ -69,6 +69,11 @@ $config = array(
                        'label'=>'lang:user_last_name',
                        'rules'=>'trim|required|ucwords|xss_clean|prep_for_form'
                ),
+               array(
+                       'field'=>'sex',
+                       'label'=>'lang:user_sex',
+                       'rules'=>'required|xss_clean|prep_for_form'
+               ),
                array(
                        'field'=>'birth-date',
                        'label'=>'lang:user_birth_date',
diff --git a/application/controllers/admin.php b/application/controllers/admin.php
deleted file mode 100644 (file)
index 2951570..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-<?php
-
-/**
- * Class Admin controls site administration features
- *
- * @category   Controller
- * @author             Călin-Andrei Burloiu
- */
-class Admin extends CI_Controller {
-       
-       public function index()
-       {
-               
-       }
-}
-
-/* End of file admin.php */
-/* Location: ./application/controllers/admin.php */
diff --git a/application/controllers/admin_cli.php b/application/controllers/admin_cli.php
new file mode 100644 (file)
index 0000000..604c07f
--- /dev/null
@@ -0,0 +1,45 @@
+<?php
+
+/**
+ * Class Admin_cli controls site administration features
+ *
+ * @category   Controller
+ * @author             Călin-Andrei Burloiu
+ */
+class Admin_cli extends CI_Controller {
+       
+       public function __construct()
+       {
+               parent::__construct();
+               
+               if (!$this->input->is_cli_request())
+               {
+                       die("This controller is allowed only from CLI!");
+               }
+       }
+       
+       public function index()
+       {               
+       }
+       
+       /**
+        * Removes users that didn't activated their account within
+        * $days_to_expire days inclusively.
+        * 
+        * @param int $days_to_expire 
+        */
+       public function cleanup_unactivated_users($days_to_expire = 2)
+       {
+               $days_to_expire = intval($days_to_expire);
+               
+               $this->load->model('users_model');
+               
+               if ($this->users_model->cleanup_unactivated_users($days_to_expire))
+                       echo "Users unactivated within $days_to_expire days were successfully deleted from the database.".PHP_EOL;
+               else
+                       echo "No users were deleted.".PHP_EOL;
+       }
+}
+
+/* End of file admin_cli.php */
+/* Location: ./application/controllers/admin_cli.php */
index 5820379..810069d 100644 (file)
@@ -26,7 +26,24 @@ class User extends CI_Controller {
        
        public function test($user_id = 1)
        {
-               echo ($this->users_model->get_userdata('calin.burloiu') ? 'd' : 'n');
+//             echo ($this->users_model->get_userdata('calin.burloiu') ? 'd' : 'n');
+       }
+       
+       // DEBUG
+       public function show_session()
+       {
+               if (ENVIRONMENT == 'production')
+                       die();
+                       
+               var_dump($this->session->all_userdata());
+       }
+       // DEBUG
+       public function destroy_session()
+       {
+               if (ENVIRONMENT == 'production')
+                       die();
+                       
+               $this->session->sess_destroy();
        }
 
        /**
@@ -165,6 +182,8 @@ class User extends CI_Controller {
                $this->load->library('form_validation');
                $this->load->helper('localization');
                $this->load->helper('date');
+               
+               $user_id = $this->session->userdata('user_id');
                        
                $this->form_validation->set_error_delimiters('<span class="error">',
                                        '</span>');
@@ -192,16 +211,15 @@ class User extends CI_Controller {
                }
                else
                        $b_validation = FALSE;
-               
+
                if (! $b_validation)
                {
                        // Edit account data if logged in, otherwise register.
-                       $user_id = $this->session->userdata('user_id');
                        if ($user_id)
                        {
                                $userdata = $this->users_model->get_userdata(intval($user_id));
                                if (substr($userdata['username'], 0, 8) == 'autogen_')
-                                       $userdata['autogen_username'] = //'xxx';
+                                       $userdata['autogen_username'] =
                                                substr($userdata['username'], 8);
                                $selected_menu = 'account';
                        }
@@ -238,12 +256,14 @@ class User extends CI_Controller {
                }
                else
                {
-                       $user_id = $this->input->post('user-id');
+                       // TODO: Security problem!
+                       //$user_id = $this->input->post('user-id');
                        if ($this->input->post('username'))
                                $data['username'] = $this->input->post('username');
                        $data['email'] = $this->input->post('email');
                        $data['first_name'] = $this->input->post('first-name');
                        $data['last_name'] = $this->input->post('last-name');
+                       $data['sex'] = intval($this->input->post('sex'));
                        $data['birth_date'] = $this->input->post('birth-date');
                        $data['country'] = $this->input->post('country');
                        $data['locality'] = $this->input->post('locality');
@@ -270,6 +290,7 @@ class User extends CI_Controller {
                                                . $upload_data['file_name']. '-thumb.jpg', 120, 90);
                        }
                        
+                       // TODO: To much info as session data?
                        // Update session user data.
                        $this->_update_session_userdata($data);
                        
@@ -278,7 +299,7 @@ class User extends CI_Controller {
                        {
                                $password = $this->input->post('new-password');
                                if ($password)
-                                       $data['password'] = $this->input->post('new-password');
+                                       $data['password'] = $password;
                                
                                $this->users_model->set_userdata($user_id, $data);
                                
@@ -290,6 +311,7 @@ class User extends CI_Controller {
                        {
                                $data['username'] = $this->input->post('username');
                                $data['password'] = $this->input->post('password');
+                               $data['auth_src'] = 'internal';
                                
                                $this->users_model->register($data);
                                $user_id = $this->users_model->get_userdata($data['username'],
@@ -543,7 +565,10 @@ class User extends CI_Controller {
        public function _update_session_userdata($data)
        {
                foreach ($data as $key=> $val)
-                       $this->session->set_userdata($key, $val);
+               {
+                       if ($this->session->userdata($key))
+                               $this->session->set_userdata($key, $val);
+               }
        }
        
        public function _is_username_unique($username)
@@ -586,12 +611,12 @@ class User extends CI_Controller {
                return $date;
        }
        
-       public function _valid_old_password($old_password, $field_username)
+       public function _valid_old_password($old_password)
        {
                if (! $old_password)
                        return TRUE;
                
-               $username= $this->input->post($field_username);
+               $username= $this->session->userdata('username');
                
                if ($this->users_model->login($username, $old_password))
                        return TRUE;
@@ -611,7 +636,7 @@ class User extends CI_Controller {
        
        public function _required_by_register($param)
        {
-               $user_id = $this->input->post('user-id');
+               $user_id = $this->session->userdata('user_id');
                
                if (! $user_id && ! $param)
                        return FALSE;
index a5ba105..898e0ae 100644 (file)
@@ -16,6 +16,9 @@ $lang['user_new_password_confirmation'] = 'New Password Confirmation';
 $lang['user_email'] = 'E-mail';
 $lang['user_first_name'] = 'First Name';
 $lang['user_last_name'] = 'Surname';
+$lang['user_sex'] = 'Sex';
+$lang['user_sex_male'] = 'Male';
+$lang['user_sex_female'] = 'Female';
 $lang['user_birth_date'] = 'Birth Date';
 $lang['user_date_format_hint'] = 'use format YEAR-MONTH-DAY';
 $lang['user_country'] = 'Country';
diff --git a/application/libraries/Captcha.php b/application/libraries/Captcha.php
new file mode 100644 (file)
index 0000000..fc41471
--- /dev/null
@@ -0,0 +1,78 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
+
+class Captcha {
+       
+       private $ci = NULL;
+       private $db;
+       private $params = NULL;
+       
+       public function __construct()
+       {
+               $this->ci =& get_instance();
+               $this->ci->config->load('captcha');
+               $this->ci->load->library('Singleton_db');
+               $this->db = $this->ci->singleton_db->connect();
+               
+               $this->params = $this->ci->config->item('captcha_params');
+               
+               if (!$this->params)
+                       die('Cannot load CAPTCHA config file.');
+       }
+       
+       /**
+        * Generates a CAPTCHA image and returns an HTML image tag for it.
+        * 
+        * @param string $word
+        * @return string
+        */
+       public function get_captcha_tag($word = NULL)
+       {
+               $this->load->helper('captcha');
+               
+               if ($word)
+                       $this->params['word'] = $word;
+
+               $cap = create_captcha($this->params);
+
+               $data = array(
+                       'captcha_time' => $cap['time'],
+                       'ip_address' => $this->input->ip_address(),
+                       'word' => $cap['word']
+                       );
+
+               $str_query = $this->db->insert_string('captcha', $data);
+               $this->db->query($str_query);
+
+               return $cap['image'];
+       }
+       
+       /**
+        * Check againt the DB if the word(s) entered by the user ($word) matches
+        * the CAPTCHA and if the CAPTCHA did not expired.
+        */
+       public function check_captcha($word)
+       {
+               // First, delete old captchas
+               $expiration_limit = (!$this->params['expiration']
+                               ? 7200 : $this->params['expiration']);
+               $expiration = time() - $expiration_limit; // Two hour limit
+               $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
+               // TODO also delete the CAPTCHA image file
+
+               // Then see if a captcha exists:
+               $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
+               $binds = array($word, $this->input->ip_address(), $expiration);
+               $query = $this->db->query($sql, $binds);
+               $row = $query->row();
+
+               if ($row->count == 0)
+               {
+                       return FALSE;
+               }
+               
+               return TRUE;
+       }
+}
+
+/* End of file Captcha.php */
+/* Location: ./application/libraries/Captcha.php */
index 252a5db..85ad649 100644 (file)
@@ -415,7 +415,7 @@ class Users_model extends CI_Model {
         * Adds a new user to DB.
         * Do not add join_date and last_login column, they will be automatically
         * added.
-        * Provide an 'openid' with the OpenID as value in order to register users
+        * Provide an $openid with the OpenID as value in order to register users
         * logging in this way.
         * 
         * @param array $data   corresponds to DB columns
@@ -505,10 +505,45 @@ class Users_model extends CI_Model {
                return $query->row()->id;
        }
        
-       // TODO cleanup account activation
-       public function cleanup_account_activation()
+       /**
+        * Removes users that didn't activated their account within $days_to_expire
+        * days inclusively.
+        * 
+        * @param int $days_to_expire 
+        */
+       public function cleanup_unactivated_users($days_to_expire)
        {
+               // Get user_id-s with expired activation period.
+               $query = $this->db->query("SELECT u.id
+                       FROM `users` u, `users_unactivated` a
+                       WHERE u.id = a.user_id
+                               AND DATEDIFF(CURRENT_DATE(), u.registration_date) > $days_to_expire");
                
+               if ($query->num_rows() > 0)
+               {
+                       $str_user_ids = '';
+                       $results = $query->result();
+                       foreach ($results as $result)
+                               $str_user_ids .= "{$result->id}, ";
+                       $str_user_ids = substr($str_user_ids, 0, -2);
+               }
+               else
+                       return FALSE;
+               
+               // Delete from `users` table.
+               $ret = $this->db->query("DELETE FROM `users`
+                       WHERE id IN ($str_user_ids)");
+               if (!$ret)
+                       return FALSE;
+               
+               // Delete from `users_unactivated table.
+               $ret = $this->db->query("DELETE FROM `users_unactivated`
+                       WHERE user_id IN ($str_user_ids)");
+               if (!$ret)
+                       return FALSE;
+               
+               // Success
+               return TRUE;
        }
        
        /**
index dd97e2e..e038dfc 100644 (file)
@@ -7,7 +7,7 @@ function _set_value($userdata, $field, $default = '')
                return $post_value;
 
        return ($post_value === $default 
-               ? $userdata[ str_replace('-','_',$field) ]
+               ? ''.$userdata[ str_replace('-','_',$field) ]
                : $post_value);
 }
 
@@ -17,10 +17,10 @@ else
        echo form_open_multipart("user/account/$redirect");
 ?>
 
-<?php if ($userdata): ?>
+<!--<?php if ($userdata): ?>
 <input type="hidden" name="user-id" value="<?php echo $userdata['id'] ?>" />
 <input type="hidden" name="username" value="<?php echo $userdata['username'] ?>" />
-<?php endif ?>
+<?php endif ?>-->
 
 <table class="form">
        <tr>
@@ -44,6 +44,7 @@ else
                <th><?php echo $this->lang->line('user_username'). ' : ' ?></th>
                <td>
                        &nbsp;<em><?php echo $userdata['username'] ?></em>
+                       <!--<input type="hidden" name="username" value="<?php echo $userdata['username'] ?>" />-->
                </td>
          <?php endif ?>
        </tr>
@@ -119,6 +120,19 @@ else
        </tr>
        <tr><td></td><td><?php echo form_error('last-name') ?></td></tr>
        
+       <tr>
+               <th><?php echo $this->lang->line('user_sex'). ' <span class="required">*</span> : ' ?></th>
+               <td>
+                       <?php echo form_dropdown('sex', 
+                               array(
+                                       '0'=> $this->lang->line('user_sex_male'),
+                                       '1'=> $this->lang->line('user_sex_female')),
+                               _set_value($userdata, 'sex', '0')
+                       ) ?>
+               </td>
+       </tr>
+       <tr><td></td><td><?php echo form_error('sex') ?></td></tr>
+       
        <tr>
                <th><?php echo $this->lang->line('user_birth_date'). ' : ' ?></th>
                <td>