source: tags/release-1_7_0/include/functions_user.inc.php @ 26010

Last change on this file since 26010 was 1986, checked in by rub, 17 years ago

Issue 0000682: Error on user registration
On register page when the 2 passwords are not the same, an error occurs but user is also created.

=> Just error must be raised.

Merge BSF 1984:1985 into branch-1_7

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