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

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

Issue 578
User guest must be real user

Step 1: guest is a real user

On next commit, I finish installation and use of guest of user list and group

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 28.6 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 1926 2007-03-28 19:57:00Z rub $
8// | last update   : $Date: 2007-03-28 19:57:00 +0000 (Wed, 28 Mar 2007) $
9// | last modifier : $Author: rub $
10// | revision      : $Revision: 1926 $
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
731  if (is_array($page['cache_default_user']) and $convert_str)
732  {
733    $default_user = array();
734    foreach ($page['cache_default_user'] as $name => $value)
735    {
736      // If the field is true or false, the variable is transformed into a
737      // boolean value.
738      if ($value == 'true' or $value == 'false')
739      {
740        $default_user[$name] = get_boolean($value);
741      }
742      else
743      {
744        $default_user[$name] = $value;
745      }
746    }
747    return $default_user;
748  }
749  else
750  {
751    return $page['cache_default_user'];
752  }
753}
754
755/*
756 * Returns a default user value
757 *
758 * @param value_name: name of value
759 * @param sos_value: value used if don't exist value
760 */
761function get_default_user_value($value_name, $sos_value)
762{
763  $default_user = get_default_user_info(true);
764  if ($default_user === false or !isset($default_user[$value_name]))
765  {
766    return $sos_value;
767  }
768  else
769  {
770   return $default_user[$value_name];
771  }
772}
773
774/*
775 * Returns the default template value
776 *
777 */
778function get_default_template()
779{
780  return get_default_user_value('template', PHPWG_DEFAULT_TEMPLATE);
781}
782
783/*
784 * Returns the default language value
785 *
786 */
787function get_default_language()
788{
789  return get_default_user_value('language', PHPWG_DEFAULT_LANGUAGE);
790}
791
792/**
793 * add user informations based on default values
794 *
795 * @param int user_id / array of user_if
796 */
797function create_user_infos($arg_id)
798{
799  global $conf;
800
801  if (is_array($arg_id))
802  {
803    $user_ids = $arg_id;
804  }
805  else
806  {
807    $user_ids = array();
808    if (is_integer($arg_id))
809    {
810      $user_ids[] = $arg_id;
811    }
812  }
813
814  if (!empty($user_ids))
815  {
816    $inserts = array();
817    list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
818
819    $default_user = get_default_user_info(false);
820    if ($default_user === false)
821    {
822      // Default on structure are used
823      $default_user = array();
824    }
825   
826
827    foreach ($user_ids as $user_id)
828    {
829      if ($user_id == $conf['webmaster_id'])
830      {
831        $status = 'webmaster';
832      }
833      else if (($user_id == $conf['guest_id']) or 
834               ($user_id == $conf['default_user_id']))
835      {
836        $status = 'guest';
837      }
838      else
839      {
840        $status = 'normal';
841      }
842
843      $insert =
844        array(
845          'user_id' => $user_id,
846          'status' => $status,
847          'registration_date' => $dbnow
848          );
849
850      array_push($inserts, $insert);
851      }
852
853    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
854    mass_inserts(USER_INFOS_TABLE, array_keys($inserts[0]), $inserts);
855
856  }
857}
858
859/**
860 * returns the groupname corresponding to the given group identifier if
861 * exists
862 *
863 * @param int group_id
864 * @return mixed
865 */
866function get_groupname($group_id)
867{
868  $query = '
869SELECT name
870  FROM '.GROUPS_TABLE.'
871  WHERE id = '.intval($group_id).'
872;';
873  $result = pwg_query($query);
874  if (mysql_num_rows($result) > 0)
875  {
876    list($groupname) = mysql_fetch_row($result);
877  }
878  else
879  {
880    return false;
881  }
882
883  return $groupname;
884}
885
886/**
887 * return the file path of the given language filename, depending on the
888 * availability of the file
889 *
890 * in descending order of preference:
891 *   param language, user language, default language
892 * PhpWebGallery default language.
893 *
894 * @param string filename
895 * @param string dirname
896 * @param string language
897 * @return string filepath
898 */
899function get_language_filepath($filename, $dirname = '', $language = '')
900{
901  global $user, $conf;
902
903  if (empty($dirname))
904  {
905    $dirname = PHPWG_ROOT_PATH;
906  }
907  $dirname .= 'language'.'/';
908
909  $dir_methods = array();
910
911  if (!empty($language))
912  {
913    $dir_methods[] = 1;
914  }
915
916  $dir_methods[] = 2;
917  $dir_methods[] = 3;
918  $dir_methods[] = 4;
919
920  foreach ($dir_methods as $dir_method)
921  {
922    switch ($dir_method)
923    {
924      case '1':
925      {
926        $directory = $dirname.$language;
927        break;
928      }
929      case '2':
930      {
931        $directory = $dirname.$user['language'];
932        break;
933      }
934      case '3':
935      {
936        $directory = $dirname.get_default_language();
937        break;
938      }
939      case '4':
940      default:
941      {
942        $directory = $dirname.PHPWG_DEFAULT_LANGUAGE;
943        break;
944      }
945      {
946        $directory = '.';
947      }
948    }
949
950    $filepath = $directory.'/'.$filename;
951
952    if (file_exists($filepath))
953    {
954      return $filepath;
955    }
956  }
957
958  return false;
959}
960
961/**
962 * returns the auto login key or false on error
963 * @param int user_id
964 * @param string [out] username
965*/
966function calculate_auto_login_key($user_id, &$username)
967{
968  global $conf;
969  $query = '
970SELECT '.$conf['user_fields']['username'].' AS username
971  , '.$conf['user_fields']['password'].' AS password
972FROM '.USERS_TABLE.'
973WHERE '.$conf['user_fields']['id'].' = '.$user_id;
974  $result = pwg_query($query);
975  if (mysql_num_rows($result) > 0)
976  {
977    $row = mysql_fetch_assoc($result);
978    $username = $row['username'];
979    $data = $row['username'].$row['password'];
980    $key = base64_encode(
981      pack('H*', sha1($data))
982      .hash_hmac('md5', $data, $conf['secret_key'],true)
983      );
984    return $key;
985  }
986  return false;
987}
988
989/*
990 * Performs all required actions for user login
991 * @param int user_id
992 * @param bool remember_me
993 * @return void
994*/
995function log_user($user_id, $remember_me)
996{
997  global $conf, $user;
998
999  if ($remember_me and $conf['authorize_remembering'])
1000  {
1001    $key = calculate_auto_login_key($user_id, $username);
1002    if ($key!==false)
1003    {
1004      $cookie = array('id' => (int)$user_id, 'key' => $key);
1005      setcookie($conf['remember_me_name'],
1006                serialize($cookie),
1007                time()+$conf['remember_me_length'],
1008                cookie_path()
1009              );
1010        }
1011  }
1012  else
1013  { // make sure we clean any remember me ...
1014    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1015  }
1016  if ( session_id()!="" )
1017  { // we regenerate the session for security reasons
1018    // see http://www.acros.si/papers/session_fixation.pdf
1019    session_regenerate_id();
1020  }
1021  else
1022  {
1023    session_start();
1024  }
1025  $_SESSION['pwg_uid'] = (int)$user_id;
1026
1027  $user['id'] = $_SESSION['pwg_uid'];
1028}
1029
1030/*
1031 * Performs auto-connexion when cookie remember_me exists
1032 * @return true/false
1033*/
1034function auto_login() {
1035  global $conf;
1036
1037  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
1038  {
1039    $cookie = unserialize(stripslashes($_COOKIE[$conf['remember_me_name']]));
1040    if ($cookie!==false and is_numeric(@$cookie['id']) )
1041    {
1042      $key = calculate_auto_login_key( $cookie['id'], $username );
1043      if ($key!==false and $key===$cookie['key'])
1044      {
1045        log_user($cookie['id'], true);
1046        trigger_action('login_success', $username);
1047        return true;
1048      }
1049    }
1050    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1051  }
1052  return false;
1053}
1054
1055/**
1056 * Tries to login a user given username and password (must be MySql escaped)
1057 * return true on success
1058 */
1059function try_log_user($username, $password, $remember_me)
1060{
1061  global $conf;
1062  // retrieving the encrypted password of the login submitted
1063  $query = '
1064SELECT '.$conf['user_fields']['id'].' AS id,
1065       '.$conf['user_fields']['password'].' AS password
1066  FROM '.USERS_TABLE.'
1067  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
1068;';
1069  $row = mysql_fetch_assoc(pwg_query($query));
1070  if ($row['password'] == $conf['pass_convert']($password))
1071  {
1072    log_user($row['id'], $remember_me);
1073    trigger_action('login_success', $username);
1074    return true;
1075  }
1076  trigger_action('login_failure', $username);
1077  return false;
1078}
1079
1080/*
1081 * Return access_type definition of uuser
1082 * Test does with user status
1083 * @return bool
1084*/
1085function get_access_type_status($user_status='')
1086{
1087  global $user, $conf;
1088
1089  if (empty($user_status))
1090  {
1091    if (isset($user['status']))
1092    {
1093      $user_status = $user['status'];
1094    }
1095    else
1096    {
1097      // swicth to default value
1098      $user_status = '';
1099    }
1100  }
1101
1102  switch ($user_status)
1103  {
1104    case 'guest':
1105    {
1106      $access_type_status =
1107        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_NONE);
1108      break;
1109    }
1110    case 'generic':
1111    {
1112      $access_type_status = ACCESS_GUEST;
1113      break;
1114    }
1115    case 'normal':
1116    {
1117      $access_type_status = ACCESS_CLASSIC;
1118      break;
1119    }
1120    case 'admin':
1121    {
1122      $access_type_status = ACCESS_ADMINISTRATOR;
1123      break;
1124    }
1125    case 'webmaster':
1126    {
1127      $access_type_status = ACCESS_WEBMASTER;
1128      break;
1129    }
1130    case 'default':
1131    {
1132      $access_type_status = ACCESS_NONE;
1133    }
1134  }
1135
1136  return $access_type_status;
1137}
1138
1139/*
1140 * Return if user have access to access_type definition
1141 * Test does with user status
1142 * @return bool
1143*/
1144function is_autorize_status($access_type, $user_status = '')
1145{
1146  return (get_access_type_status($user_status) >= $access_type);
1147}
1148
1149/*
1150 * Check if user have access to access_type definition
1151 * Stop action if there are not access
1152 * Test does with user status
1153 * @return none
1154*/
1155function check_status($access_type, $user_status = '')
1156{
1157  if (!is_autorize_status($access_type, $user_status))
1158  {
1159    access_denied();
1160  }
1161}
1162
1163/*
1164 * Return if user is an administrator
1165 * @return bool
1166*/
1167 function is_admin($user_status = '')
1168{
1169  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
1170}
1171
1172/*
1173 * Return if current user is an adviser
1174 * @return bool
1175*/
1176function is_adviser()
1177{
1178  global $user;
1179
1180  return ($user['adviser'] == 'true');
1181}
1182
1183/*
1184 * Return mail address as display text
1185 * @return string
1186*/
1187function get_email_address_as_display_text($email_address)
1188{
1189  global $conf;
1190
1191  if (!isset($email_address) or (trim($email_address) == ''))
1192  {
1193    return '';
1194  }
1195  else
1196  {
1197    if (is_adviser())
1198    {
1199      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
1200    }
1201    else
1202    {
1203      return $email_address;
1204    }
1205  }
1206}
1207
1208/*
1209 * Compute sql where condition with restrict and filter data. "FandF" means
1210 * Forbidden and Filters.
1211 *
1212 * @param array condition_fields: read function body
1213 * @param string prefix_condition: prefixes sql if condition is not empty
1214 * @param boolean force_one_condition: use at least "1 = 1"
1215 *
1216 * @return string sql where/conditions
1217 */
1218function get_sql_condition_FandF(
1219  $condition_fields,
1220  $prefix_condition = null,
1221  $force_one_condition = false
1222  )
1223{
1224  global $user, $filter;
1225
1226  $sql_list = array();
1227
1228  foreach ($condition_fields as $condition => $field_name)
1229  {
1230    switch($condition)
1231    {
1232      case 'forbidden_categories':
1233      {
1234        if (!empty($user['forbidden_categories']))
1235        {
1236          $sql_list[] =
1237            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
1238        }
1239        break;
1240      }
1241      case 'visible_categories':
1242      {
1243        if (!empty($filter['visible_categories']))
1244        {
1245          $sql_list[] =
1246            $field_name.' IN ('.$filter['visible_categories'].')';
1247        }
1248        break;
1249      }
1250      case 'visible_images':
1251      {
1252        if (!empty($filter['visible_images']))
1253        {
1254          $sql_list[] =
1255            $field_name.' IN ('.$filter['visible_images'].')';
1256        }
1257        break;
1258      }
1259      default:
1260      {
1261        die('Unknow condition');
1262        break;
1263      }
1264    }
1265  }
1266
1267  if (count($sql_list) > 0)
1268  {
1269    $sql = '('.implode(' AND ', $sql_list).')';
1270  }
1271  else
1272  {
1273    if ($force_one_condition)
1274    {
1275      $sql = '1 = 1';
1276    }
1277    else
1278    {
1279      $sql = '';
1280    }
1281  }
1282
1283  if (isset($prefix_condition) and !empty($sql))
1284  {
1285    $sql = $prefix_condition.' '.$sql;
1286  }
1287
1288  return $sql;
1289}
1290
1291?>
Note: See TracBrowser for help on using the repository browser.