source: branches/branch-1_7/include/functions_user.inc.php @ 2054

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

Resolved issue 0000717: guest must be guest

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