source: tags/release-1_7_1/include/functions_user.inc.php @ 14518

Last change on this file since 14518 was 2177, checked in by rub, 16 years ago

Resolved issue 0000784: Mail notification disabled on register user

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