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

Last change on this file since 1051 was 1036, checked in by plg, 18 years ago

improvement: $pagewhere string replaced by $pageitems.
$pagewhere was an SQL clause used to retrieve pictures in #images
table. $pageitems is the list of picture ids of the current section.

improvement: function initialize_category replaced by dedicated included PHP
script include/section_init.inc.php. Code was refactored to improve
readibility and maintenability. $pagenavigation_bar is now build in
category.php instead of initialize_category function. Function check_cat_id
was also replaced by a piece of code in the new file. The file to include to
display thumbnails from category.php is now set in section_init.inc.php
instead of calculated in category.php.

bug fix: the test for rel="up" link for standard HTML navigation links in
category menu was not working with non numeric categories, such as
"favorites".

improvement: function check_login_authorization removed because useless but
in profile.php.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 12.6 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: 2006-02-12 21:52:16 +0000 (Sun, 12 Feb 2006) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 1036 $
12// | revision      : $Revision: 1036 $
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      // update user cache
192      $query = '
193DELETE FROM '.USER_CACHE_TABLE.'
194  WHERE user_id = '.$userdata['id'].'
195;';
196      pwg_query($query);
197 
198      $query = '
199INSERT INTO '.USER_CACHE_TABLE.'
200  (user_id,need_update,forbidden_categories)
201  VALUES
202  ('.$userdata['id'].',\'false\',\''.$userdata['forbidden_categories'].'\')
203;';
204      pwg_query($query);
205    }
206  }
207
208  return $userdata;
209}
210
211/*
212 * deletes favorites of the current user if he's not allowed to see them
213 *
214 * @return void
215 */
216function check_user_favorites()
217{
218  global $user;
219
220  if ($user['forbidden_categories'] == '')
221  {
222    return;
223  }
224
225  // retrieving images allowed : belonging to at least one authorized
226  // category
227  $query = '
228SELECT DISTINCT f.image_id
229  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
230    ON f.image_id = ic.image_id
231  WHERE f.user_id = '.$user['id'].'
232    AND ic.category_id NOT IN ('.$user['forbidden_categories'].')
233;';
234  $result = pwg_query($query);
235  $authorizeds = array();
236  while ($row = mysql_fetch_array($result))
237  {
238    array_push($authorizeds, $row['image_id']);
239  }
240
241  $query = '
242SELECT image_id
243  FROM '.FAVORITES_TABLE.'
244  WHERE user_id = '.$user['id'].'
245;';
246  $result = pwg_query($query);
247  $favorites = array();
248  while ($row = mysql_fetch_array($result))
249  {
250    array_push($favorites, $row['image_id']);
251  }
252
253  $to_deletes = array_diff($favorites, $authorizeds);
254
255  if (count($to_deletes) > 0)
256  {
257    $query = '
258DELETE FROM '.FAVORITES_TABLE.'
259  WHERE image_id IN ('.implode(',', $to_deletes).')
260    AND user_id = '.$user['id'].'
261;';
262    pwg_query($query);
263  }
264}
265
266/**
267 * calculates the list of forbidden categories for a given user
268 *
269 * Calculation is based on private categories minus categories authorized to
270 * the groups the user belongs to minus the categories directly authorized
271 * to the user. The list contains at least -1 to be compliant with queries
272 * such as "WHERE category_id NOT IN ($forbidden_categories)"
273 *
274 * @param int user_id
275 * @param string user_status
276 * @return string forbidden_categories
277 */
278function calculate_permissions($user_id, $user_status)
279{
280  $private_array = array();
281  $authorized_array = array();
282
283  $query = '
284SELECT id
285  FROM '.CATEGORIES_TABLE.'
286  WHERE status = \'private\'
287;';
288  $result = pwg_query($query);
289  while ($row = mysql_fetch_array($result))
290  {
291    array_push($private_array, $row['id']);
292  }
293
294  // if user is not an admin, locked categories can be considered as private$
295  if ($user_status != 'admin')
296  {
297    $query = '
298SELECT id
299  FROM '.CATEGORIES_TABLE.'
300  WHERE visible = \'false\'
301;';
302    $result = pwg_query($query);
303    while ($row = mysql_fetch_array($result))
304    {
305      array_push($private_array, $row['id']);
306    }
307
308    $private_array = array_unique($private_array);
309  }
310 
311  // retrieve category ids directly authorized to the user
312  $query = '
313SELECT cat_id
314  FROM '.USER_ACCESS_TABLE.'
315  WHERE user_id = '.$user_id.'
316;';
317  $authorized_array = array_from_query($query, 'cat_id');
318
319  // retrieve category ids authorized to the groups the user belongs to
320  $query = '
321SELECT cat_id
322  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
323    ON ug.group_id = ga.group_id
324  WHERE ug.user_id = '.$user_id.'
325;';
326  $authorized_array =
327    array_merge(
328      $authorized_array,
329      array_from_query($query, 'cat_id')
330      );
331
332  // uniquify ids : some private categories might be authorized for the
333  // groups and for the user
334  $authorized_array = array_unique($authorized_array);
335
336  // only unauthorized private categories are forbidden
337  $forbidden_array = array_diff($private_array, $authorized_array);
338
339  // at least, the list contains -1 values. This category does not exists so
340  // where clauses such as "WHERE category_id NOT IN(-1)" will always be
341  // true.
342  array_push($forbidden_array, '-1');
343 
344  return implode(',', $forbidden_array);
345}
346
347/**
348 * returns the username corresponding to the given user identifier if exists
349 *
350 * @param int user_id
351 * @return mixed
352 */
353function get_username($user_id)
354{
355  global $conf;
356 
357  $query = '
358SELECT '.$conf['user_fields']['username'].'
359  FROM '.USERS_TABLE.'
360  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
361;';
362  $result = pwg_query($query);
363  if (mysql_num_rows($result) > 0)
364  {
365    list($username) = mysql_fetch_row($result);
366  }
367  else
368  {
369    return false;
370  }
371 
372  return $username;
373}
374
375/**
376 * returns user identifier thanks to his name, false if not found
377 *
378 * @param string username
379 * @param int user identifier
380 */
381function get_userid($username)
382{
383  global $conf;
384
385  $username = mysql_escape_string($username);
386
387  $query = '
388SELECT '.$conf['user_fields']['id'].'
389  FROM '.USERS_TABLE.'
390  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
391;';
392  $result = pwg_query($query);
393
394  if (mysql_num_rows($result) == 0)
395  {
396    return false;
397  }
398  else
399  {
400    list($user_id) = mysql_fetch_row($result);
401    return $user_id;
402  }
403}
404
405/**
406 * search an available feed_id
407 *
408 * @return string feed identifier
409 */
410function find_available_feed_id()
411{
412  while (true)
413  {
414    $key = generate_key(50);
415    $query = '
416SELECT COUNT(*)
417  FROM '.USER_FEED_TABLE.'
418  WHERE id = \''.$key.'\'
419;';
420    list($count) = mysql_fetch_row(pwg_query($query));
421    if (0 == $count)
422    {
423      return $key;
424    }
425  }
426}
427
428/**
429 * add user informations based on default values
430 *
431 * @param int user_id
432 */
433function create_user_infos($user_id)
434{
435  global $conf;
436 
437  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
438
439  $insert =
440    array(
441      'user_id' => $user_id,
442      'status' => $user_id == $conf['webmaster_id'] ? 'admin' : 'guest',
443      'template' => $conf['default_template'],
444      'nb_image_line' => $conf['nb_image_line'],
445      'nb_line_page' => $conf['nb_line_page'],
446      'language' => $conf['default_language'],
447      'recent_period' => $conf['recent_period'],
448      'expand' => boolean_to_string($conf['auto_expand']),
449      'show_nb_comments' => boolean_to_string($conf['show_nb_comments']),
450      'maxwidth' => $conf['default_maxwidth'],
451      'maxheight' => $conf['default_maxheight'],
452      'registration_date' => $dbnow
453      );
454
455  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
456  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
457}
458
459/**
460 * returns the groupname corresponding to the given group identifier if
461 * exists
462 *
463 * @param int group_id
464 * @return mixed
465 */
466function get_groupname($group_id)
467{
468  $query = '
469SELECT name
470  FROM '.GROUPS_TABLE.'
471  WHERE id = '.intval($group_id).'
472;';
473  $result = pwg_query($query);
474  if (mysql_num_rows($result) > 0)
475  {
476    list($groupname) = mysql_fetch_row($result);
477  }
478  else
479  {
480    return false;
481  }
482 
483  return $groupname;
484}
485
486/**
487 * return the file path of the given language filename, depending on the
488 * availability of the file
489 *
490 * in descending order of preference: user language, default language,
491 * PhpWebGallery default language.
492 *
493 * @param string filename
494 * @return string filepath
495 */
496function get_language_filepath($filename)
497{
498  global $user, $conf;
499 
500  $directories =
501    array(
502      PHPWG_ROOT_PATH.'language/'.$user['language'],
503      PHPWG_ROOT_PATH.'language/'.$conf['default_language'],
504      PHPWG_ROOT_PATH.'language/'.PHPWG_DEFAULT_LANGUAGE
505      );
506
507  foreach ($directories as $directory)
508  {
509    $filepath = $directory.'/'.$filename;
510   
511    if (file_exists($filepath))
512    {
513      return $filepath;
514    }
515  }
516 
517  return false;
518}
519?>
Note: See TracBrowser for help on using the repository browser.