OpenID login and comment improoved
[living-lab-site.git] / application / controllers / user.php
1 <?php
2
3 /**
4  * Class User controls video hierarchy and searching
5  *
6  * @category    Controller
7  * @author              Călin-Andrei Burloiu
8  */
9 class User extends CI_Controller {
10
11         private $import = FALSE;
12         private $activated_account = TRUE;
13         private $user_id = NULL;
14
15         public function __construct()
16         {
17                 parent::__construct();
18
19                 $this->lang->load('user');
20                 $this->load->model('users_model');
21         }
22
23         public function index()
24         {
25         }
26         
27         public function test($user_id = 1)
28         {
29                 echo ($this->users_model->get_userdata('calin.burloiu') ? 'd' : 'n');
30         }
31
32         /**
33         * Login a user and then redirect it to the last page which must be encoded
34         * in $redirect.
35         *
36         * @param string $redirect       contains the last page URI segments encoded
37         * with helper url_encode_segments.
38         */
39         public function login($redirect = '')
40         {
41                 $this->load->library('form_validation');
42                 $this->form_validation->set_error_delimiters('<span class="error">',
43                         '</span>');
44                 
45                 // Normal or OpenID login?
46                 if ($this->input->post('openid') !== FALSE)
47                         $b_openid = TRUE;
48                 else
49                         $b_openid = FALSE;
50                 // Validate the correct form.
51                 $res_form_validation = FALSE;
52                 if (!$b_openid)
53                         $res_form_validation = $this->form_validation->run('login');
54                 else
55                         $res_form_validation = $this->form_validation->run('login_openid');
56
57                 if ($res_form_validation === FALSE)
58                 {
59                         $params = array(        'title' =>
60                                                                         $this->lang->line('ui_nav_menu_login')
61                                                                                 .' &ndash; '
62                                                                                 . $this->config->item('site_name'),
63                                                                 //'metas' => array('description'=>'')
64                         );
65                         $this->load->library('html_head_params', $params);
66                                 
67                         // **
68                         // ** LOADING VIEWS
69                         // **
70                         $this->load->view('html_begin', $this->html_head_params);
71                         $this->load->view('header', array('selected_menu' => 'login'));
72
73                         $main_params['content'] = $this->load->view('user/login_view',
74                                 array('redirect'=> $redirect), TRUE);
75                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
76                         $this->load->view('main', $main_params);
77                                 
78                         $this->load->view('footer');
79                         $this->load->view('html_end');
80                 }
81                 else
82                 {
83                         if ($b_openid)
84                         {
85                                 $this->users_model->openid_begin_login(
86                                                 $this->input->post('openid'));
87                                 return;
88                         }
89                         
90                         // Without OpenID
91                         if (! $this->activated_account)
92                                 header('Location: '
93                                         . site_url("user/activate/{$this->user_id}"));
94                         else if (! $this->import)
95                         {
96                                 // Redirect to last page before login. 
97                                 header('Location: '. site_url(urldecode_segments($redirect)));
98                         }
99                         else
100                         {
101                                 // Redirect to account page because an user authenticates here
102                                 // for the first time with external authentication. The page
103                                 // will display imported data.
104                                 header('Location: '. site_url('user/account'));
105                         }
106                 }
107         }
108         
109         public function check_openid_login()
110         {
111                 $user = $this->users_model->openid_complete_login();
112                 
113                 // Authentication failed.
114                 if ($user == Auth_OpenID_CANCEL)
115                 {
116                         $this->load->helper('message');
117                         show_error_msg_page($this, $this->lang->line('openid_cancel'));
118                         return;
119                 }               
120                 else if ($user == Auth_OpenID_FAILURE)
121                 {
122                         $this->load->helper('message');
123                         show_error_msg_page($this, $this->lang->line('openid_failure'));
124                         return;
125                 }
126
127                 // Authentication successful: set session with user data.
128                 $this->session->set_userdata(array(
129                         'user_id'=> $user['id'],
130                         'username'=> $user['username'],
131                         'auth_src'=> $user['auth_src'],
132                         'time_zone'=> $user['time_zone']
133                 ));
134                 
135                 if ($user['import'])
136                         header('Location: '. site_url('user/account'));
137                 else
138                         header('Location: '. site_url());
139         }
140         
141         public function openid_policy()
142         {
143                 $this->load->view('openid_policy_view');
144         }
145         
146         /**
147          * Logout user and then redirect it to the last page which must be encoded
148          * in $redirect.
149          * 
150          * @param string $redirect      contains the last page URI segments encoded
151          * with helper url_encode_segments.
152          */
153         public function logout($redirect = '')
154         {
155                 $this->session->unset_userdata('user_id');
156                 $this->session->unset_userdata('username');
157                 $this->session->unset_userdata('auth_src');
158                 $this->session->unset_userdata('time_zone');
159                 
160                 header('Location: '. site_url(urldecode_segments($redirect)));
161         }
162         
163         public function register($redirect = '')
164         {
165                 $this->load->library('form_validation');
166                 $this->load->helper('localization');
167                 $this->load->helper('date');
168                         
169                 $this->form_validation->set_error_delimiters('<span class="error">',
170                                         '</span>');
171                 $error_upload = '';
172
173                 if ($this->form_validation->run('register'))
174                 {
175                         $b_validation = TRUE;
176                         
177                         if ($_FILES['picture']['tmp_name'])
178                         {
179                                 // Upload library
180                                 $config_upload['upload_path'] = './data/user_pictures';
181                                 $config_upload['file_name'] = 
182                                         str_replace('.', '-', $this->input->post('username')) .'-';
183                                 $config_upload['allowed_types'] = 'gif|jpg|png';
184                                 $config_upload['max_size'] = '10240';
185                                 $this->load->library('upload', $config_upload);
186                                 
187                                 $b_validation = $this->upload->do_upload('picture');
188                                 $error_upload = 
189                                         $this->upload->display_errors('<span class="error">',
190                                                         '</span>');
191                         }
192                 }
193                 else
194                         $b_validation = FALSE;
195                 
196                 if (! $b_validation)
197                 {
198                         // Edit account data if logged in, otherwise register.
199                         $user_id = $this->session->userdata('user_id');
200                         if ($user_id)
201                         {
202                                 $userdata = $this->users_model->get_userdata(intval($user_id));
203                                 if (substr($userdata['username'], 0, 8) == 'autogen_')
204                                         $userdata['autogen_username'] = //'xxx';
205                                                 substr($userdata['username'], 8);
206                                 $selected_menu = 'account';
207                         }
208                         else
209                         {
210                                 $userdata = FALSE;
211                                 $selected_menu = 'register';
212                         }
213                         
214                         $params = array('title' =>
215                                                                 $this->lang->line('ui_nav_menu_register')
216                                                                         .' &ndash; '
217                                                                         . $this->config->item('site_name'),
218                                                         //'metas' => array('description'=>'')
219                         );
220                         $this->load->library('html_head_params', $params);
221                 
222                         // **
223                         // ** LOADING VIEWS
224                         // **
225                         $this->load->view('html_begin', $this->html_head_params);
226                         $this->load->view('header', 
227                                 array('selected_menu' => $selected_menu));
228                         
229                         $main_params['content'] = $this->load->view('user/register_view', 
230                                 array('userdata'=> $userdata, 'redirect'=> $redirect,
231                                         'error_upload'=> $error_upload),
232                                 TRUE);
233                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
234                         $this->load->view('main', $main_params);
235                 
236                         $this->load->view('footer');
237                         $this->load->view('html_end');
238                 }
239                 else
240                 {
241                         $user_id = $this->input->post('user-id');
242                         if ($this->input->post('username'))
243                                 $data['username'] = $this->input->post('username');
244                         $data['email'] = $this->input->post('email');
245                         $data['first_name'] = $this->input->post('first-name');
246                         $data['last_name'] = $this->input->post('last-name');
247                         $data['birth_date'] = $this->input->post('birth-date');
248                         $data['country'] = $this->input->post('country');
249                         $data['locality'] = $this->input->post('locality');
250                         $data['ui_lang'] = $this->input->post('ui-lang');
251                         $data['time_zone'] = $this->input->post('time-zone');
252                         
253                         // Handle picture if one was uploaded.
254                         if ($_FILES['picture']['tmp_name'])
255                         {
256                                 $upload_data = $this->upload->data();
257                                 $this->load->library('image');
258                                 $this->image->load($upload_data['full_path']);
259                                 // Resize original to a maximum size.
260                                 if ($this->image->get_width() * $this->image->get_height()
261                                                 > 640*480)
262                                 {
263                                         $this->image->save_thumbnail(
264                                                 $upload_data['full_path'],
265                                                 640, 480, IMAGETYPE_AUTO);
266                                 }
267                                 // Create thumbnail.
268                                 $data['picture'] = $upload_data['file_name'];
269                                 $this->image->save_thumbnail($upload_data['file_path']
270                                                 . $upload_data['file_name']. '-thumb.jpg', 120, 90);
271                         }
272                         
273                         // Update session user data.
274                         $this->_update_session_userdata($data);
275                         
276                         // Edit account data
277                         if ($user_id)
278                         {
279                                 $password = $this->input->post('new-password');
280                                 if ($password)
281                                         $data['password'] = $this->input->post('new-password');
282                                 
283                                 $this->users_model->set_userdata($user_id, $data);
284                                 
285                                 // Redirect to last page before login.
286                                 header('Location: '. site_url(urldecode_segments($redirect)));
287                         }
288                         // Registration
289                         else
290                         {
291                                 $data['username'] = $this->input->post('username');
292                                 $data['password'] = $this->input->post('password');
293                                 
294                                 $this->users_model->register($data);
295                                 $user_id = $this->users_model->get_userdata($data['username'],
296                                                 "id");
297                                 $user_id = $user_id['id'];
298                                 
299                                 // Redirect account activation page.
300                                 header('Location: '. site_url("user/activate/$user_id"));
301                         }
302                 }
303         }
304         
305         public function account($redirect = '')
306         {
307                 $this->register($redirect);
308         }
309         
310         public function profile($username, $videos_offset = 0)
311         {
312                 // TODO handle user not found
313                 
314                 $this->load->config('localization');
315                 $this->load->helper('date');
316                 $this->lang->load('date');
317                 
318                 // **
319                 // ** LOADING MODEL
320                 // **
321                 // Logged in user time zone
322                 $time_zone = $this->session->userdata('time_zone');
323                 
324                 // User data
325                 $userdata = $this->users_model->get_userdata($username);
326                 $userdata['roles'] = Users_model::roles_to_string($userdata['roles']);
327                 $country_list = $this->config->item('country_list');
328                 $userdata['country_name'] = $country_list[ $userdata['country'] ];
329                 $userdata['last_login'] = human_gmt_to_human_local(
330                         $userdata['last_login'], $time_zone); 
331                 $userdata['time_zone'] = $this->lang->line($userdata['time_zone']);
332                 
333                 // User's videos
334                 $this->load->model('videos_model');
335                 $vs_data['videos'] = $this->videos_model->get_videos_summary(
336                         NULL, $username, intval($videos_offset),
337                         $this->config->item('videos_per_page'));
338                 
339                 // Pagination
340                 $this->load->library('pagination');
341                 $pg_config['base_url'] = site_url("user/profile/$username/");
342                 $pg_config['uri_segment'] = 4;
343                 $pg_config['total_rows'] = $this->videos_model->get_videos_count(
344                         NULL, $username);
345                 $pg_config['per_page'] = $this->config->item('videos_per_page');
346                 $this->pagination->initialize($pg_config);
347                 $vs_data['pagination'] = $this->pagination->create_links();
348                 $vs_data['title'] = NULL;
349                 $vs_data['category_name'] = ''; // TODO videos_summary with AJAX
350                 
351                 $params = array(
352                         'title'=> $this->lang->line('user_appelation').' '.$username
353                                 .' &ndash; '
354                                 . $this->config->item('site_name'),
355                         'css'=> array('catalog.css')
356                         //'metas' => array('description'=>'')
357                 );
358                 $this->load->library('html_head_params', $params);
359                 
360                 // Current user profile tab
361                 $tab = (! $videos_offset ? 0 : 1);
362                 
363                 // **
364                 // ** LOADING VIEWS
365                 // **
366                 $this->load->view('html_begin', $this->html_head_params);
367                 $this->load->view('header', array());
368                 
369                 $vs = $this->load->view('catalog/videos_summary_view', $vs_data, TRUE);
370                 
371                 $main_params['content'] = $this->load->view('user/profile_view',
372                         array('userdata'=> $userdata, 'videos_summary'=> $vs, 'tab'=>$tab),
373                         TRUE);
374                 $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
375                 $this->load->view('main', $main_params);
376                 
377                 $this->load->view('footer');
378                 $this->load->view('html_end');
379         }
380         
381         public function activate($user_id, $method='', $activation_code='')
382         {
383                 $user_id = intval($user_id);            
384                 $res_form_validation = FALSE;
385                 
386                 if ($method == 'code')
387                 {
388                         if (! $activation_code)
389                                 $res_form_validation = $this->form_validation->run('activate');
390                         // Activation code is provided in URL.
391                         else
392                         {
393                                 if ($this->_valid_activation_code($activation_code)
394                                                 && $this->users_model->activate_account($user_id,
395                                                         $activation_code))
396                                 {
397                                         $this->load->helper('message');
398                                         show_info_msg_page($this, sprintf(
399                                                 $this->lang->line('user_msg_activated_account'), 
400                                                 site_url('user/login')));
401                                         return;
402                                 }
403                                 else
404                                 {
405                                         $this->load->helper('message');
406                                         show_error_msg_page($this, 
407                                                         $this->lang->line(
408                                                                         'user_msg_wrong_activation_code'));
409                                         return;
410                                 }
411                         }
412                 }
413                 else if ($method == 'resend')
414                 {
415                         $res_form_validation =
416                                 $this->form_validation->run('resend_activation');
417                 }
418                 
419                 $userdata = $this->users_model->get_userdata($user_id,
420                                 'email, a.activation_code');
421                 $email = $userdata['email'];
422                 $activated_account = ($userdata['activation_code'] == NULL);
423                 
424                 if ($activated_account)
425                 {
426                         $this->load->helper('message');
427                         show_info_msg_page($this, sprintf(
428                                 $this->lang->line('user_msg_activated_account'), 
429                                 site_url('user/login')));
430                         return;
431                 }
432                 
433                 $this->load->library('form_validation');
434                         
435                 $this->form_validation->set_error_delimiters('<span class="error">',
436                                         '</span>');
437                 
438                 if ($res_form_validation === FALSE)
439                 {
440                         $params = array(
441                                 'title'=> $this->lang->line('user_title_activation')
442                                         .' &ndash; '
443                                         . $this->config->item('site_name'),
444                                 //'metas' => array('description'=>'')
445                         );
446                         $this->load->library('html_head_params', $params);
447                 
448                         // **
449                         // ** LOADING VIEWS
450                         // **
451                         $this->load->view('html_begin', $this->html_head_params);
452                         $this->load->view('header', array());
453
454                         // Show form
455                         $main_params['content'] = 
456                                 $this->load->view('user/activate_view',
457                                 array(  'user_id'=> $user_id,
458                                                 'email'=> $userdata['email']),
459                                 TRUE);
460                         
461                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
462                         $this->load->view('main', $main_params);
463                 
464                         $this->load->view('footer');
465                         $this->load->view('html_end');
466                 }
467                 else
468                 {
469                         if ($method == 'code')
470                         {
471                                 // A message which tells the user that the
472                                 // activation was successful.
473                                 $this->load->helper('message');
474                                 show_info_msg_page($this, sprintf(
475                                         $this->lang->line('user_msg_activated_account'), 
476                                         site_url('user/login')));
477                                 return;
478                         }
479                         else if ($method == 'resend')
480                         {
481                                 // Redirect to resent message
482                                 $this->load->helper('message');
483                                 show_info_msg_page($this, sprintf(
484                                                 $this->lang->line('user_msg_activation_resent'),
485                                                 $this->input->post('email')));
486                                 return;
487                         }
488                 }
489         }
490         
491         public function recover_password()
492         {
493                 $this->load->library('form_validation');
494                         
495                 $this->form_validation->set_error_delimiters('<span class="error">',
496                         '</span>');
497
498                 if ($this->form_validation->run('recover_password') === FALSE)
499                 {
500                         $params = array(        'title' =>
501                                                                         $this->lang->line(
502                                                                                 'user_title_password_recovery')
503                                                                                 .' &ndash; '
504                                                                                 . $this->config->item('site_name'),
505                                                                 //'metas' => array('description'=>'')
506                         );
507                         $this->load->library('html_head_params', $params);
508                                 
509                         // **
510                         // ** LOADING VIEWS
511                         // **
512                         $this->load->view('html_begin', $this->html_head_params);
513                         $this->load->view('header', array('selected_menu' => 
514                                         'recover_password'));
515
516                         $main_params['content'] = $this->load->view(
517                                 'user/recover_password_view', array(),
518                                 TRUE);
519                         
520                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
521                         $this->load->view('main', $main_params);
522                                 
523                         $this->load->view('footer');
524                         $this->load->view('html_end');
525                 }
526                 else
527                 {
528                         // Resent message
529                         $this->load->helper('message');
530                         show_info_msg_page($this, sprintf(
531                                         $this->lang->line('user_msg_password_recovery_email_sent'),
532                                         $this->input->post('username'),
533                                         $this->input->post('email')));
534                         return;
535                 }
536         }
537         
538         public function _format_message($msg, $val = '', $sub = '%s')
539         {
540                 return str_replace($sub, $val, $this->lang->line($msg));
541         }
542         
543         public function _update_session_userdata($data)
544         {
545                 foreach ($data as $key=> $val)
546                         $this->session->set_userdata($key, $val);
547         }
548         
549         public function _is_username_unique($username)
550         {
551                 if ($this->users_model->get_userdata($username))
552                         return FALSE;
553                 
554                 return TRUE;
555         }
556         
557         public function _valid_username($username)
558         {
559                 return (preg_match('/^[a-z0-9\._]+$/', $username) === 1);
560         }
561
562         public function _valid_username_or_email($username)
563         {
564                 $this->load->helper('email');
565
566                 if (valid_email($username))
567                         return TRUE;
568                 else
569                         return $this->_valid_username($username);
570         }
571         
572         public function _valid_date($date)
573         {
574                 if (! $date)
575                         return TRUE;
576                 
577                 return (preg_match('/[\d]{4}-[\d]{2}-[\d]{2}/', $date) === 1);
578         }
579         
580         public function _postprocess_birth_date($date)
581         {
582                 // If the user entered no birth date NULL needs to be inserted into DB.
583                 if (! $date)
584                         return NULL;
585                 
586                 return $date;
587         }
588         
589         public function _valid_old_password($old_password, $field_username)
590         {
591                 if (! $old_password)
592                         return TRUE;
593                 
594                 $username= $this->input->post($field_username);
595                 
596                 if ($this->users_model->login($username, $old_password))
597                         return TRUE;
598                 
599                 return FALSE;
600         }
601         
602         public function _change_password_cond($param)
603         {
604                 $old = $this->input->post('old-password');
605                 $new = $this->input->post('new-password');
606                 $newc = $this->input->post('new-password-confirmation');
607                 
608                 return (!$old && !$new && !$newc)
609                         || ($old && $new && $newc);
610         }
611         
612         public function _required_by_register($param)
613         {
614                 $user_id = $this->input->post('user-id');
615                 
616                 if (! $user_id && ! $param)
617                         return FALSE;
618                 
619                 return TRUE;
620         }
621         
622         public function _valid_activation_code($activation_code)
623         {
624                 return (preg_match('/^[a-fA-F0-9]{16}$/', $activation_code) == 1);
625         }
626
627         public function _do_login($username, $field_password)
628         {
629                 $password = $this->input->post($field_password);
630
631                 $user = $this->users_model->login($username, $password);
632
633                 // Authentication failed.
634                 if ($user === FALSE)
635                         return FALSE;
636                 
637                 // User has not activated the account.
638                 if ($user['activation_code'] !== NULL)
639                 {
640                         $this->activated_account = FALSE;
641                         $this->user_id = $user['id'];
642                         return TRUE;
643                 }
644                 
645                 // Authentication successful: set session with user data.
646                 $this->session->set_userdata(array(
647                         'user_id'=> $user['id'],
648                         'username'=> $user['username'],
649                         'auth_src'=> $user['auth_src'],
650                         'time_zone'=> $user['time_zone']
651                 ));
652                 $this->import = (isset($user['import']) ? $user['import'] : FALSE);
653                 return TRUE;
654         }
655         
656         public function _do_activate($activation_code)
657         {
658                 $user_id = $this->input->post('user-id');
659                 if ($user_id === FALSE)
660                         return FALSE;
661                 $user_id = intval($user_id);
662                 
663                 return $this->users_model->activate_account($user_id,
664                                 $activation_code);
665         }
666         
667         public function _do_resend_activation($email)
668         {
669                 $user_id = $this->input->post('user-id');
670                 if ($user_id === FALSE)
671                         return FALSE;
672                 $user_id = intval($user_id);
673                 
674                 $this->users_model->set_userdata($user_id,
675                         array('email'=> $email));
676                 
677                 return $this->users_model->send_activation_email($user_id, $email);
678         }
679         
680         public function _username_exists($username)
681         {
682                 $userdata = $this->users_model->get_userdata($username);
683                 
684                 if (! $userdata)
685                         return FALSE;
686                 
687                 return TRUE;
688         }
689         
690         public function _internal_account($username)
691         {
692                 $userdata = $this->users_model->get_userdata($username, 'auth_src');
693                 if (! $userdata)
694                         return FALSE;
695
696                 if ($userdata['auth_src'] != 'internal')
697                         return FALSE;
698                 
699                 return TRUE;
700         }
701         
702         public function _do_recover_password($username)
703         {
704                 $email = $this->input->post('email');
705                 if (! $email)
706                         return FALSE;
707                 
708                 return $this->users_model->recover_password($username, $email);
709         }
710 }
711
712 /* End of file user.php */
713 /* Location: ./application/controllers/user.php */