source: trunk/include/functions_user.inc.php @ 1605

Last change on this file since 1605 was 1605, checked in by rvelices, 18 years ago

plugins: added actions for register_user, delete_categories, delete_elements
and delete_user

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2006 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: functions_user.inc.php 1605 2006-11-14 00:51:15Z rvelices $
9// | last update   : $Date: 2006-11-14 00:51:15 +0000 (Tue, 14 Nov 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1605 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28// validate_mail_address verifies whether the given mail address has the
29// right format. ie someone@domain.com "someone" can contain ".", "-" or
30// even "_". Exactly as "domain". The extension doesn't have to be
31// "com". The mail address can also be empty.
32// If the mail address doesn't correspond, an error message is returned.
33function validate_mail_address( $mail_address )
34{
35  global $lang;
36
37  if ( $mail_address == '' )
38  {
39    return '';
40  }
41  $regex = '/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*\.[a-z]+$/';
42  if ( !preg_match( $regex, $mail_address ) )
43  {
44    return $lang['reg_err_mail_address'];
45  }
46}
47
48function register_user($login, $password, $mail_address)
49{
50  global $lang, $conf;
51
52  $errors = array();
53  if ($login == '')
54  {
55    array_push($errors, $lang['reg_err_login1']);
56  }
57  if (ereg("^.* $", $login))
58  {
59    array_push($errors, $lang['reg_err_login2']);
60  }
61  if (ereg("^ .*$", $login))
62  {
63    array_push($errors, $lang['reg_err_login3']);
64  }
65  if (get_userid($login))
66  {
67    array_push($errors, $lang['reg_err_login5']);
68  }
69  $mail_error = validate_mail_address($mail_address);
70  if ('' != $mail_error)
71  {
72    array_push($errors, $mail_error);
73  }
74
75  // if no error until here, registration of the user
76  if (count($errors) == 0)
77  {
78    // what will be the inserted id ?
79    $query = '
80SELECT MAX('.$conf['user_fields']['id'].') + 1
81  FROM '.USERS_TABLE.'
82;';
83    list($next_id) = mysql_fetch_array(pwg_query($query));
84
85    $insert =
86      array(
87        $conf['user_fields']['id'] => $next_id,
88        $conf['user_fields']['username'] => mysql_escape_string($login),
89        $conf['user_fields']['password'] => $conf['pass_convert']($password),
90        $conf['user_fields']['email'] => $mail_address
91        );
92
93    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
94    mass_inserts(USERS_TABLE, array_keys($insert), array($insert));
95
96  // Assign by default groups
97  {
98    $query = '
99SELECT id
100  FROM '.GROUPS_TABLE.'
101  WHERE is_default = \''.boolean_to_string(true).'\'
102  ORDER BY id ASC
103;';
104    $result = pwg_query($query);
105
106    $inserts = array();
107    while ($row = mysql_fetch_array($result))
108    {
109      array_push
110      (
111        $inserts,
112        array
113        (
114          'user_id' => $next_id,
115          'group_id' => $row['id']
116        )
117      );
118    }
119
120    if (count($inserts) != 0)
121    {
122      include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
123      mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts);
124    }
125  }
126
127    create_user_infos($next_id);
128
129    trigger_action('register_user',
130      array(
131        'id'=>$next_id,
132        'username'=>$login,
133        'email'=>$mail_address,
134       )
135      );
136  }
137
138  return $errors;
139}
140
141function setup_style($style)
142{
143  return new Template(PHPWG_ROOT_PATH.'template/'.$style);
144}
145
146function build_user( $user_id, $use_cache )
147{
148  global $conf;
149  $user['id'] = $user_id;
150  $user = array_merge( $user, getuserdata($user_id, $use_cache) );
151  if ( $user['id'] == $conf['guest_id'])
152  {
153    $user['is_the_guest']=true;
154    $user['template'] = $conf['default_template'];
155    $user['nb_image_line'] = $conf['nb_image_line'];
156    $user['nb_line_page'] = $conf['nb_line_page'];
157    $user['language'] = $conf['default_language'];
158    $user['maxwidth'] = $conf['default_maxwidth'];
159    $user['maxheight'] = $conf['default_maxheight'];
160    $user['recent_period'] = $conf['recent_period'];
161    $user['expand'] = $conf['auto_expand'];
162    $user['show_nb_comments'] = $conf['show_nb_comments'];
163    $user['enabled_high'] = $conf['newuser_default_enabled_high'];
164  }
165  else
166  {
167    $user['is_the_guest']=false;
168  }
169  // calculation of the number of picture to display per page
170  $user['nb_image_page'] = $user['nb_image_line'] * $user['nb_line_page'];
171
172  // include template/theme configuration
173  if (defined('IN_ADMIN') and IN_ADMIN)
174  {
175    list($user['template'], $user['theme']) =
176      explode
177      (
178        '/',
179        isset($conf['default_admin_layout']) ? $conf['default_admin_layout']
180                                             : $user['template']
181      );
182    // TODO : replace $conf['admin_layout'] by $user['admin_layout']
183  }
184  else
185  {
186    list($user['template'], $user['theme']) = explode('/', $user['template']);
187  }
188
189  return $user;
190}
191
192/**
193 * find informations related to the user identifier
194 *
195 * @param int user identifier
196 * @param boolean use_cache
197 * @param array
198 */
199function getuserdata($user_id, $use_cache)
200{
201  global $conf;
202
203  $userdata = array();
204
205  $query = '
206SELECT ';
207  $is_first = true;
208  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
209  {
210    if ($is_first)
211    {
212      $is_first = false;
213    }
214    else
215    {
216      $query.= '
217     , ';
218    }
219    $query.= $dbfield.' AS '.$pwgfield;
220  }
221  $query.= '
222  FROM '.USERS_TABLE.'
223  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'
224;';
225
226  $row = mysql_fetch_array(pwg_query($query));
227
228  while (true)
229  {
230    $query = '
231SELECT ui.*, uc.*
232  FROM '.USER_INFOS_TABLE.' AS ui LEFT JOIN '.USER_CACHE_TABLE.' AS uc
233    ON ui.user_id = uc.user_id
234  WHERE ui.user_id = \''.$user_id.'\'
235;';
236    $result = pwg_query($query);
237    if (mysql_num_rows($result) > 0)
238    {
239      break;
240    }
241    else
242    {
243      create_user_infos($user_id);
244    }
245  }
246
247  $row = array_merge($row, mysql_fetch_array($result));
248
249  foreach ($row as $key => $value)
250  {
251    if (!is_numeric($key))
252    {
253      // If the field is true or false, the variable is transformed into a
254      // boolean value.
255      if ($value == 'true' or $value == 'false')
256      {
257        $userdata[$key] = get_boolean($value);
258      }
259      else
260      {
261        $userdata[$key] = $value;
262      }
263    }
264  }
265
266  if ($use_cache)
267  {
268    if (!isset($userdata['need_update'])
269        or !is_bool($userdata['need_update'])
270        or $userdata['need_update'] == true)
271    {
272      $userdata['forbidden_categories'] =
273        calculate_permissions($userdata['id'], $userdata['status']);
274
275      $query = '
276SELECT COUNT(DISTINCT(image_id)) as total
277  FROM '.IMAGE_CATEGORY_TABLE.'
278  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
279;';
280      list($userdata['nb_total_images']) = mysql_fetch_array(pwg_query($query));
281
282      // update user cache
283      $query = '
284DELETE FROM '.USER_CACHE_TABLE.'
285  WHERE user_id = '.$userdata['id'].'
286;';
287      pwg_query($query);
288
289      $query = '
290INSERT INTO '.USER_CACHE_TABLE.'
291  (user_id,need_update,forbidden_categories,nb_total_images)
292  VALUES
293  ('.$userdata['id'].',\'false\',\''
294  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].')
295;';
296      pwg_query($query);
297    }
298  }
299
300  return $userdata;
301}
302
303/*
304 * deletes favorites of the current user if he's not allowed to see them
305 *
306 * @return void
307 */
308function check_user_favorites()
309{
310  global $user;
311
312  if ($user['forbidden_categories'] == '')
313  {
314    return;
315  }
316
317  // retrieving images allowed : belonging to at least one authorized
318  // category
319  $query = '
320SELECT DISTINCT f.image_id
321  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
322    ON f.image_id = ic.image_id
323  WHERE f.user_id = '.$user['id'].'
324    AND ic.category_id NOT IN ('.$user['forbidden_categories'].')
325;';
326  $result = pwg_query($query);
327  $authorizeds = array();
328  while ($row = mysql_fetch_array($result))
329  {
330    array_push($authorizeds, $row['image_id']);
331  }
332
333  $query = '
334SELECT image_id
335  FROM '.FAVORITES_TABLE.'
336  WHERE user_id = '.$user['id'].'
337;';
338  $result = pwg_query($query);
339  $favorites = array();
340  while ($row = mysql_fetch_array($result))
341  {
342    array_push($favorites, $row['image_id']);
343  }
344
345  $to_deletes = array_diff($favorites, $authorizeds);
346
347  if (count($to_deletes) > 0)
348  {
349    $query = '
350DELETE FROM '.FAVORITES_TABLE.'
351  WHERE image_id IN ('.implode(',', $to_deletes).')
352    AND user_id = '.$user['id'].'
353;';
354    pwg_query($query);
355  }
356}
357
358/**
359 * calculates the list of forbidden categories for a given user
360 *
361 * Calculation is based on private categories minus categories authorized to
362 * the groups the user belongs to minus the categories directly authorized
363 * to the user. The list contains at least -1 to be compliant with queries
364 * such as "WHERE category_id NOT IN ($forbidden_categories)"
365 *
366 * @param int user_id
367 * @param string user_status
368 * @return string forbidden_categories
369 */
370function calculate_permissions($user_id, $user_status)
371{
372  global $user;
373
374  $private_array = array();
375  $authorized_array = array();
376
377  $query = '
378SELECT id
379  FROM '.CATEGORIES_TABLE.'
380  WHERE status = \'private\'
381;';
382  $result = pwg_query($query);
383  while ($row = mysql_fetch_array($result))
384  {
385    array_push($private_array, $row['id']);
386  }
387
388  // retrieve category ids directly authorized to the user
389  $query = '
390SELECT cat_id
391  FROM '.USER_ACCESS_TABLE.'
392  WHERE user_id = '.$user_id.'
393;';
394  $authorized_array = array_from_query($query, 'cat_id');
395
396  // retrieve category ids authorized to the groups the user belongs to
397  $query = '
398SELECT cat_id
399  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
400    ON ug.group_id = ga.group_id
401  WHERE ug.user_id = '.$user_id.'
402;';
403  $authorized_array =
404    array_merge(
405      $authorized_array,
406      array_from_query($query, 'cat_id')
407      );
408
409  // uniquify ids : some private categories might be authorized for the
410  // groups and for the user
411  $authorized_array = array_unique($authorized_array);
412
413  // only unauthorized private categories are forbidden
414  $forbidden_array = array_diff($private_array, $authorized_array);
415
416  // if user is not an admin, locked categories are forbidden
417  if (!is_admin($user_status))
418  {
419    $query = '
420SELECT id
421  FROM '.CATEGORIES_TABLE.'
422  WHERE visible = \'false\'
423;';
424    $result = pwg_query($query);
425    while ($row = mysql_fetch_array($result))
426    {
427      array_push($forbidden_array, $row['id']);
428    }
429    $forbidden_array = array_unique($forbidden_array);
430  }
431
432  if ( empty($forbidden_array) )
433  {// at least, the list contains 0 value. This category does not exists so
434   // where clauses such as "WHERE category_id NOT IN(0)" will always be
435   // true.
436    array_push($forbidden_array, 0);
437  }
438
439  return implode(',', $forbidden_array);
440}
441
442/**
443 * returns the username corresponding to the given user identifier if exists
444 *
445 * @param int user_id
446 * @return mixed
447 */
448function get_username($user_id)
449{
450  global $conf;
451
452  $query = '
453SELECT '.$conf['user_fields']['username'].'
454  FROM '.USERS_TABLE.'
455  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
456;';
457  $result = pwg_query($query);
458  if (mysql_num_rows($result) > 0)
459  {
460    list($username) = mysql_fetch_row($result);
461  }
462  else
463  {
464    return false;
465  }
466
467  return $username;
468}
469
470/**
471 * returns user identifier thanks to his name, false if not found
472 *
473 * @param string username
474 * @param int user identifier
475 */
476function get_userid($username)
477{
478  global $conf;
479
480  $username = mysql_escape_string($username);
481
482  $query = '
483SELECT '.$conf['user_fields']['id'].'
484  FROM '.USERS_TABLE.'
485  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
486;';
487  $result = pwg_query($query);
488
489  if (mysql_num_rows($result) == 0)
490  {
491    return false;
492  }
493  else
494  {
495    list($user_id) = mysql_fetch_row($result);
496    return $user_id;
497  }
498}
499
500/**
501 * search an available feed_id
502 *
503 * @return string feed identifier
504 */
505function find_available_feed_id()
506{
507  while (true)
508  {
509    $key = generate_key(50);
510    $query = '
511SELECT COUNT(*)
512  FROM '.USER_FEED_TABLE.'
513  WHERE id = \''.$key.'\'
514;';
515    list($count) = mysql_fetch_row(pwg_query($query));
516    if (0 == $count)
517    {
518      return $key;
519    }
520  }
521}
522
523/**
524 * add user informations based on default values
525 *
526 * @param int user_id
527 */
528function create_user_infos($user_id)
529{
530  global $conf;
531
532  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
533
534  if ($user_id == $conf['webmaster_id'])
535  {
536    $status = 'webmaster';
537  }
538  else if ($user_id == $conf['guest_id'])
539  {
540    $status = 'guest';
541  }
542  else
543  {
544    $status = 'normal';
545  }
546
547  $insert =
548    array(
549      'user_id' => $user_id,
550      'status' => $status,
551      'template' => $conf['default_template'],
552      'nb_image_line' => $conf['nb_image_line'],
553      'nb_line_page' => $conf['nb_line_page'],
554      'language' => $conf['default_language'],
555      'recent_period' => $conf['recent_period'],
556      'expand' => boolean_to_string($conf['auto_expand']),
557      'show_nb_comments' => boolean_to_string($conf['show_nb_comments']),
558      'maxwidth' => $conf['default_maxwidth'],
559      'maxheight' => $conf['default_maxheight'],
560      'registration_date' => $dbnow,
561      'enabled_high' =>
562        boolean_to_string($conf['newuser_default_enabled_high']),
563      );
564
565  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
566  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
567}
568
569/**
570 * returns the groupname corresponding to the given group identifier if
571 * exists
572 *
573 * @param int group_id
574 * @return mixed
575 */
576function get_groupname($group_id)
577{
578  $query = '
579SELECT name
580  FROM '.GROUPS_TABLE.'
581  WHERE id = '.intval($group_id).'
582;';
583  $result = pwg_query($query);
584  if (mysql_num_rows($result) > 0)
585  {
586    list($groupname) = mysql_fetch_row($result);
587  }
588  else
589  {
590    return false;
591  }
592
593  return $groupname;
594}
595
596/**
597 * return the file path of the given language filename, depending on the
598 * availability of the file
599 *
600 * in descending order of preference: user language, default language,
601 * PhpWebGallery default language.
602 *
603 * @param string filename
604 * @return string filepath
605 */
606function get_language_filepath($filename)
607{
608  global $user, $conf;
609
610  $directories = array();
611  if ( isset($user['language']) )
612  {
613    $directories[] = PHPWG_ROOT_PATH.'language/'.$user['language'];
614  }
615  $directories[] = PHPWG_ROOT_PATH.'language/'.$conf['default_language'];
616  $directories[] = PHPWG_ROOT_PATH.'language/'.PHPWG_DEFAULT_LANGUAGE;
617
618  foreach ($directories as $directory)
619  {
620    $filepath = $directory.'/'.$filename;
621
622    if (file_exists($filepath))
623    {
624      return $filepath;
625    }
626  }
627
628  return false;
629}
630
631/*
632 * Performs all required actions for user login
633 * @param int user_id
634 * @param bool remember_me
635 * @return void
636*/
637function log_user($user_id, $remember_me)
638{
639  global $conf, $user;
640
641  if ($remember_me)
642  {
643    // search for an existing auto_login_key
644    $query = '
645SELECT auto_login_key
646  FROM '.USERS_TABLE.'
647  WHERE '.$conf['user_fields']['id'].' = '.$user_id.'
648;';
649
650    $auto_login_key = current(mysql_fetch_assoc(pwg_query($query)));
651    if (empty($auto_login_key))
652    {
653      $auto_login_key = base64_encode(md5(uniqid(rand(), true)));
654      $query = '
655UPDATE '.USERS_TABLE.'
656  SET auto_login_key=\''.$auto_login_key.'\'
657  WHERE '.$conf['user_fields']['id'].' = '.$user_id.'
658;';
659      pwg_query($query);
660    }
661    $cookie = array('id' => $user_id, 'key' => $auto_login_key);
662    setcookie($conf['remember_me_name'],
663              serialize($cookie),
664              time()+$conf['remember_me_length'],
665              cookie_path()
666              );
667  }
668  else
669  { // make sure we clean any remember me ...
670    setcookie($conf['remember_me_name'], '', 0, cookie_path());
671  }
672  if ( session_id()!="" )
673  { // this can happpen when the session is expired and auto_login
674    session_regenerate_id();
675  }
676  else
677  {
678    session_start();
679  }
680  $_SESSION['pwg_uid'] = $user_id;
681
682  $user['id'] = $_SESSION['pwg_uid'];
683}
684
685/*
686 * Performs auto-connexion when cookie remember_me exists
687 * @return true/false
688*/
689function auto_login() {
690  global $conf;
691
692  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
693  {
694    // must remove slash added in include/common.inc.php
695    $cookie = unserialize(stripslashes($_COOKIE[$conf['remember_me_name']]));
696
697    $query = '
698SELECT auto_login_key
699  FROM '.USERS_TABLE.'
700  WHERE '.$conf['user_fields']['id'].' = '.$cookie['id'].'
701;';
702
703    $auto_login_key = current(mysql_fetch_assoc(pwg_query($query)));
704    if ($auto_login_key == $cookie['key'])
705    {
706      log_user($cookie['id'], true);
707      return true;
708    }
709    else
710    {
711      setcookie($conf['remember_me_name'], '', 0, cookie_path());
712    }
713  }
714  return false;
715}
716
717/*
718 * Return access_type definition of uuser
719 * Test does with user status
720 * @return bool
721*/
722function get_access_type_status($user_status = '')
723{
724  global $user;
725
726  if (($user_status == '') and isset($user['status']))
727  {
728    $user_status = $user['status'];
729  }
730
731  $access_type_status = ACCESS_NONE;
732  switch ($user_status)
733  {
734    case 'guest':
735    case 'generic':
736    {
737      $access_type_status = ACCESS_GUEST;
738      break;
739    }
740    case 'normal':
741    {
742      $access_type_status = ACCESS_CLASSIC;
743      break;
744    }
745    case 'admin':
746    {
747      $access_type_status = ACCESS_ADMINISTRATOR;
748      break;
749    }
750    case 'webmaster':
751    {
752      $access_type_status = ACCESS_WEBMASTER;
753      break;
754    }
755  }
756
757  return $access_type_status;
758}
759
760/*
761 * Return if user have access to access_type definition
762 * Test does with user status
763 * @return bool
764*/
765function is_autorize_status($access_type, $user_status = '')
766{
767  return (get_access_type_status($user_status) >= $access_type);
768}
769
770/*
771 * Check if user have access to access_type definition
772 * Stop action if there are not access
773 * Test does with user status
774 * @return none
775*/
776function check_status($access_type, $user_status = '')
777{
778  if (!is_autorize_status($access_type, $user_status))
779  {
780    access_denied();
781  }
782}
783
784/*
785 * Return if user is an administrator
786 * @return bool
787*/
788function is_admin($user_status = '')
789{
790  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
791}
792
793/*
794 * Return if current user is an adviser
795 * @return bool
796*/
797function is_adviser()
798{
799  global $user;
800
801  return ($user['adviser'] == 'true');
802}
803
804/*
805 * Return mail address as display text
806 * @return string
807*/
808function get_email_address_as_display_text($email_address)
809{
810  global $conf;
811
812  if (!isset($email_address) or (trim($email_address) == ''))
813  {
814    return '';
815  }
816  else
817  {
818    if (is_adviser())
819    {
820      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
821    }
822    else
823    {
824      return $email_address;
825    }
826  }
827}
828
829?>
Note: See TracBrowser for help on using the repository browser.