source: branches/1.7/include/functions_user.inc.php @ 4636

Last change on this file since 4636 was 2271, checked in by patdenice, 16 years ago

Trigger correction in functions_user.inc.php

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