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

Last change on this file since 3450 was 3450, checked in by nikrou, 15 years ago

Feature 1026 step 2 :
add author_id column so that guest cannot modify old users comments

  • Property svn:eol-style set to LF
File size: 32.1 KB
RevLine 
[2]1<?php
[362]2// +-----------------------------------------------------------------------+
[2297]3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
[3049]5// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
[2297]6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
[2]23
[2115]24// validate_mail_address:
25//   o verifies whether the given mail address has the
26//     right format. ie someone@domain.com "someone" can contain ".", "-" or
27//     even "_". Exactly as "domain". The extension doesn't have to be
28//     "com". The mail address can also be empty.
29//   o check if address could be empty
30//   o check if address is not used by a other user
[9]31// If the mail address doesn't correspond, an error message is returned.
[2127]32//
[2124]33function validate_mail_address($user_id, $mail_address)
[2]34{
[2115]35  global $conf;
[2]36
[2032]37  if (empty($mail_address) and
[2127]38      !($conf['obligatory_user_mail_address'] and
[2124]39      in_array(script_basename(), array('register', 'profile'))))
[2]40  {
[9]41    return '';
[2]42  }
[2115]43
[2507]44  $atom   = '[-a-z0-9!#$%&\'*+\\/=?^_`{|}~]';   // before  arobase
[2572]45  $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // domain name
[2507]46  $regex = '/^' . $atom . '+' . '(\.' . $atom . '+)*' . '@' . '(' . $domain . '{1,63}\.)+' . $domain . '{2,63}$/i';
47
[9]48  if ( !preg_match( $regex, $mail_address ) )
49  {
[2115]50    return l10n('reg_err_mail_address');
[9]51  }
[2127]52
[2115]53  if (defined("PHPWG_INSTALLED") and !empty($mail_address))
54  {
55    $query = '
56select count(*)
57from '.USERS_TABLE.'
58where upper('.$conf['user_fields']['email'].') = upper(\''.$mail_address.'\')
[2124]59'.(is_numeric($user_id) ? 'and '.$conf['user_fields']['id'].' != \''.$user_id.'\'' : '').'
[2115]60;';
61    list($count) = mysql_fetch_array(pwg_query($query));
62    if ($count != 0)
63    {
64      return l10n('reg_err_mail_address_dbl');
65    }
66  }
[2]67}
68
[2178]69function register_user($login, $password, $mail_address,
70  $with_notification = true, $errors = array())
[2]71{
[2115]72  global $conf;
[2]73
[661]74  if ($login == '')
75  {
[2115]76    array_push($errors, l10n('reg_err_login1'));
[661]77  }
78  if (ereg("^.* $", $login))
79  {
[2115]80    array_push($errors, l10n('reg_err_login2'));
[661]81  }
82  if (ereg("^ .*$", $login))
83  {
[2115]84    array_push($errors, l10n('reg_err_login3'));
[661]85  }
[808]86  if (get_userid($login))
[804]87  {
[2115]88    array_push($errors, l10n('reg_err_login5'));
[2]89  }
[2124]90  $mail_error = validate_mail_address(null, $mail_address);
[808]91  if ('' != $mail_error)
[661]92  {
[808]93    array_push($errors, $mail_error);
[661]94  }
[2]95
[2237]96  $errors = trigger_event('register_user_check',
97              $errors,
98              array(
[2268]99                'username'=>$login,
[2237]100                'password'=>$password,
101                'email'=>$mail_address,
102              )
103            );
104
[9]105  // if no error until here, registration of the user
[661]106  if (count($errors) == 0)
[2]107  {
[906]108    // what will be the inserted id ?
109    $query = '
110SELECT MAX('.$conf['user_fields']['id'].') + 1
111  FROM '.USERS_TABLE.'
112;';
113    list($next_id) = mysql_fetch_array(pwg_query($query));
[1068]114
[808]115    $insert =
116      array(
[906]117        $conf['user_fields']['id'] => $next_id,
[2752]118        $conf['user_fields']['username'] => mysql_real_escape_string($login),
[808]119        $conf['user_fields']['password'] => $conf['pass_convert']($password),
120        $conf['user_fields']['email'] => $mail_address
121        );
[661]122
[808]123    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
124    mass_inserts(USERS_TABLE, array_keys($insert), array($insert));
[1068]125
[2178]126    // Assign by default groups
127    {
128      $query = '
[1583]129SELECT id
130  FROM '.GROUPS_TABLE.'
131  WHERE is_default = \''.boolean_to_string(true).'\'
132  ORDER BY id ASC
133;';
[2178]134      $result = pwg_query($query);
[1581]135
[2178]136      $inserts = array();
137      while ($row = mysql_fetch_array($result))
138      {
139        array_push
[1583]140        (
[2178]141          $inserts,
142          array
143          (
144            'user_id' => $next_id,
145            'group_id' => $row['id']
146          )
147        );
148      }
[1583]149    }
[1581]150
[1583]151    if (count($inserts) != 0)
152    {
[1581]153      include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
[1583]154      mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts);
[1581]155    }
156
[2425]157    $override = null;
158    if ($with_notification and $conf['browser_language'])
159    {
160      if ( !get_browser_language($override['language']) )
161        $override=null;
162    }
163    create_user_infos($next_id, $override);
[1605]164
[2178]165    if ($with_notification and $conf['email_admin_on_new_user'])
166    {
167      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
168      $admin_url = get_absolute_root_url()
[2268]169                   .'admin.php?page=user_list&username='.$login;
[2178]170
171      $keyargs_content = array
172      (
[2268]173        get_l10n_args('User: %s', $login),
[2178]174        get_l10n_args('Email: %s', $_POST['mail_address']),
175        get_l10n_args('', ''),
176        get_l10n_args('Admin: %s', $admin_url)
177      );
178
179      pwg_mail_notification_admins
180      (
[2268]181        get_l10n_args('Registration of %s', $login),
[2178]182        $keyargs_content
183      );
184    }
185
[1605]186    trigger_action('register_user',
187      array(
188        'id'=>$next_id,
189        'username'=>$login,
190        'email'=>$mail_address,
191       )
192      );
[2]193  }
[906]194
[661]195  return $errors;
[2]196}
197
[1677]198function build_user( $user_id, $use_cache )
[1568]199{
200  global $conf;
[2038]201
[1568]202  $user['id'] = $user_id;
[1677]203  $user = array_merge( $user, getuserdata($user_id, $use_cache) );
[1926]204
[2055]205  if ($user['id'] == $conf['guest_id'] and $user['status'] <> 'guest')
206  {
207    $user['status'] = 'guest';
208    $user['internal_status']['guest_must_be_guest'] = true;
209  }
210
[1568]211  // calculation of the number of picture to display per page
212  $user['nb_image_page'] = $user['nb_image_line'] * $user['nb_line_page'];
213
[2039]214  list($user['template'], $user['theme']) = explode('/', $user['template']);
215
[1568]216  return $user;
217}
218
[808]219/**
220 * find informations related to the user identifier
221 *
222 * @param int user identifier
223 * @param boolean use_cache
224 * @param array
225 */
[1677]226function getuserdata($user_id, $use_cache)
[393]227{
[808]228  global $conf;
229
230  $userdata = array();
[1068]231
[808]232  $query = '
233SELECT ';
234  $is_first = true;
235  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
236  {
237    if ($is_first)
238    {
239      $is_first = false;
240    }
241    else
242    {
243      $query.= '
244     , ';
245    }
246    $query.= $dbfield.' AS '.$pwgfield;
247  }
248  $query.= '
249  FROM '.USERS_TABLE.'
250  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'
251;';
[1068]252
[808]253  $row = mysql_fetch_array(pwg_query($query));
254
255  while (true)
256  {
257    $query = '
258SELECT ui.*, uc.*
259  FROM '.USER_INFOS_TABLE.' AS ui LEFT JOIN '.USER_CACHE_TABLE.' AS uc
260    ON ui.user_id = uc.user_id
261  WHERE ui.user_id = \''.$user_id.'\'
262;';
263    $result = pwg_query($query);
264    if (mysql_num_rows($result) > 0)
265    {
266      break;
267    }
268    else
269    {
270      create_user_infos($user_id);
271    }
272  }
[1068]273
[808]274  $row = array_merge($row, mysql_fetch_array($result));
[1068]275
[808]276  foreach ($row as $key => $value)
277  {
278    if (!is_numeric($key))
279    {
280      // If the field is true or false, the variable is transformed into a
281      // boolean value.
282      if ($value == 'true' or $value == 'false')
283      {
284        $userdata[$key] = get_boolean($value);
285      }
286      else
287      {
288        $userdata[$key] = $value;
289      }
290    }
291  }
292
293  if ($use_cache)
294  {
295    if (!isset($userdata['need_update'])
296        or !is_bool($userdata['need_update'])
[1677]297        or $userdata['need_update'] == true)
[808]298    {
[2448]299      $userdata['cache_update_time'] = time();
300
301      // Set need update are done
302      $userdata['need_update'] = false;
303
[808]304      $userdata['forbidden_categories'] =
305        calculate_permissions($userdata['id'], $userdata['status']);
306
[2084]307      /* now we build the list of forbidden images (this list does not contain
308      images that are not in at least an authorized category)*/
309      $query = '
310SELECT DISTINCT(id)
311  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
312  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
313    AND level>'.$userdata['level'];
314      $forbidden_ids = array_from_query($query, 'id');
315
316      if ( empty($forbidden_ids) )
317      {
318        array_push( $forbidden_ids, 0 );
319      }
320      $userdata['image_access_type'] = 'NOT IN'; //TODO maybe later
321      $userdata['image_access_list'] = implode(',',$forbidden_ids);
322
[1860]323      update_user_cache_categories($userdata);
[1624]324
[1081]325      $query = '
326SELECT COUNT(DISTINCT(image_id)) as total
327  FROM '.IMAGE_CATEGORY_TABLE.'
328  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
[2084]329    AND image_id '.$userdata['image_access_type'].' ('.$userdata['image_access_list'].')
[1081]330;';
331      list($userdata['nb_total_images']) = mysql_fetch_array(pwg_query($query));
332
[808]333      // update user cache
334      $query = '
335DELETE FROM '.USER_CACHE_TABLE.'
336  WHERE user_id = '.$userdata['id'].'
337;';
338      pwg_query($query);
[1068]339
[808]340      $query = '
341INSERT INTO '.USER_CACHE_TABLE.'
[2448]342  (user_id, need_update, cache_update_time, forbidden_categories, nb_total_images,
[2084]343    image_access_type, image_access_list)
[808]344  VALUES
[2448]345  ('.$userdata['id'].',\''.boolean_to_string($userdata['need_update']).'\','
346  .$userdata['cache_update_time'].',\''
[2084]347  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].',"'
348  .$userdata['image_access_type'].'","'.$userdata['image_access_list'].'")
[808]349;';
350      pwg_query($query);
351    }
352  }
353
354  return $userdata;
[393]355}
[647]356
357/*
358 * deletes favorites of the current user if he's not allowed to see them
359 *
360 * @return void
361 */
362function check_user_favorites()
363{
364  global $user;
365
366  if ($user['forbidden_categories'] == '')
367  {
368    return;
369  }
[832]370
[1677]371  // $filter['visible_categories'] and $filter['visible_images']
372  // must be not used because filter <> restriction
[832]373  // retrieving images allowed : belonging to at least one authorized
374  // category
[647]375  $query = '
[832]376SELECT DISTINCT f.image_id
[647]377  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
378    ON f.image_id = ic.image_id
379  WHERE f.user_id = '.$user['id'].'
[1677]380'.get_sql_condition_FandF
381  (
382    array
383      (
384        'forbidden_categories' => 'ic.category_id',
385      ),
386    'AND'
387  ).'
[647]388;';
389  $result = pwg_query($query);
[832]390  $authorizeds = array();
[647]391  while ($row = mysql_fetch_array($result))
392  {
[832]393    array_push($authorizeds, $row['image_id']);
[647]394  }
395
[832]396  $query = '
397SELECT image_id
398  FROM '.FAVORITES_TABLE.'
399  WHERE user_id = '.$user['id'].'
400;';
401  $result = pwg_query($query);
402  $favorites = array();
403  while ($row = mysql_fetch_array($result))
[647]404  {
[832]405    array_push($favorites, $row['image_id']);
406  }
407
408  $to_deletes = array_diff($favorites, $authorizeds);
409
410  if (count($to_deletes) > 0)
411  {
[647]412    $query = '
413DELETE FROM '.FAVORITES_TABLE.'
[832]414  WHERE image_id IN ('.implode(',', $to_deletes).')
[647]415    AND user_id = '.$user['id'].'
416;';
417    pwg_query($query);
418  }
419}
[648]420
421/**
[808]422 * calculates the list of forbidden categories for a given user
[648]423 *
[808]424 * Calculation is based on private categories minus categories authorized to
425 * the groups the user belongs to minus the categories directly authorized
426 * to the user. The list contains at least -1 to be compliant with queries
427 * such as "WHERE category_id NOT IN ($forbidden_categories)"
[648]428 *
429 * @param int user_id
[680]430 * @param string user_status
[648]431 * @return string forbidden_categories
432 */
[680]433function calculate_permissions($user_id, $user_status)
[648]434{
435  $private_array = array();
436  $authorized_array = array();
437
438  $query = '
439SELECT id
440  FROM '.CATEGORIES_TABLE.'
441  WHERE status = \'private\'
442;';
443  $result = pwg_query($query);
444  while ($row = mysql_fetch_array($result))
445  {
446    array_push($private_array, $row['id']);
447  }
[680]448
[648]449  // retrieve category ids directly authorized to the user
450  $query = '
451SELECT cat_id
452  FROM '.USER_ACCESS_TABLE.'
453  WHERE user_id = '.$user_id.'
454;';
[808]455  $authorized_array = array_from_query($query, 'cat_id');
[648]456
457  // retrieve category ids authorized to the groups the user belongs to
458  $query = '
459SELECT cat_id
460  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
461    ON ug.group_id = ga.group_id
462  WHERE ug.user_id = '.$user_id.'
463;';
[808]464  $authorized_array =
465    array_merge(
466      $authorized_array,
467      array_from_query($query, 'cat_id')
468      );
[648]469
470  // uniquify ids : some private categories might be authorized for the
471  // groups and for the user
472  $authorized_array = array_unique($authorized_array);
473
474  // only unauthorized private categories are forbidden
475  $forbidden_array = array_diff($private_array, $authorized_array);
476
[1117]477  // if user is not an admin, locked categories are forbidden
[1851]478  if (!is_admin($user_status))
[1117]479  {
480    $query = '
481SELECT id
482  FROM '.CATEGORIES_TABLE.'
483  WHERE visible = \'false\'
484;';
485    $result = pwg_query($query);
486    while ($row = mysql_fetch_array($result))
487    {
488      array_push($forbidden_array, $row['id']);
489    }
490    $forbidden_array = array_unique($forbidden_array);
491  }
[1068]492
[1117]493  if ( empty($forbidden_array) )
[1331]494  {// at least, the list contains 0 value. This category does not exists so
495   // where clauses such as "WHERE category_id NOT IN(0)" will always be
[1117]496   // true.
[1331]497    array_push($forbidden_array, 0);
[1117]498  }
499
[808]500  return implode(',', $forbidden_array);
[648]501}
[708]502
503/**
[1677]504 * compute data of categories branches (one branch only)
[1624]505 */
[1640]506function compute_branch_cat_data(&$cats, &$list_cat_id, &$level, &$ref_level)
[1624]507{
[1640]508  $date = '';
509  $count_images = 0;
510  $count_categories = 0;
511  do
[1624]512  {
[1640]513    $cat_id = array_pop($list_cat_id);
514    if (!is_null($cat_id))
[1624]515    {
[1640]516      // Count images and categories
517      $cats[$cat_id]['count_images'] += $count_images;
518      $cats[$cat_id]['count_categories'] += $count_categories;
519      $count_images = $cats[$cat_id]['count_images'];
520      $count_categories = $cats[$cat_id]['count_categories'] + 1;
521
522      if ((empty($cats[$cat_id]['max_date_last'])) or ($cats[$cat_id]['max_date_last'] < $date))
[1624]523      {
[1640]524        $cats[$cat_id]['max_date_last'] = $date;
[1624]525      }
526      else
527      {
[1640]528        $date = $cats[$cat_id]['max_date_last'];
[1624]529      }
[1640]530      $ref_level = substr_count($cats[$cat_id]['global_rank'], '.') + 1;
531    }
532    else
[1624]533    {
[1640]534      $ref_level = 0;
[1624]535    }
[1640]536  } while ($level <= $ref_level);
537
538  // Last cat updating must be added to list for next branch
539  if ($ref_level <> 0)
540  {
541    array_push($list_cat_id, $cat_id);
[1624]542  }
[1640]543}
[1624]544
[1640]545/**
[1677]546 * compute data of categories branches
[1640]547 */
[1677]548function compute_categories_data(&$cats)
[1640]549{
[1677]550  $ref_level = 0;
551  $level = 0;
552  $list_cat_id = array();
[1624]553
[1677]554  foreach ($cats as $id => $category)
[1624]555  {
[1677]556    // Compute
557    $level = substr_count($category['global_rank'], '.') + 1;
558    if ($level > $ref_level)
559    {
560      array_push($list_cat_id, $id);
561    }
562    else
563    {
564      compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
565      array_push($list_cat_id, $id);
566    }
567    $ref_level = $level;
[1624]568  }
[1651]569
[1677]570  $level = 1;
571  compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
572}
[1651]573
[1677]574/**
575 * get computed array of categories
576 *
[1860]577 * @param array userdata
578 * @param int filter_days number of recent days to filter on or null
[1677]579 * @return array
580 */
[1860]581function get_computed_categories($userdata, $filter_days=null)
[1677]582{
[1860]583  $query = 'SELECT c.id cat_id, global_rank';
[2084]584  // Count by date_available to avoid count null
585  $query .= ',
[2324]586  MAX(date_available) date_last, COUNT(date_available) nb_images
[2084]587FROM '.CATEGORIES_TABLE.' as c
588  LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
589  LEFT JOIN '.IMAGES_TABLE.' AS i
590    ON ic.image_id = i.id
591      AND i.level<='.$userdata['level'];
592
593  if ( isset($filter_days) )
[1651]594  {
[2084]595    $query .= ' AND i.date_available > SUBDATE(CURRENT_DATE,INTERVAL '.$filter_days.' DAY)';
[1651]596  }
597
[1860]598  if ( !empty($userdata['forbidden_categories']) )
[1651]599  {
600    $query.= '
[1860]601  WHERE c.id NOT IN ('.$userdata['forbidden_categories'].')';
[1651]602  }
603
[2324]604  $query.= '
605  GROUP BY c.id';
[1624]606
607  $result = pwg_query($query);
608
609  $cats = array();
[1641]610  while ($row = mysql_fetch_assoc($result))
[1624]611  {
[1860]612    $row['user_id'] = $userdata['id'];
[1641]613    $row['count_categories'] = 0;
[2324]614    $row['count_images'] = (int)$row['nb_images'];
615    $row['max_date_last'] = $row['date_last'];
[1860]616
[1624]617    $cats += array($row['cat_id'] => $row);
618  }
619  usort($cats, 'global_rank_compare');
620
[1677]621  compute_categories_data($cats);
[1624]622
[1860]623  if ( isset($filter_days) )
[1624]624  {
[1651]625    $cat_tmp = $cats;
626    $cats = array();
[1860]627
[1677]628    foreach ($cat_tmp as $category)
[1651]629    {
[1677]630      if (!empty($category['max_date_last']))
[1651]631      {
[1677]632        // Re-init counters
633        $category['count_categories'] = 0;
[2324]634        $category['count_images'] = (int)$category['nb_images'];
[1677]635        // Keep category
636        $cats[$category['cat_id']] = $category;
[1651]637      }
638    }
[1677]639    // Compute a second time
640    compute_categories_data($cats);
[1651]641  }
[1677]642  return $cats;
643}
644
645/**
646 * update data of user_cache_categories
647 *
[1860]648 * @param array userdata
[1677]649 * @return null
650 */
[1860]651function update_user_cache_categories($userdata)
[1677]652{
653  // delete user cache
654  $query = '
655DELETE FROM '.USER_CACHE_CATEGORIES_TABLE.'
[1860]656  WHERE user_id = '.$userdata['id'].'
[1677]657;';
658  pwg_query($query);
659
[1860]660  $cats = get_computed_categories($userdata, null);
[1677]661
[1624]662  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
663  mass_inserts
664  (
665    USER_CACHE_CATEGORIES_TABLE,
666    array
667    (
[1641]668      'user_id', 'cat_id',
[2324]669      'date_last', 'max_date_last', 'nb_images', 'count_images', 'count_categories'
[1624]670    ),
671    $cats
672  );
673}
674
675/**
[808]676 * returns user identifier thanks to his name, false if not found
677 *
678 * @param string username
679 * @param int user identifier
680 */
681function get_userid($username)
682{
683  global $conf;
684
[2752]685  $username = mysql_real_escape_string($username);
[808]686
687  $query = '
688SELECT '.$conf['user_fields']['id'].'
689  FROM '.USERS_TABLE.'
690  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
691;';
692  $result = pwg_query($query);
693
694  if (mysql_num_rows($result) == 0)
695  {
696    return false;
697  }
698  else
699  {
700    list($user_id) = mysql_fetch_row($result);
701    return $user_id;
702  }
703}
704
705/**
[801]706 * search an available feed_id
707 *
708 * @return string feed identifier
709 */
710function find_available_feed_id()
711{
712  while (true)
713  {
714    $key = generate_key(50);
715    $query = '
716SELECT COUNT(*)
[833]717  FROM '.USER_FEED_TABLE.'
718  WHERE id = \''.$key.'\'
[801]719;';
720    list($count) = mysql_fetch_row(pwg_query($query));
721    if (0 == $count)
722    {
723      return $key;
724    }
725  }
726}
[808]727
[1926]728/*
729 * Returns a array with default user value
[808]730 *
[1926]731 * @param convert_str allows to convert string value if necessary
[808]732 */
[1926]733function get_default_user_info($convert_str = true)
[808]734{
[3126]735  global $cache, $conf;
[2084]736
[3126]737  if (!isset($cache['default_user']))
[1926]738  {
[3126]739    $query = 'SELECT * FROM '.USER_INFOS_TABLE.
740            ' WHERE user_id = '.$conf['default_user_id'].';';
[1068]741
[1926]742    $result = pwg_query($query);
[3126]743    $cache['default_user'] = mysql_fetch_assoc($result);
[2084]744
[3126]745    if ($cache['default_user'] !== false)
[1930]746    {
[3126]747      unset($cache['default_user']['user_id']);
748      unset($cache['default_user']['status']);
749      unset($cache['default_user']['registration_date']);
[1930]750    }
[1926]751  }
[808]752
[3126]753  if (is_array($cache['default_user']) and $convert_str)
[1284]754  {
[1926]755    $default_user = array();
[3126]756    foreach ($cache['default_user'] as $name => $value)
[1926]757    {
758      // If the field is true or false, the variable is transformed into a
759      // boolean value.
760      if ($value == 'true' or $value == 'false')
761      {
762        $default_user[$name] = get_boolean($value);
763      }
764      else
765      {
766        $default_user[$name] = $value;
767      }
768    }
769    return $default_user;
[1284]770  }
[1926]771  else
[1284]772  {
[3126]773    return $cache['default_user'];
[1284]774  }
[1926]775}
776
777/*
778 * Returns a default user value
779 *
780 * @param value_name: name of value
781 * @param sos_value: value used if don't exist value
782 */
783function get_default_user_value($value_name, $sos_value)
784{
785  $default_user = get_default_user_info(true);
786  if ($default_user === false or !isset($default_user[$value_name]))
787  {
788    return $sos_value;
789  }
[1284]790  else
791  {
[1926]792   return $default_user[$value_name];
[1284]793  }
[1926]794}
[1567]795
[1926]796/*
797 * Returns the default template value
798 *
799 */
800function get_default_template()
801{
802  return get_default_user_value('template', PHPWG_DEFAULT_TEMPLATE);
803}
[808]804
[1926]805/*
806 * Returns the default language value
807 *
808 */
809function get_default_language()
810{
[2425]811  return get_default_user_value('language', PHPWG_DEFAULT_LANGUAGE);
[808]812}
[817]813
814/**
[2425]815  * Returns true if the browser language value is set into param $lang
[2411]816  *
817  */
[2425]818function get_browser_language(&$lang)
[2411]819{
[2572]820  $browser_language = substr(@$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
[2411]821  foreach (get_languages() as $language_code => $language_name)
822  {
823    if (substr($language_code, 0, 2) == $browser_language)
824    {
[2425]825      $lang = $language_code;
826      return true;
[2411]827    }
828  }
[2425]829  return false;
[2411]830}
831
832/**
[1926]833 * add user informations based on default values
834 *
835 * @param int user_id / array of user_if
[1930]836 * @param array of values used to override default user values
[1926]837 */
[1930]838function create_user_infos($arg_id, $override_values = null)
[1926]839{
840  global $conf;
841
842  if (is_array($arg_id))
843  {
844    $user_ids = $arg_id;
845  }
846  else
847  {
848    $user_ids = array();
[2229]849    if (is_numeric($arg_id))
[1926]850    {
851      $user_ids[] = $arg_id;
852    }
853  }
854
855  if (!empty($user_ids))
856  {
857    $inserts = array();
858    list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
859
860    $default_user = get_default_user_info(false);
861    if ($default_user === false)
862    {
863      // Default on structure are used
864      $default_user = array();
865    }
866
[1930]867    if (!is_null($override_values))
868    {
869      $default_user = array_merge($default_user, $override_values);
870    }
871
[1926]872    foreach ($user_ids as $user_id)
873    {
[2084]874      $level= isset($default_user['level']) ? $default_user['level'] : 0;
[1926]875      if ($user_id == $conf['webmaster_id'])
876      {
877        $status = 'webmaster';
[2084]878        $level = max( $conf['available_permission_levels'] );
[1926]879      }
[2084]880      else if (($user_id == $conf['guest_id']) or
[1926]881               ($user_id == $conf['default_user_id']))
882      {
883        $status = 'guest';
884      }
885      else
886      {
887        $status = 'normal';
888      }
889
[1930]890      $insert = array_merge(
891        $default_user,
[1926]892        array(
893          'user_id' => $user_id,
894          'status' => $status,
[2084]895          'registration_date' => $dbnow,
896          'level' => $level
[1930]897          ));
[1926]898
899      array_push($inserts, $insert);
[2084]900    }
[1926]901
902    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
903    mass_inserts(USER_INFOS_TABLE, array_keys($inserts[0]), $inserts);
904
905  }
906}
907
908/**
[1622]909 * returns the auto login key or false on error
910 * @param int user_id
[2411]911 * @param time_t time
[1744]912 * @param string [out] username
[1622]913*/
[2409]914function calculate_auto_login_key($user_id, $time, &$username)
[1622]915{
916  global $conf;
917  $query = '
918SELECT '.$conf['user_fields']['username'].' AS username
919  , '.$conf['user_fields']['password'].' AS password
920FROM '.USERS_TABLE.'
921WHERE '.$conf['user_fields']['id'].' = '.$user_id;
922  $result = pwg_query($query);
923  if (mysql_num_rows($result) > 0)
924  {
925    $row = mysql_fetch_assoc($result);
[1744]926    $username = $row['username'];
[2409]927    $data = $time.$row['username'].$row['password'];
[1744]928    $key = base64_encode(
929      pack('H*', sha1($data))
930      .hash_hmac('md5', $data, $conf['secret_key'],true)
931      );
[1622]932    return $key;
933  }
934  return false;
935}
936
[1068]937/*
938 * Performs all required actions for user login
939 * @param int user_id
940 * @param bool remember_me
941 * @return void
942*/
943function log_user($user_id, $remember_me)
944{
[1511]945  global $conf, $user;
[1493]946
[1641]947  if ($remember_me and $conf['authorize_remembering'])
[1068]948  {
[2409]949    $now = time();
950    $key = calculate_auto_login_key($user_id, $now, $username);
[1622]951    if ($key!==false)
[1493]952    {
[2409]953      $cookie = $user_id.'-'.$now.'-'.$key;
[2757]954      if (version_compare(PHP_VERSION, '5.2', '>=') )
955      {
956        setcookie($conf['remember_me_name'],
[2409]957            $cookie,
[2029]958            time()+$conf['remember_me_length'],
[2757]959            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure'),
960            ini_get('session.cookie_httponly')
[2029]961          );
[2757]962      }
963      else
964      {
965        setcookie($conf['remember_me_name'],
966            $cookie,
967            time()+$conf['remember_me_length'],
968            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure')
969          );
970      }
[2029]971    }
[1068]972  }
[1568]973  else
974  { // make sure we clean any remember me ...
[2757]975    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
[1568]976  }
977  if ( session_id()!="" )
[1622]978  { // we regenerate the session for security reasons
979    // see http://www.acros.si/papers/session_fixation.pdf
[1568]980    session_regenerate_id();
981  }
982  else
983  {
984    session_start();
985  }
[1622]986  $_SESSION['pwg_uid'] = (int)$user_id;
[1511]987
988  $user['id'] = $_SESSION['pwg_uid'];
[1068]989}
990
[1070]991/*
[1511]992 * Performs auto-connexion when cookie remember_me exists
[1568]993 * @return true/false
[1511]994*/
[1567]995function auto_login() {
[1511]996  global $conf;
997
[1568]998  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
999  {
[2409]1000    $cookie = explode('-', stripslashes($_COOKIE[$conf['remember_me_name']]));
[2411]1001    if ( count($cookie)===3
[2409]1002        and is_numeric(@$cookie[0]) /*user id*/
1003        and is_numeric(@$cookie[1]) /*time*/
1004        and time()-$conf['remember_me_length']<=@$cookie[1]
1005        and time()>=@$cookie[1] /*cookie generated in the past*/ )
[1568]1006    {
[2409]1007      $key = calculate_auto_login_key( $cookie[0], $cookie[1], $username );
1008      if ($key!==false and $key===$cookie[2])
[1622]1009      {
[2409]1010        log_user($cookie[0], true);
[1744]1011        trigger_action('login_success', $username);
[1622]1012        return true;
1013      }
[1568]1014    }
[2757]1015    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
[1511]1016  }
[1568]1017  return false;
[1511]1018}
1019
[1744]1020/**
1021 * Tries to login a user given username and password (must be MySql escaped)
1022 * return true on success
1023 */
1024function try_log_user($username, $password, $remember_me)
1025{
1026  global $conf;
1027  // retrieving the encrypted password of the login submitted
1028  $query = '
1029SELECT '.$conf['user_fields']['id'].' AS id,
1030       '.$conf['user_fields']['password'].' AS password
1031  FROM '.USERS_TABLE.'
1032  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
1033;';
1034  $row = mysql_fetch_assoc(pwg_query($query));
1035  if ($row['password'] == $conf['pass_convert']($password))
1036  {
1037    log_user($row['id'], $remember_me);
1038    trigger_action('login_success', $username);
1039    return true;
1040  }
1041  trigger_action('login_failure', $username);
1042  return false;
1043}
1044
[2757]1045/** Performs all the cleanup on user logout */
1046function logout_user()
1047{
1048  global $conf;
1049  $_SESSION = array();
1050  session_unset();
1051  session_destroy();
1052  setcookie(session_name(),'',0,
1053      ini_get('session.cookie_path'),
1054      ini_get('session.cookie_domain')
1055    );
1056  setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
1057}
1058
[1511]1059/*
[2029]1060 * Return user status used in this library
1061 * @return string
[1070]1062*/
[2029]1063function get_user_status($user_status)
[1070]1064{
[2029]1065  global $user;
[1072]1066
[1854]1067  if (empty($user_status))
[1075]1068  {
[1854]1069    if (isset($user['status']))
1070    {
1071      $user_status = $user['status'];
1072    }
1073    else
1074    {
1075      // swicth to default value
1076      $user_status = '';
1077    }
[1075]1078  }
[2029]1079  return $user_status;
1080}
[1075]1081
[2029]1082/*
[2325]1083 * Return access_type definition of user
[2029]1084 * Test does with user status
1085 * @return bool
1086*/
1087function get_access_type_status($user_status='')
1088{
1089  global $conf;
1090
1091  switch (get_user_status($user_status))
[1072]1092  {
[1075]1093    case 'guest':
[1851]1094    {
[1854]1095      $access_type_status =
[2325]1096        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_FREE);
[1851]1097      break;
1098    }
[1075]1099    case 'generic':
[1072]1100    {
[1075]1101      $access_type_status = ACCESS_GUEST;
1102      break;
[1072]1103    }
[1075]1104    case 'normal':
1105    {
1106      $access_type_status = ACCESS_CLASSIC;
1107      break;
1108    }
1109    case 'admin':
1110    {
1111      $access_type_status = ACCESS_ADMINISTRATOR;
1112      break;
1113    }
1114    case 'webmaster':
1115    {
1116      $access_type_status = ACCESS_WEBMASTER;
1117      break;
1118    }
[2221]1119    default:
[1854]1120    {
[2325]1121      $access_type_status = ACCESS_FREE;
[2221]1122      break;
[1854]1123    }
[1072]1124  }
1125
[1085]1126  return $access_type_status;
[1070]1127}
1128
[1072]1129/*
[1085]1130 * Return if user have access to access_type definition
1131 * Test does with user status
1132 * @return bool
1133*/
[1851]1134function is_autorize_status($access_type, $user_status = '')
[1085]1135{
[1851]1136  return (get_access_type_status($user_status) >= $access_type);
[1085]1137}
1138
1139/*
1140 * Check if user have access to access_type definition
[1072]1141 * Stop action if there are not access
1142 * Test does with user status
1143 * @return none
1144*/
[1851]1145function check_status($access_type, $user_status = '')
[1072]1146{
[1851]1147  if (!is_autorize_status($access_type, $user_status))
[1072]1148  {
[1113]1149    access_denied();
[1072]1150  }
1151}
1152
1153/*
[2163]1154 * Return if user is generic
[1072]1155 * @return bool
1156*/
[2163]1157 function is_generic($user_status = '')
[2029]1158{
[2163]1159  return get_user_status($user_status) == 'generic';
[2029]1160}
1161
1162/*
[2163]1163 * Return if user is only a guest
[2161]1164 * @return bool
1165*/
[2163]1166 function is_a_guest($user_status = '')
[2161]1167{
[2163]1168  return get_user_status($user_status) == 'guest';
[2161]1169}
[2163]1170
[2161]1171/*
[2029]1172 * Return if user is, at least, a classic user
1173 * @return bool
1174*/
1175 function is_classic_user($user_status = '')
1176{
1177  return is_autorize_status(ACCESS_CLASSIC, $user_status);
1178}
1179
1180/*
1181 * Return if user is, at least, an administrator
1182 * @return bool
1183*/
[1851]1184 function is_admin($user_status = '')
[1072]1185{
[1851]1186  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
[1072]1187}
1188
[1085]1189/*
1190 * Return if current user is an adviser
1191 * @return bool
1192*/
1193function is_adviser()
1194{
1195  global $user;
1196
1197  return ($user['adviser'] == 'true');
1198}
[1458]1199
1200/*
[3445]1201 * Return if current user can edit/delete a comment
1202 * @param action edit/delete
1203 * @return bool
1204 */
[3450]1205function can_manage_comment($action, $comment_author_id) 
[3445]1206{
1207  if (!in_array($action, array('delete','edit'))) {
1208    return false;
1209  }
1210  return (is_admin() || 
[3450]1211          (($GLOBALS['user']['id'] == $comment_author_id) 
1212           && !is_a_guest()
[3445]1213           && $GLOBALS['conf'][sprintf('user_can_%s_comment', $action)]));
1214}
1215
1216/*
[1458]1217 * Return mail address as display text
1218 * @return string
1219*/
1220function get_email_address_as_display_text($email_address)
1221{
1222  global $conf;
1223
[1462]1224  if (!isset($email_address) or (trim($email_address) == ''))
[1458]1225  {
[1462]1226    return '';
[1458]1227  }
1228  else
1229  {
[2237]1230    if (defined('IN_ADMIN') and is_adviser())
[1462]1231    {
1232      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
1233    }
1234    else
1235    {
1236      return $email_address;
1237    }
[1458]1238  }
1239}
1240
[1677]1241/*
[1817]1242 * Compute sql where condition with restrict and filter data. "FandF" means
1243 * Forbidden and Filters.
[1677]1244 *
[1817]1245 * @param array condition_fields: read function body
1246 * @param string prefix_condition: prefixes sql if condition is not empty
1247 * @param boolean force_one_condition: use at least "1 = 1"
[1677]1248 *
1249 * @return string sql where/conditions
1250 */
[1817]1251function get_sql_condition_FandF(
1252  $condition_fields,
1253  $prefix_condition = null,
1254  $force_one_condition = false
1255  )
[1677]1256{
1257  global $user, $filter;
1258
1259  $sql_list = array();
1260
1261  foreach ($condition_fields as $condition => $field_name)
1262  {
1263    switch($condition)
1264    {
1265      case 'forbidden_categories':
[1817]1266      {
[1677]1267        if (!empty($user['forbidden_categories']))
1268        {
[1817]1269          $sql_list[] =
1270            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
[1677]1271        }
1272        break;
[1817]1273      }
[1677]1274      case 'visible_categories':
[1817]1275      {
[1677]1276        if (!empty($filter['visible_categories']))
1277        {
[1817]1278          $sql_list[] =
1279            $field_name.' IN ('.$filter['visible_categories'].')';
[1677]1280        }
1281        break;
[1817]1282      }
[1677]1283      case 'visible_images':
1284        if (!empty($filter['visible_images']))
1285        {
[1817]1286          $sql_list[] =
1287            $field_name.' IN ('.$filter['visible_images'].')';
[1677]1288        }
[2084]1289        // note there is no break - visible include forbidden
1290      case 'forbidden_images':
1291        if (
1292            !empty($user['image_access_list'])
1293            or $user['image_access_type']!='NOT IN'
1294            )
1295        {
1296          $table_prefix=null;
1297          if ($field_name=='id')
1298          {
1299            $table_prefix = '';
1300          }
1301          elseif ($field_name=='i.id')
1302          {
1303            $table_prefix = 'i.';
1304          }
1305          if ( isset($table_prefix) )
1306          {
1307            $sql_list[]=$table_prefix.'level<='.$user['level'];
1308          }
1309          else
1310          {
1311            $sql_list[]=$field_name.' '.$user['image_access_type']
1312                .' ('.$user['image_access_list'].')';
1313          }
1314        }
[1677]1315        break;
1316      default:
[1817]1317      {
[1677]1318        die('Unknow condition');
1319        break;
[1817]1320      }
[1677]1321    }
1322  }
1323
1324  if (count($sql_list) > 0)
1325  {
1326    $sql = '('.implode(' AND ', $sql_list).')';
1327  }
1328  else
1329  {
[2824]1330    $sql = $force_one_condition ? '1 = 1' : '';
[1677]1331  }
1332
1333  if (isset($prefix_condition) and !empty($sql))
1334  {
1335    $sql = $prefix_condition.' '.$sql;
1336  }
1337
1338  return $sql;
1339}
1340
[1860]1341?>
Note: See TracBrowser for help on using the repository browser.