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

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