source: branches/1.6/include/functions_user.inc.php @ 21236

Last change on this file since 21236 was 1594, checked in by plg, 18 years ago

Bug fixed: #users.auto_login_key moved to #user_infos.auto_login_key because
table users does not contain information specificaly related to
PhpWebGallery. With auto_login_key field in #users, external authentication
won't work.

Warning: when updating with subversion, you'll have to go directly to
upgrade_feed.php

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