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

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