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

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

Issue 578
User guest must be real user

Step 2: Installation finished, guest must be used on list and group, corrections

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