397699bdbfd2c226ece3c910d7758aa3703b767b
[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                         if ($user_id = $this->session->userdata('user_id'))
200                         {
201                                 $userdata = $this->users_model->get_userdata(intval($user_id));
202                                 $selected_menu = 'account';
203                         }
204                         else
205                         {
206                                 $userdata = FALSE;
207                                 $selected_menu = 'register';
208                         }
209                         
210                         $params = array('title' =>
211                                                                 $this->lang->line('ui_nav_menu_register')
212                                                                         .' &ndash; '
213                                                                         . $this->config->item('site_name'),
214                                                         //'metas' => array('description'=>'')
215                         );
216                         $this->load->library('html_head_params', $params);
217                 
218                         // **
219                         // ** LOADING VIEWS
220                         // **
221                         $this->load->view('html_begin', $this->html_head_params);
222                         $this->load->view('header', 
223                                 array('selected_menu' => $selected_menu));
224                         
225                         $main_params['content'] = $this->load->view('user/register_view', 
226                                 array('userdata'=> $userdata, 'redirect'=> $redirect,
227                                         'error_upload'=> $error_upload),
228                                 TRUE);
229                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
230                         $this->load->view('main', $main_params);
231                 
232                         $this->load->view('footer');
233                         $this->load->view('html_end');
234                 }
235                 else
236                 {
237                         $user_id = $this->input->post('user-id');
238                         $data['email'] = $this->input->post('email');
239                         $data['first_name'] = $this->input->post('first-name');
240                         $data['last_name'] = $this->input->post('last-name');
241                         $data['birth_date'] = $this->input->post('birth-date');
242                         $data['country'] = $this->input->post('country');
243                         $data['locality'] = $this->input->post('locality');
244                         $data['ui_lang'] = $this->input->post('ui-lang');
245                         $data['time_zone'] = $this->input->post('time-zone');
246                         
247                         // Handle picture if one was uploaded.
248                         if ($_FILES['picture']['tmp_name'])
249                         {
250                                 $upload_data = $this->upload->data();
251                                 $this->load->library('image');
252                                 $this->image->load($upload_data['full_path']);
253                                 // Resize original to a maximum size.
254                                 if ($this->image->get_width() * $this->image->get_height()
255                                                 > 640*480)
256                                 {
257                                         $this->image->save_thumbnail(
258                                                 $upload_data['full_path'],
259                                                 640, 480, IMAGETYPE_AUTO);
260                                 }
261                                 // Create thumbnail.
262                                 $data['picture'] = $upload_data['file_name'];
263                                 $this->image->save_thumbnail($upload_data['file_path']
264                                                 . $upload_data['file_name']. '-thumb.jpg', 120, 90);
265                         }
266                         
267                         // Update session user data.
268                         $this->_update_session_userdata($data);
269                         
270                         // Edit account data
271                         if ($user_id)
272                         {
273                                 $password = $this->input->post('new-password');
274                                 if ($password)
275                                         $data['password'] = $this->input->post('new-password');
276                                 
277                                 $this->users_model->set_userdata($user_id, $data);
278                                 
279                                 // Redirect to last page before login.
280                                 header('Location: '. site_url(urldecode_segments($redirect)));
281                         }
282                         // Registration
283                         else
284                         {
285                                 $data['username'] = $this->input->post('username');
286                                 $data['password'] = $this->input->post('password');
287                                 
288                                 $this->users_model->register($data);
289                                 $user_id = $this->users_model->get_userdata($data['username'],
290                                                 "id");
291                                 $user_id = $user_id['id'];
292                                 
293                                 // Redirect account activation page.
294                                 header('Location: '. site_url("user/activate/$user_id"));
295                         }
296                 }
297         }
298         
299         public function account($redirect = '')
300         {
301                 $this->register($redirect);
302         }
303         
304         public function profile($username, $videos_offset = 0)
305         {
306                 // TODO handle user not found
307                 
308                 $this->load->config('localization');
309                 $this->load->helper('date');
310                 $this->lang->load('date');
311                 
312                 // **
313                 // ** LOADING MODEL
314                 // **
315                 // Logged in user time zone
316                 $time_zone = $this->session->userdata('time_zone');
317                 
318                 // User data
319                 $userdata = $this->users_model->get_userdata($username);
320                 $userdata['roles'] = Users_model::roles_to_string($userdata['roles']);
321                 $country_list = $this->config->item('country_list');
322                 $userdata['country_name'] = $country_list[ $userdata['country'] ];
323                 $userdata['last_login'] = human_gmt_to_human_local(
324                         $userdata['last_login'], $time_zone); 
325                 $userdata['time_zone'] = $this->lang->line($userdata['time_zone']);
326                 
327                 // User's videos
328                 $this->load->model('videos_model');
329                 $vs_data['videos'] = $this->videos_model->get_videos_summary(
330                         NULL, $username, intval($videos_offset),
331                         $this->config->item('videos_per_page'));
332                 
333                 // Pagination
334                 $this->load->library('pagination');
335                 $pg_config['base_url'] = site_url("user/profile/$username/");
336                 $pg_config['uri_segment'] = 4;
337                 $pg_config['total_rows'] = $this->videos_model->get_videos_count(
338                         NULL, $username);
339                 $pg_config['per_page'] = $this->config->item('videos_per_page');
340                 $this->pagination->initialize($pg_config);
341                 $vs_data['pagination'] = $this->pagination->create_links();
342                 $vs_data['title'] = NULL;
343                 $vs_data['category_name'] = ''; // TODO videos_summary with AJAX
344                 
345                 $params = array(
346                         'title'=> $this->lang->line('user_appelation').' '.$username
347                                 .' &ndash; '
348                                 . $this->config->item('site_name'),
349                         'css'=> array('catalog.css')
350                         //'metas' => array('description'=>'')
351                 );
352                 $this->load->library('html_head_params', $params);
353                 
354                 // Current user profile tab
355                 $tab = (! $videos_offset ? 0 : 1);
356                 
357                 // **
358                 // ** LOADING VIEWS
359                 // **
360                 $this->load->view('html_begin', $this->html_head_params);
361                 $this->load->view('header', array());
362                 
363                 $vs = $this->load->view('catalog/videos_summary_view', $vs_data, TRUE);
364                 
365                 $main_params['content'] = $this->load->view('user/profile_view',
366                         array('userdata'=> $userdata, 'videos_summary'=> $vs, 'tab'=>$tab),
367                         TRUE);
368                 $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
369                 $this->load->view('main', $main_params);
370                 
371                 $this->load->view('footer');
372                 $this->load->view('html_end');
373         }
374         
375         public function activate($user_id, $method='', $activation_code='')
376         {
377                 $user_id = intval($user_id);            
378                 $res_form_validation = FALSE;
379                 
380                 if ($method == 'code')
381                 {
382                         if (! $activation_code)
383                                 $res_form_validation = $this->form_validation->run('activate');
384                         // Activation code is provided in URL.
385                         else
386                         {
387                                 if ($this->_valid_activation_code($activation_code)
388                                                 && $this->users_model->activate_account($user_id,
389                                                         $activation_code))
390                                 {
391                                         $this->load->helper('message');
392                                         show_info_msg_page($this, sprintf(
393                                                 $this->lang->line('user_msg_activated_account'), 
394                                                 site_url('user/login')));
395                                         return;
396                                 }
397                                 else
398                                 {
399                                         $this->load->helper('message');
400                                         show_error_msg_page($this, 
401                                                         $this->lang->line(
402                                                                         'user_msg_wrong_activation_code'));
403                                         return;
404                                 }
405                         }
406                 }
407                 else if ($method == 'resend')
408                 {
409                         $res_form_validation =
410                                 $this->form_validation->run('resend_activation');
411                 }
412                 
413                 $userdata = $this->users_model->get_userdata($user_id,
414                                 'email, a.activation_code');
415                 $email = $userdata['email'];
416                 $activated_account = ($userdata['activation_code'] == NULL);
417                 
418                 if ($activated_account)
419                 {
420                         $this->load->helper('message');
421                         show_info_msg_page($this, sprintf(
422                                 $this->lang->line('user_msg_activated_account'), 
423                                 site_url('user/login')));
424                         return;
425                 }
426                 
427                 $this->load->library('form_validation');
428                         
429                 $this->form_validation->set_error_delimiters('<span class="error">',
430                                         '</span>');
431                 
432                 if ($res_form_validation === FALSE)
433                 {
434                         $params = array(
435                                 'title'=> $this->lang->line('user_title_activation')
436                                         .' &ndash; '
437                                         . $this->config->item('site_name'),
438                                 //'metas' => array('description'=>'')
439                         );
440                         $this->load->library('html_head_params', $params);
441                 
442                         // **
443                         // ** LOADING VIEWS
444                         // **
445                         $this->load->view('html_begin', $this->html_head_params);
446                         $this->load->view('header', array());
447
448                         // Show form
449                         $main_params['content'] = 
450                                 $this->load->view('user/activate_view',
451                                 array(  'user_id'=> $user_id,
452                                                 'email'=> $userdata['email']),
453                                 TRUE);
454                         
455                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
456                         $this->load->view('main', $main_params);
457                 
458                         $this->load->view('footer');
459                         $this->load->view('html_end');
460                 }
461                 else
462                 {
463                         if ($method == 'code')
464                         {
465                                 // A message which tells the user that the
466                                 // activation was successful.
467                                 $this->load->helper('message');
468                                 show_info_msg_page($this, sprintf(
469                                         $this->lang->line('user_msg_activated_account'), 
470                                         site_url('user/login')));
471                                 return;
472                         }
473                         else if ($method == 'resend')
474                         {
475                                 // Redirect to resent message
476                                 $this->load->helper('message');
477                                 show_info_msg_page($this, sprintf(
478                                                 $this->lang->line('user_msg_activation_resent'),
479                                                 $this->input->post('email')));
480                                 return;
481                         }
482                 }
483         }
484         
485         public function recover_password()
486         {
487                 $this->load->library('form_validation');
488                         
489                 $this->form_validation->set_error_delimiters('<span class="error">',
490                         '</span>');
491
492                 if ($this->form_validation->run('recover_password') === FALSE)
493                 {
494                         $params = array(        'title' =>
495                                                                         $this->lang->line(
496                                                                                 'user_title_password_recovery')
497                                                                                 .' &ndash; '
498                                                                                 . $this->config->item('site_name'),
499                                                                 //'metas' => array('description'=>'')
500                         );
501                         $this->load->library('html_head_params', $params);
502                                 
503                         // **
504                         // ** LOADING VIEWS
505                         // **
506                         $this->load->view('html_begin', $this->html_head_params);
507                         $this->load->view('header', array('selected_menu' => 
508                                         'recover_password'));
509
510                         $main_params['content'] = $this->load->view(
511                                 'user/recover_password_view', array(),
512                                 TRUE);
513                         
514                         $main_params['side'] = $this->load->view('side_default', NULL, TRUE);
515                         $this->load->view('main', $main_params);
516                                 
517                         $this->load->view('footer');
518                         $this->load->view('html_end');
519                 }
520                 else
521                 {
522                         // Resent message
523                         $this->load->helper('message');
524                         show_info_msg_page($this, sprintf(
525                                         $this->lang->line('user_msg_password_recovery_email_sent'),
526                                         $this->input->post('username'),
527                                         $this->input->post('email')));
528                         return;
529                 }
530         }
531         
532         public function _format_message($msg, $val = '', $sub = '%s')
533         {
534                 return str_replace($sub, $val, $this->lang->line($msg));
535         }
536         
537         public function _update_session_userdata($data)
538         {
539                 foreach ($data as $key=> $val)
540                         $this->session->set_userdata($key, $val);
541         }
542         
543         public function _valid_username($username)
544         {
545                 return (preg_match('/^[a-z0-9\._]+$/', $username) === 1);
546         }
547
548         public function _valid_username_or_email($username)
549         {
550                 $this->load->helper('email');
551
552                 if (valid_email($username))
553                         return TRUE;
554                 else
555                         return $this->_valid_username($username);
556         }
557         
558         public function _valid_date($date)
559         {
560                 if (! $date)
561                         return TRUE;
562                 
563                 return (preg_match('/[\d]{4}-[\d]{2}-[\d]{2}/', $date) === 1);
564         }
565         
566         public function _postprocess_birth_date($date)
567         {
568                 // If the user entered no birth date NULL needs to be inserted into DB.
569                 if (! $date)
570                         return NULL;
571                 
572                 return $date;
573         }
574         
575         public function _valid_old_password($old_password, $field_username)
576         {
577                 if (! $old_password)
578                         return TRUE;
579                 
580                 $username= $this->input->post($field_username);
581                 
582                 if ($this->users_model->login($username, $old_password))
583                         return TRUE;
584                 
585                 return FALSE;
586         }
587         
588         public function _change_password_cond($param)
589         {
590                 $old = $this->input->post('old-password');
591                 $new = $this->input->post('new-password');
592                 $newc = $this->input->post('new-password-confirmation');
593                 
594                 return (!$old && !$new && !$newc)
595                         || ($old && $new && $newc);
596         }
597         
598         public function _required_by_register($param)
599         {
600                 $user_id = $this->input->post('user-id');
601                 
602                 if (! $user_id && ! $param)
603                         return FALSE;
604                 
605                 return TRUE;
606         }
607         
608         public function _valid_activation_code($activation_code)
609         {
610                 return (preg_match('/^[a-fA-F0-9]{16}$/', $activation_code) == 1);
611         }
612
613         public function _do_login($username, $field_password)
614         {
615                 $password = $this->input->post($field_password);
616
617                 $user = $this->users_model->login($username, $password);
618
619                 // Authentication failed.
620                 if ($user === FALSE)
621                         return FALSE;
622                 
623                 // User has not activated the account.
624                 if ($user['activation_code'] !== NULL)
625                 {
626                         $this->activated_account = FALSE;
627                         $this->user_id = $user['id'];
628                         return TRUE;
629                 }
630                 
631                 // Authentication successful: set session with user data.
632                 $this->session->set_userdata(array(
633                         'user_id'=> $user['id'],
634                         'username'=> $user['username'],
635                         'auth_src'=> $user['auth_src'],
636                         'time_zone'=> $user['time_zone']
637                 ));
638                 $this->import = (isset($user['import']) ? $user['import'] : FALSE);
639                 return TRUE;
640         }
641         
642         public function _do_activate($activation_code)
643         {
644                 $user_id = $this->input->post('user-id');
645                 if ($user_id === FALSE)
646                         return FALSE;
647                 $user_id = intval($user_id);
648                 
649                 return $this->users_model->activate_account($user_id,
650                                 $activation_code);
651         }
652         
653         public function _do_resend_activation($email)
654         {
655                 $user_id = $this->input->post('user-id');
656                 if ($user_id === FALSE)
657                         return FALSE;
658                 $user_id = intval($user_id);
659                 
660                 $this->users_model->set_userdata($user_id,
661                         array('email'=> $email));
662                 
663                 return $this->users_model->send_activation_email($user_id, $email);
664         }
665         
666         public function _username_exists($username)
667         {
668                 $userdata = $this->users_model->get_userdata($username);
669                 
670                 if (! $userdata)
671                         return FALSE;
672                 
673                 return TRUE;
674         }
675         
676         public function _internal_account($username)
677         {
678                 $userdata = $this->users_model->get_userdata($username, 'auth_src');
679                 if (! $userdata)
680                         return FALSE;
681
682                 if ($userdata['auth_src'] != 'internal')
683                         return FALSE;
684                 
685                 return TRUE;
686         }
687         
688         public function _do_recover_password($username)
689         {
690                 $email = $this->input->post('email');
691                 if (! $email)
692                         return FALSE;
693                 
694                 return $this->users_model->recover_password($username, $email);
695         }
696 }
697
698 /* End of file user.php */
699 /* Location: ./application/controllers/user.php */