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

Last change on this file since 1563 was 1527, checked in by nikrou, 18 years ago

line (error_log('...')) not wanted: debug

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