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

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