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

Last change on this file since 1113 was 1113, checked in by rvelices, 18 years ago

fix: image_order cookie path fixed for url rewriting

improve: add function access_denied called when check_status or
check_restrictions fail

fix: french language correction

fix: remove php warnings in clean_iptc_value

split search functions into include/functions_search.inc.php

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 14.8 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 1113 2006-03-30 00:37:07Z rvelices $
9// | last update   : $Date: 2006-03-30 00:37:07 +0000 (Thu, 30 Mar 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1113 $
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  // if user is not an admin, locked categories can be considered as private$
304  if (!is_admin($user_status))
305  {
306    $query = '
307SELECT id
308  FROM '.CATEGORIES_TABLE.'
309  WHERE visible = \'false\'
310;';
311    $result = pwg_query($query);
312    while ($row = mysql_fetch_array($result))
313    {
314      array_push($private_array, $row['id']);
315    }
316
317    $private_array = array_unique($private_array);
318  }
319
320  // retrieve category ids directly authorized to the user
321  $query = '
322SELECT cat_id
323  FROM '.USER_ACCESS_TABLE.'
324  WHERE user_id = '.$user_id.'
325;';
326  $authorized_array = array_from_query($query, 'cat_id');
327
328  // retrieve category ids authorized to the groups the user belongs to
329  $query = '
330SELECT cat_id
331  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
332    ON ug.group_id = ga.group_id
333  WHERE ug.user_id = '.$user_id.'
334;';
335  $authorized_array =
336    array_merge(
337      $authorized_array,
338      array_from_query($query, 'cat_id')
339      );
340
341  // uniquify ids : some private categories might be authorized for the
342  // groups and for the user
343  $authorized_array = array_unique($authorized_array);
344
345  // only unauthorized private categories are forbidden
346  $forbidden_array = array_diff($private_array, $authorized_array);
347
348  // at least, the list contains -1 values. This category does not exists so
349  // where clauses such as "WHERE category_id NOT IN(-1)" will always be
350  // true.
351  array_push($forbidden_array, '-1');
352
353  return implode(',', $forbidden_array);
354}
355
356/**
357 * returns the username corresponding to the given user identifier if exists
358 *
359 * @param int user_id
360 * @return mixed
361 */
362function get_username($user_id)
363{
364  global $conf;
365
366  $query = '
367SELECT '.$conf['user_fields']['username'].'
368  FROM '.USERS_TABLE.'
369  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
370;';
371  $result = pwg_query($query);
372  if (mysql_num_rows($result) > 0)
373  {
374    list($username) = mysql_fetch_row($result);
375  }
376  else
377  {
378    return false;
379  }
380
381  return $username;
382}
383
384/**
385 * returns user identifier thanks to his name, false if not found
386 *
387 * @param string username
388 * @param int user identifier
389 */
390function get_userid($username)
391{
392  global $conf;
393
394  $username = mysql_escape_string($username);
395
396  $query = '
397SELECT '.$conf['user_fields']['id'].'
398  FROM '.USERS_TABLE.'
399  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
400;';
401  $result = pwg_query($query);
402
403  if (mysql_num_rows($result) == 0)
404  {
405    return false;
406  }
407  else
408  {
409    list($user_id) = mysql_fetch_row($result);
410    return $user_id;
411  }
412}
413
414/**
415 * search an available feed_id
416 *
417 * @return string feed identifier
418 */
419function find_available_feed_id()
420{
421  while (true)
422  {
423    $key = generate_key(50);
424    $query = '
425SELECT COUNT(*)
426  FROM '.USER_FEED_TABLE.'
427  WHERE id = \''.$key.'\'
428;';
429    list($count) = mysql_fetch_row(pwg_query($query));
430    if (0 == $count)
431    {
432      return $key;
433    }
434  }
435}
436
437/**
438 * add user informations based on default values
439 *
440 * @param int user_id
441 */
442function create_user_infos($user_id)
443{
444  global $conf;
445
446  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
447
448  $insert =
449    array(
450      'user_id' => $user_id,
451      'status' => $user_id == $conf['webmaster_id'] ? 'admin' : 'normal',
452      'template' => $conf['default_template'],
453      'nb_image_line' => $conf['nb_image_line'],
454      'nb_line_page' => $conf['nb_line_page'],
455      'language' => $conf['default_language'],
456      'recent_period' => $conf['recent_period'],
457      'expand' => boolean_to_string($conf['auto_expand']),
458      'show_nb_comments' => boolean_to_string($conf['show_nb_comments']),
459      'maxwidth' => $conf['default_maxwidth'],
460      'maxheight' => $conf['default_maxheight'],
461      'registration_date' => $dbnow,
462      'enabled_high' => $conf['newuser_default_enabled_high']
463      );
464
465  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
466  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
467}
468
469/**
470 * returns the groupname corresponding to the given group identifier if
471 * exists
472 *
473 * @param int group_id
474 * @return mixed
475 */
476function get_groupname($group_id)
477{
478  $query = '
479SELECT name
480  FROM '.GROUPS_TABLE.'
481  WHERE id = '.intval($group_id).'
482;';
483  $result = pwg_query($query);
484  if (mysql_num_rows($result) > 0)
485  {
486    list($groupname) = mysql_fetch_row($result);
487  }
488  else
489  {
490    return false;
491  }
492
493  return $groupname;
494}
495
496/**
497 * return the file path of the given language filename, depending on the
498 * availability of the file
499 *
500 * in descending order of preference: user language, default language,
501 * PhpWebGallery default language.
502 *
503 * @param string filename
504 * @return string filepath
505 */
506function get_language_filepath($filename)
507{
508  global $user, $conf;
509
510  $directories =
511    array(
512      PHPWG_ROOT_PATH.'language/'.$user['language'],
513      PHPWG_ROOT_PATH.'language/'.$conf['default_language'],
514      PHPWG_ROOT_PATH.'language/'.PHPWG_DEFAULT_LANGUAGE
515      );
516
517  foreach ($directories as $directory)
518  {
519    $filepath = $directory.'/'.$filename;
520
521    if (file_exists($filepath))
522    {
523      return $filepath;
524    }
525  }
526
527  return false;
528}
529
530/*
531 * Performs all required actions for user login
532 * @param int user_id
533 * @param bool remember_me
534 * @return void
535*/
536function log_user($user_id, $remember_me)
537{
538  global $conf;
539  $session_length = $conf['session_length'];
540  if ($remember_me)
541  {
542    $session_length = $conf['remember_me_length'];
543  }
544  session_set_cookie_params($session_length);
545  session_start();
546  $_SESSION['id'] = $user_id;
547}
548
549/*
550 * Return access_type definition of uuser
551 * Test does with user status
552 * @return bool
553*/
554function get_access_type_status($user_status = '')
555{
556  global $user;
557
558  if (($user_status == '') and isset($user['status']))
559  {
560    $user_status = $user['status'];
561  }
562
563  $access_type_status = ACCESS_NONE;
564  switch ($user_status)
565  {
566    case 'guest':
567    case 'generic':
568    {
569      $access_type_status = ACCESS_GUEST;
570      break;
571    }
572    case 'normal':
573    {
574      $access_type_status = ACCESS_CLASSIC;
575      break;
576    }
577    case 'admin':
578    {
579      $access_type_status = ACCESS_ADMINISTRATOR;
580      break;
581    }
582    case 'webmaster':
583    {
584      $access_type_status = ACCESS_WEBMASTER;
585      break;
586    }
587  }
588
589  return $access_type_status;
590}
591
592/*
593 * Return if user have access to access_type definition
594 * Test does with user status
595 * @return bool
596*/
597function is_autorize_status($access_type, $user_status = '')
598{
599  return (get_access_type_status($user_status) >= $access_type);
600}
601
602/*
603 * Check if user have access to access_type definition
604 * Stop action if there are not access
605 * Test does with user status
606 * @return none
607*/
608function check_status($access_type, $user_status = '')
609{
610  if (!is_autorize_status($access_type, $user_status))
611  {
612    access_denied();
613  }
614}
615
616/*
617 * Return if user is an administrator
618 * @return bool
619*/
620function is_admin($user_status = '')
621{
622  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
623}
624
625/*
626 * Return if current user is an adviser
627 * @return bool
628*/
629function is_adviser()
630{
631  global $user;
632
633  return ($user['adviser'] == 'true');
634}
635
636?>
Note: See TracBrowser for help on using the repository browser.