root/trunk/include/functions_user.inc.php @ 2229

Revision 2229, 31.2 KB (checked in by patdenice, 5 years ago)

Merge from revision 2228.
Resolved bugs:
741 and 793: Added user does not appear in listing.
769: show email address in adviser mode when editing user profil.
800: get_absolute_root_url does not work with https protocol.

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