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

Last change on this file since 948 was 906, checked in by plg, 19 years ago
  • bug 173 fixed: due to phpBB user identifiers management, the method to find the next user identifier has changer to MAX+1.
  • improvement: information message when new user added
  • bug fixed: language item "Username" used instead of "login".
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 13.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-2005 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $RCSfile$
9// | last update   : $Date: 2005-10-22 09:53:12 +0000 (Sat, 22 Oct 2005) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 906 $
12// | revision      : $Revision: 906 $
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 check_login_authorization($guest_allowed = true)
104{
105  global $user,$lang,$conf,$template;
106
107  if ($user['is_the_guest'] and !$guest_allowed)
108  {
109    echo '<div style="text-align:center;">'.$lang['only_members'].'<br />';
110    echo '<a href="./identification.php">'.$lang['ident_title'].'</a></div>';
111    exit();
112  }
113
114  if ($conf['gallery_locked'])
115  {
116    echo '<div style="text-align:center;">';
117    echo $lang['gallery_locked_message'];
118    echo '</div>';
119    if ($user['status'] != 'admin')
120    {
121      exit();
122    }
123  }
124}
125
126function setup_style($style)
127{
128  return new Template(PHPWG_ROOT_PATH.'template/'.$style);
129}
130
131/**
132 * find informations related to the user identifier
133 *
134 * @param int user identifier
135 * @param boolean use_cache
136 * @param array
137 */
138function getuserdata($user_id, $use_cache)
139{
140  global $conf;
141
142  $userdata = array();
143 
144  $query = '
145SELECT ';
146  $is_first = true;
147  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
148  {
149    if ($is_first)
150    {
151      $is_first = false;
152    }
153    else
154    {
155      $query.= '
156     , ';
157    }
158    $query.= $dbfield.' AS '.$pwgfield;
159  }
160  $query.= '
161  FROM '.USERS_TABLE.'
162  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'
163;';
164 
165  $row = mysql_fetch_array(pwg_query($query));
166
167  while (true)
168  {
169    $query = '
170SELECT ui.*, uc.*
171  FROM '.USER_INFOS_TABLE.' AS ui LEFT JOIN '.USER_CACHE_TABLE.' AS uc
172    ON ui.user_id = uc.user_id
173  WHERE ui.user_id = \''.$user_id.'\'
174;';
175    $result = pwg_query($query);
176    if (mysql_num_rows($result) > 0)
177    {
178      break;
179    }
180    else
181    {
182      create_user_infos($user_id);
183    }
184  }
185 
186  $row = array_merge($row, mysql_fetch_array($result));
187 
188  foreach ($row as $key => $value)
189  {
190    if (!is_numeric($key))
191    {
192      // If the field is true or false, the variable is transformed into a
193      // boolean value.
194      if ($value == 'true' or $value == 'false')
195      {
196        $userdata[$key] = get_boolean($value);
197      }
198      else
199      {
200        $userdata[$key] = $value;
201      }
202    }
203  }
204
205  if ($use_cache)
206  {
207    if (!isset($userdata['need_update'])
208        or !is_bool($userdata['need_update'])
209        or $userdata['need_update'] == true)
210    {
211      $userdata['forbidden_categories'] =
212        calculate_permissions($userdata['id'], $userdata['status']);
213
214      // update user cache
215      $query = '
216DELETE FROM '.USER_CACHE_TABLE.'
217  WHERE user_id = '.$userdata['id'].'
218;';
219      pwg_query($query);
220 
221      $query = '
222INSERT INTO '.USER_CACHE_TABLE.'
223  (user_id,need_update,forbidden_categories)
224  VALUES
225  ('.$userdata['id'].',\'false\',\''.$userdata['forbidden_categories'].'\')
226;';
227      pwg_query($query);
228    }
229  }
230
231  return $userdata;
232}
233
234/*
235 * deletes favorites of the current user if he's not allowed to see them
236 *
237 * @return void
238 */
239function check_user_favorites()
240{
241  global $user;
242
243  if ($user['forbidden_categories'] == '')
244  {
245    return;
246  }
247
248  // retrieving images allowed : belonging to at least one authorized
249  // category
250  $query = '
251SELECT DISTINCT f.image_id
252  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
253    ON f.image_id = ic.image_id
254  WHERE f.user_id = '.$user['id'].'
255    AND ic.category_id NOT IN ('.$user['forbidden_categories'].')
256;';
257  $result = pwg_query($query);
258  $authorizeds = array();
259  while ($row = mysql_fetch_array($result))
260  {
261    array_push($authorizeds, $row['image_id']);
262  }
263
264  $query = '
265SELECT image_id
266  FROM '.FAVORITES_TABLE.'
267  WHERE user_id = '.$user['id'].'
268;';
269  $result = pwg_query($query);
270  $favorites = array();
271  while ($row = mysql_fetch_array($result))
272  {
273    array_push($favorites, $row['image_id']);
274  }
275
276  $to_deletes = array_diff($favorites, $authorizeds);
277
278  if (count($to_deletes) > 0)
279  {
280    $query = '
281DELETE FROM '.FAVORITES_TABLE.'
282  WHERE image_id IN ('.implode(',', $to_deletes).')
283    AND user_id = '.$user['id'].'
284;';
285    pwg_query($query);
286  }
287}
288
289/**
290 * calculates the list of forbidden categories for a given user
291 *
292 * Calculation is based on private categories minus categories authorized to
293 * the groups the user belongs to minus the categories directly authorized
294 * to the user. The list contains at least -1 to be compliant with queries
295 * such as "WHERE category_id NOT IN ($forbidden_categories)"
296 *
297 * @param int user_id
298 * @param string user_status
299 * @return string forbidden_categories
300 */
301function calculate_permissions($user_id, $user_status)
302{
303  $private_array = array();
304  $authorized_array = array();
305
306  $query = '
307SELECT id
308  FROM '.CATEGORIES_TABLE.'
309  WHERE status = \'private\'
310;';
311  $result = pwg_query($query);
312  while ($row = mysql_fetch_array($result))
313  {
314    array_push($private_array, $row['id']);
315  }
316
317  // if user is not an admin, locked categories can be considered as private$
318  if ($user_status != 'admin')
319  {
320    $query = '
321SELECT id
322  FROM '.CATEGORIES_TABLE.'
323  WHERE visible = \'false\'
324;';
325    $result = pwg_query($query);
326    while ($row = mysql_fetch_array($result))
327    {
328      array_push($private_array, $row['id']);
329    }
330
331    $private_array = array_unique($private_array);
332  }
333 
334  // retrieve category ids directly authorized to the user
335  $query = '
336SELECT cat_id
337  FROM '.USER_ACCESS_TABLE.'
338  WHERE user_id = '.$user_id.'
339;';
340  $authorized_array = array_from_query($query, 'cat_id');
341
342  // retrieve category ids authorized to the groups the user belongs to
343  $query = '
344SELECT cat_id
345  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
346    ON ug.group_id = ga.group_id
347  WHERE ug.user_id = '.$user_id.'
348;';
349  $authorized_array =
350    array_merge(
351      $authorized_array,
352      array_from_query($query, 'cat_id')
353      );
354
355  // uniquify ids : some private categories might be authorized for the
356  // groups and for the user
357  $authorized_array = array_unique($authorized_array);
358
359  // only unauthorized private categories are forbidden
360  $forbidden_array = array_diff($private_array, $authorized_array);
361
362  // at least, the list contains -1 values. This category does not exists so
363  // where clauses such as "WHERE category_id NOT IN(-1)" will always be
364  // true.
365  array_push($forbidden_array, '-1');
366 
367  return implode(',', $forbidden_array);
368}
369
370/**
371 * returns the username corresponding to the given user identifier if exists
372 *
373 * @param int user_id
374 * @return mixed
375 */
376function get_username($user_id)
377{
378  global $conf;
379 
380  $query = '
381SELECT '.$conf['user_fields']['username'].'
382  FROM '.USERS_TABLE.'
383  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
384;';
385  $result = pwg_query($query);
386  if (mysql_num_rows($result) > 0)
387  {
388    list($username) = mysql_fetch_row($result);
389  }
390  else
391  {
392    return false;
393  }
394 
395  return $username;
396}
397
398/**
399 * returns user identifier thanks to his name, false if not found
400 *
401 * @param string username
402 * @param int user identifier
403 */
404function get_userid($username)
405{
406  global $conf;
407
408  $username = mysql_escape_string($username);
409
410  $query = '
411SELECT '.$conf['user_fields']['id'].'
412  FROM '.USERS_TABLE.'
413  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
414;';
415  $result = pwg_query($query);
416
417  if (mysql_num_rows($result) == 0)
418  {
419    return false;
420  }
421  else
422  {
423    list($user_id) = mysql_fetch_row($result);
424    return $user_id;
425  }
426}
427
428/**
429 * search an available feed_id
430 *
431 * @return string feed identifier
432 */
433function find_available_feed_id()
434{
435  while (true)
436  {
437    $key = generate_key(50);
438    $query = '
439SELECT COUNT(*)
440  FROM '.USER_FEED_TABLE.'
441  WHERE id = \''.$key.'\'
442;';
443    list($count) = mysql_fetch_row(pwg_query($query));
444    if (0 == $count)
445    {
446      return $key;
447    }
448  }
449}
450
451/**
452 * add user informations based on default values
453 *
454 * @param int user_id
455 */
456function create_user_infos($user_id)
457{
458  global $conf;
459 
460  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
461
462  $insert =
463    array(
464      'user_id' => $user_id,
465      'status' => $user_id == $conf['webmaster_id'] ? 'admin' : 'guest',
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      );
477
478  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
479  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
480}
481
482/**
483 * returns the groupname corresponding to the given group identifier if
484 * exists
485 *
486 * @param int group_id
487 * @return mixed
488 */
489function get_groupname($group_id)
490{
491  $query = '
492SELECT name
493  FROM '.GROUPS_TABLE.'
494  WHERE id = '.intval($group_id).'
495;';
496  $result = pwg_query($query);
497  if (mysql_num_rows($result) > 0)
498  {
499    list($groupname) = mysql_fetch_row($result);
500  }
501  else
502  {
503    return false;
504  }
505 
506  return $groupname;
507}
508
509/**
510 * return the file path of the given language filename, depending on the
511 * availability of the file
512 *
513 * in descending order of preference: user language, default language,
514 * PhpWebGallery default language.
515 *
516 * @param string filename
517 * @return string filepath
518 */
519function get_language_filepath($filename)
520{
521  global $user, $conf;
522 
523  $directories =
524    array(
525      PHPWG_ROOT_PATH.'language/'.$user['language'],
526      PHPWG_ROOT_PATH.'language/'.$conf['default_language'],
527      PHPWG_ROOT_PATH.'language/'.PHPWG_DEFAULT_LANGUAGE
528      );
529
530  foreach ($directories as $directory)
531  {
532    $filepath = $directory.'/'.$filename;
533   
534    if (file_exists($filepath))
535    {
536      return $filepath;
537    }
538  }
539 
540  return false;
541}
542?>
Note: See TracBrowser for help on using the repository browser.