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

Last change on this file since 1156 was 1119, checked in by plg, 18 years ago

improvement: tags replace keywords. Better data model, less
limitations. Each image can be associated to as many tag as needed. Tags can
contain non ASCII characters. Oriented navigation with tags by association.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 14.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-2006 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: functions_user.inc.php 1119 2006-04-02 22:26:19Z plg $
9// | last update   : $Date: 2006-04-02 22:26:19 +0000 (Sun, 02 Apr 2006) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 1119 $
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 -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
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  if (!is_autorize_status($access_type, $user_status))
612  {
613    access_denied();
614  }
615}
616
617/*
618 * Return if user is an administrator
619 * @return bool
620*/
621function is_admin($user_status = '')
622{
623  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
624}
625
626/*
627 * Return if current user is an adviser
628 * @return bool
629*/
630function is_adviser()
631{
632  global $user;
633
634  return ($user['adviser'] == 'true');
635}
636?>
Note: See TracBrowser for help on using the repository browser.