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

Last change on this file since 1085 was 1085, checked in by rub, 18 years ago

Step 7 improvement issue 0000301:

o can attribute status <= current user
o define mode adviser

=> buttons disabled (gray on IE, not on FF)
=> truncated actions
=> display info mode adviser

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.1 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          : $RCSfile$
9// | last update   : $Date: 2006-03-16 22:58:16 +0000 (Thu, 16 Mar 2006) $
10// | last modifier : $Author: rub $
11// | revision      : $Revision: 1085 $
12// | revision      : $Revision: 1085 $
13// +-----------------------------------------------------------------------+
14// | This program is free software; you can redistribute it and/or modify  |
15// | it under the terms of the GNU General Public License as published by  |
16// | the Free Software Foundation                                          |
17// |                                                                       |
18// | This program is distributed in the hope that it will be useful, but   |
19// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
20// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
21// | General Public License for more details.                              |
22// |                                                                       |
23// | You should have received a copy of the GNU General Public License     |
24// | along with this program; if not, write to the Free Software           |
25// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
26// | USA.                                                                  |
27// +-----------------------------------------------------------------------+
28
29// validate_mail_address verifies whether the given mail address has the
30// right format. ie someone@domain.com "someone" can contain ".", "-" or
31// even "_". Exactly as "domain". The extension doesn't have to be
32// "com". The mail address can also be empty.
33// If the mail address doesn't correspond, an error message is returned.
34function validate_mail_address( $mail_address )
35{
36  global $lang;
37
38  if ( $mail_address == '' )
39  {
40    return '';
41  }
42  $regex = '/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*\.[a-z]+$/';
43  if ( !preg_match( $regex, $mail_address ) )
44  {
45    return $lang['reg_err_mail_address'];
46  }
47}
48
49function register_user($login, $password, $mail_address)
50{
51  global $lang, $conf;
52
53  $errors = array();
54  if ($login == '')
55  {
56    array_push($errors, $lang['reg_err_login1']);
57  }
58  if (ereg("^.* $", $login))
59  {
60    array_push($errors, $lang['reg_err_login2']);
61  }
62  if (ereg("^ .*$", $login))
63  {
64    array_push($errors, $lang['reg_err_login3']);
65  }
66  if (get_userid($login))
67  {
68    array_push($errors, $lang['reg_err_login5']);
69  }
70  $mail_error = validate_mail_address($mail_address);
71  if ('' != $mail_error)
72  {
73    array_push($errors, $mail_error);
74  }
75
76  // if no error until here, registration of the user
77  if (count($errors) == 0)
78  {
79    // what will be the inserted id ?
80    $query = '
81SELECT MAX('.$conf['user_fields']['id'].') + 1
82  FROM '.USERS_TABLE.'
83;';
84    list($next_id) = mysql_fetch_array(pwg_query($query));
85
86    $insert =
87      array(
88        $conf['user_fields']['id'] => $next_id,
89        $conf['user_fields']['username'] => mysql_escape_string($login),
90        $conf['user_fields']['password'] => $conf['pass_convert']($password),
91        $conf['user_fields']['email'] => $mail_address
92        );
93
94    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
95    mass_inserts(USERS_TABLE, array_keys($insert), array($insert));
96
97    create_user_infos($next_id);
98  }
99
100  return $errors;
101}
102
103function setup_style($style)
104{
105  return new Template(PHPWG_ROOT_PATH.'template/'.$style);
106}
107
108/**
109 * find informations related to the user identifier
110 *
111 * @param int user identifier
112 * @param boolean use_cache
113 * @param array
114 */
115function getuserdata($user_id, $use_cache)
116{
117  global $conf;
118
119  $userdata = array();
120
121  $query = '
122SELECT ';
123  $is_first = true;
124  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
125  {
126    if ($is_first)
127    {
128      $is_first = false;
129    }
130    else
131    {
132      $query.= '
133     , ';
134    }
135    $query.= $dbfield.' AS '.$pwgfield;
136  }
137  $query.= '
138  FROM '.USERS_TABLE.'
139  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'
140;';
141
142  $row = mysql_fetch_array(pwg_query($query));
143
144  while (true)
145  {
146    $query = '
147SELECT ui.*, uc.*
148  FROM '.USER_INFOS_TABLE.' AS ui LEFT JOIN '.USER_CACHE_TABLE.' AS uc
149    ON ui.user_id = uc.user_id
150  WHERE ui.user_id = \''.$user_id.'\'
151;';
152    $result = pwg_query($query);
153    if (mysql_num_rows($result) > 0)
154    {
155      break;
156    }
157    else
158    {
159      create_user_infos($user_id);
160    }
161  }
162
163  $row = array_merge($row, mysql_fetch_array($result));
164
165  foreach ($row as $key => $value)
166  {
167    if (!is_numeric($key))
168    {
169      // If the field is true or false, the variable is transformed into a
170      // boolean value.
171      if ($value == 'true' or $value == 'false')
172      {
173        $userdata[$key] = get_boolean($value);
174      }
175      else
176      {
177        $userdata[$key] = $value;
178      }
179    }
180  }
181
182  if ($use_cache)
183  {
184    if (!isset($userdata['need_update'])
185        or !is_bool($userdata['need_update'])
186        or $userdata['need_update'] == true)
187    {
188      $userdata['forbidden_categories'] =
189        calculate_permissions($userdata['id'], $userdata['status']);
190
191      $query = '
192SELECT COUNT(DISTINCT(image_id)) as total
193  FROM '.IMAGE_CATEGORY_TABLE.'
194  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
195;';
196      list($userdata['nb_total_images']) = mysql_fetch_array(pwg_query($query));
197
198      // update user cache
199      $query = '
200DELETE FROM '.USER_CACHE_TABLE.'
201  WHERE user_id = '.$userdata['id'].'
202;';
203      pwg_query($query);
204
205      $query = '
206INSERT INTO '.USER_CACHE_TABLE.'
207  (user_id,need_update,forbidden_categories,nb_total_images)
208  VALUES
209  ('.$userdata['id'].',\'false\',\''
210  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].')
211;';
212      pwg_query($query);
213    }
214  }
215
216  return $userdata;
217}
218
219/*
220 * deletes favorites of the current user if he's not allowed to see them
221 *
222 * @return void
223 */
224function check_user_favorites()
225{
226  global $user;
227
228  if ($user['forbidden_categories'] == '')
229  {
230    return;
231  }
232
233  // retrieving images allowed : belonging to at least one authorized
234  // category
235  $query = '
236SELECT DISTINCT f.image_id
237  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
238    ON f.image_id = ic.image_id
239  WHERE f.user_id = '.$user['id'].'
240    AND ic.category_id NOT IN ('.$user['forbidden_categories'].')
241;';
242  $result = pwg_query($query);
243  $authorizeds = array();
244  while ($row = mysql_fetch_array($result))
245  {
246    array_push($authorizeds, $row['image_id']);
247  }
248
249  $query = '
250SELECT image_id
251  FROM '.FAVORITES_TABLE.'
252  WHERE user_id = '.$user['id'].'
253;';
254  $result = pwg_query($query);
255  $favorites = array();
256  while ($row = mysql_fetch_array($result))
257  {
258    array_push($favorites, $row['image_id']);
259  }
260
261  $to_deletes = array_diff($favorites, $authorizeds);
262
263  if (count($to_deletes) > 0)
264  {
265    $query = '
266DELETE FROM '.FAVORITES_TABLE.'
267  WHERE image_id IN ('.implode(',', $to_deletes).')
268    AND user_id = '.$user['id'].'
269;';
270    pwg_query($query);
271  }
272}
273
274/**
275 * calculates the list of forbidden categories for a given user
276 *
277 * Calculation is based on private categories minus categories authorized to
278 * the groups the user belongs to minus the categories directly authorized
279 * to the user. The list contains at least -1 to be compliant with queries
280 * such as "WHERE category_id NOT IN ($forbidden_categories)"
281 *
282 * @param int user_id
283 * @param string user_status
284 * @return string forbidden_categories
285 */
286function calculate_permissions($user_id, $user_status)
287{
288  global $user;
289
290  $private_array = array();
291  $authorized_array = array();
292
293  $query = '
294SELECT id
295  FROM '.CATEGORIES_TABLE.'
296  WHERE status = \'private\'
297;';
298  $result = pwg_query($query);
299  while ($row = mysql_fetch_array($result))
300  {
301    array_push($private_array, $row['id']);
302  }
303
304  // if user is not an admin, locked categories can be considered as private$
305  if (!is_admin($user_status))
306  {
307    $query = '
308SELECT id
309  FROM '.CATEGORIES_TABLE.'
310  WHERE visible = \'false\'
311;';
312    $result = pwg_query($query);
313    while ($row = mysql_fetch_array($result))
314    {
315      array_push($private_array, $row['id']);
316    }
317
318    $private_array = array_unique($private_array);
319  }
320
321  // retrieve category ids directly authorized to the user
322  $query = '
323SELECT cat_id
324  FROM '.USER_ACCESS_TABLE.'
325  WHERE user_id = '.$user_id.'
326;';
327  $authorized_array = array_from_query($query, 'cat_id');
328
329  // retrieve category ids authorized to the groups the user belongs to
330  $query = '
331SELECT cat_id
332  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
333    ON ug.group_id = ga.group_id
334  WHERE ug.user_id = '.$user_id.'
335;';
336  $authorized_array =
337    array_merge(
338      $authorized_array,
339      array_from_query($query, 'cat_id')
340      );
341
342  // uniquify ids : some private categories might be authorized for the
343  // groups and for the user
344  $authorized_array = array_unique($authorized_array);
345
346  // only unauthorized private categories are forbidden
347  $forbidden_array = array_diff($private_array, $authorized_array);
348
349  // at least, the list contains -1 values. This category does not exists so
350  // where clauses such as "WHERE category_id NOT IN(-1)" will always be
351  // true.
352  array_push($forbidden_array, '-1');
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  $insert =
450    array(
451      'user_id' => $user_id,
452      'status' => $user_id == $conf['webmaster_id'] ? 'admin' : 'normal',
453      'template' => $conf['default_template'],
454      'nb_image_line' => $conf['nb_image_line'],
455      'nb_line_page' => $conf['nb_line_page'],
456      'language' => $conf['default_language'],
457      'recent_period' => $conf['recent_period'],
458      'expand' => boolean_to_string($conf['auto_expand']),
459      'show_nb_comments' => boolean_to_string($conf['show_nb_comments']),
460      'maxwidth' => $conf['default_maxwidth'],
461      'maxheight' => $conf['default_maxheight'],
462      'registration_date' => $dbnow,
463      'enabled_high' => $conf['newuser_default_enabled_high']
464      );
465
466  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
467  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
468}
469
470/**
471 * returns the groupname corresponding to the given group identifier if
472 * exists
473 *
474 * @param int group_id
475 * @return mixed
476 */
477function get_groupname($group_id)
478{
479  $query = '
480SELECT name
481  FROM '.GROUPS_TABLE.'
482  WHERE id = '.intval($group_id).'
483;';
484  $result = pwg_query($query);
485  if (mysql_num_rows($result) > 0)
486  {
487    list($groupname) = mysql_fetch_row($result);
488  }
489  else
490  {
491    return false;
492  }
493
494  return $groupname;
495}
496
497/**
498 * return the file path of the given language filename, depending on the
499 * availability of the file
500 *
501 * in descending order of preference: user language, default language,
502 * PhpWebGallery default language.
503 *
504 * @param string filename
505 * @return string filepath
506 */
507function get_language_filepath($filename)
508{
509  global $user, $conf;
510
511  $directories =
512    array(
513      PHPWG_ROOT_PATH.'language/'.$user['language'],
514      PHPWG_ROOT_PATH.'language/'.$conf['default_language'],
515      PHPWG_ROOT_PATH.'language/'.PHPWG_DEFAULT_LANGUAGE
516      );
517
518  foreach ($directories as $directory)
519  {
520    $filepath = $directory.'/'.$filename;
521
522    if (file_exists($filepath))
523    {
524      return $filepath;
525    }
526  }
527
528  return false;
529}
530
531/*
532 * Performs all required actions for user login
533 * @param int user_id
534 * @param bool remember_me
535 * @return void
536*/
537function log_user($user_id, $remember_me)
538{
539  global $conf;
540  $session_length = $conf['session_length'];
541  if ($remember_me)
542  {
543    $session_length = $conf['remember_me_length'];
544  }
545  session_set_cookie_params($session_length);
546  session_start();
547  $_SESSION['id'] = $user_id;
548}
549
550/*
551 * Return access_type definition of uuser
552 * Test does with user status
553 * @return bool
554*/
555function get_access_type_status($user_status = '')
556{
557  global $user;
558
559  if (($user_status == '') and isset($user['status']))
560  {
561    $user_status = $user['status'];
562  }
563
564  $access_type_status = ACCESS_NONE;
565  switch ($user_status)
566  {
567    case 'guest':
568    case 'generic':
569    {
570      $access_type_status = ACCESS_GUEST;
571      break;
572    }
573    case 'normal':
574    {
575      $access_type_status = ACCESS_CLASSIC;
576      break;
577    }
578    case 'admin':
579    {
580      $access_type_status = ACCESS_ADMINISTRATOR;
581      break;
582    }
583    case 'webmaster':
584    {
585      $access_type_status = ACCESS_WEBMASTER;
586      break;
587    }
588  }
589
590  return $access_type_status;
591}
592
593/*
594 * Return if user have access to access_type definition
595 * Test does with user status
596 * @return bool
597*/
598function is_autorize_status($access_type, $user_status = '')
599{
600  return (get_access_type_status($user_status) >= $access_type);
601}
602
603/*
604 * Check if user have access to access_type definition
605 * Stop action if there are not access
606 * Test does with user status
607 * @return none
608*/
609function check_status($access_type, $user_status = '')
610{
611  global $lang;
612
613  if (!is_autorize_status($access_type, $user_status))
614  {
615    echo '<div style="text-align:center;">'.$lang['access_forbiden'].'<br />';
616    echo '<a href="'.PHPWG_ROOT_PATH.'identification.php">'.$lang['identification'].'</a></div>';
617    exit();
618  }
619}
620
621/*
622 * Return if user is an administrator
623 * @return bool
624*/
625function is_admin($user_status = '')
626{
627  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
628}
629
630/*
631 * Return if current user is an adviser
632 * @return bool
633*/
634function is_adviser()
635{
636  global $user;
637
638  return ($user['adviser'] == 'true');
639}
640
641?>
Note: See TracBrowser for help on using the repository browser.