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

Last change on this file since 5060 was 5060, checked in by Eric, 14 years ago

Renaming $confno_case_sensitive_for_login to $confinsensitive_case_logon according with VDigital's proposal

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