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

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