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

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

Fix bad default value for language on table user_info
Improve mail send (Undisclosed-recipients, switch language, ...)
Improve send an email to group members (Use Bcc, template, multi-language, ...) (But need more improvements)

  • Property svn:eol-style set to LF
  • 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-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | file          : $Id: functions_user.inc.php 1904 2007-03-13 23:01:16Z rub $
8// | last update   : $Date: 2007-03-13 23:01:16 +0000 (Tue, 13 Mar 2007) $
9// | last modifier : $Author: rub $
10// | revision      : $Revision: 1904 $
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  if ( $user['id'] == $conf['guest_id'])
151  {
152    $user['is_the_guest']=true;
153    $user['template'] = $conf['default_template'];
154    $user['nb_image_line'] = $conf['nb_image_line'];
155    $user['nb_line_page'] = $conf['nb_line_page'];
156    $user['language'] = $conf['default_language'];
157    $user['maxwidth'] = $conf['default_maxwidth'];
158    $user['maxheight'] = $conf['default_maxheight'];
159    $user['recent_period'] = $conf['recent_period'];
160    $user['expand'] = $conf['auto_expand'];
161    $user['show_nb_comments'] = $conf['show_nb_comments'];
162    $user['show_nb_hits'] = $conf['show_nb_hits'];
163    $user['enabled_high'] = $conf['newuser_default_enabled_high'];
164  }
165  else
166  {
167    $user['is_the_guest']=false;
168  }
169  // calculation of the number of picture to display per page
170  $user['nb_image_page'] = $user['nb_image_line'] * $user['nb_line_page'];
171
172  // include template/theme configuration
173  if (defined('IN_ADMIN') and IN_ADMIN)
174  {
175    list($user['template'], $user['theme']) =
176      explode
177      (
178        '/',
179        isset($conf['default_admin_layout']) ? $conf['default_admin_layout']
180                                             : $user['template']
181      );
182    // TODO : replace $conf['admin_layout'] by $user['admin_layout']
183  }
184  else
185  {
186    list($user['template'], $user['theme']) = explode('/', $user['template']);
187  }
188
189  return $user;
190}
191
192/**
193 * find informations related to the user identifier
194 *
195 * @param int user identifier
196 * @param boolean use_cache
197 * @param array
198 */
199function getuserdata($user_id, $use_cache)
200{
201  global $conf;
202
203  $userdata = array();
204
205  $query = '
206SELECT ';
207  $is_first = true;
208  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
209  {
210    if ($is_first)
211    {
212      $is_first = false;
213    }
214    else
215    {
216      $query.= '
217     , ';
218    }
219    $query.= $dbfield.' AS '.$pwgfield;
220  }
221  $query.= '
222  FROM '.USERS_TABLE.'
223  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'
224;';
225
226  $row = mysql_fetch_array(pwg_query($query));
227
228  while (true)
229  {
230    $query = '
231SELECT ui.*, uc.*
232  FROM '.USER_INFOS_TABLE.' AS ui LEFT JOIN '.USER_CACHE_TABLE.' AS uc
233    ON ui.user_id = uc.user_id
234  WHERE ui.user_id = \''.$user_id.'\'
235;';
236    $result = pwg_query($query);
237    if (mysql_num_rows($result) > 0)
238    {
239      break;
240    }
241    else
242    {
243      create_user_infos($user_id);
244    }
245  }
246
247  $row = array_merge($row, mysql_fetch_array($result));
248
249  foreach ($row as $key => $value)
250  {
251    if (!is_numeric($key))
252    {
253      // If the field is true or false, the variable is transformed into a
254      // boolean value.
255      if ($value == 'true' or $value == 'false')
256      {
257        $userdata[$key] = get_boolean($value);
258      }
259      else
260      {
261        $userdata[$key] = $value;
262      }
263    }
264  }
265
266  if ($use_cache)
267  {
268    if (!isset($userdata['need_update'])
269        or !is_bool($userdata['need_update'])
270        or $userdata['need_update'] == true)
271    {
272      $userdata['forbidden_categories'] =
273        calculate_permissions($userdata['id'], $userdata['status']);
274
275      update_user_cache_categories($userdata);
276
277      // Set need update are done
278      $userdata['need_update'] = false;
279
280      // Indicate update done
281      $userdata['need_update_done'] = true;
282
283      $query = '
284SELECT COUNT(DISTINCT(image_id)) as total
285  FROM '.IMAGE_CATEGORY_TABLE.'
286  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
287;';
288      list($userdata['nb_total_images']) = mysql_fetch_array(pwg_query($query));
289
290      // update user cache
291      $query = '
292DELETE FROM '.USER_CACHE_TABLE.'
293  WHERE user_id = '.$userdata['id'].'
294;';
295      pwg_query($query);
296
297      $query = '
298INSERT INTO '.USER_CACHE_TABLE.'
299  (user_id, need_update, forbidden_categories, nb_total_images)
300  VALUES
301  ('.$userdata['id'].',\''.boolean_to_string($userdata['need_update']).'\',\''
302  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].')
303;';
304      pwg_query($query);
305    }
306    else
307    {
308      // Indicate update not done
309      $userdata['need_update_done'] = false;
310    }
311  }
312
313  return $userdata;
314}
315
316/*
317 * deletes favorites of the current user if he's not allowed to see them
318 *
319 * @return void
320 */
321function check_user_favorites()
322{
323  global $user;
324
325  if ($user['forbidden_categories'] == '')
326  {
327    return;
328  }
329
330  // $filter['visible_categories'] and $filter['visible_images']
331  // must be not used because filter <> restriction
332  // retrieving images allowed : belonging to at least one authorized
333  // category
334  $query = '
335SELECT DISTINCT f.image_id
336  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
337    ON f.image_id = ic.image_id
338  WHERE f.user_id = '.$user['id'].'
339'.get_sql_condition_FandF
340  (
341    array
342      (
343        'forbidden_categories' => 'ic.category_id',
344      ),
345    'AND'
346  ).'
347;';
348  $result = pwg_query($query);
349  $authorizeds = array();
350  while ($row = mysql_fetch_array($result))
351  {
352    array_push($authorizeds, $row['image_id']);
353  }
354
355  $query = '
356SELECT image_id
357  FROM '.FAVORITES_TABLE.'
358  WHERE user_id = '.$user['id'].'
359;';
360  $result = pwg_query($query);
361  $favorites = array();
362  while ($row = mysql_fetch_array($result))
363  {
364    array_push($favorites, $row['image_id']);
365  }
366
367  $to_deletes = array_diff($favorites, $authorizeds);
368
369  if (count($to_deletes) > 0)
370  {
371    $query = '
372DELETE FROM '.FAVORITES_TABLE.'
373  WHERE image_id IN ('.implode(',', $to_deletes).')
374    AND user_id = '.$user['id'].'
375;';
376    pwg_query($query);
377  }
378}
379
380/**
381 * calculates the list of forbidden categories for a given user
382 *
383 * Calculation is based on private categories minus categories authorized to
384 * the groups the user belongs to minus the categories directly authorized
385 * to the user. The list contains at least -1 to be compliant with queries
386 * such as "WHERE category_id NOT IN ($forbidden_categories)"
387 *
388 * @param int user_id
389 * @param string user_status
390 * @return string forbidden_categories
391 */
392function calculate_permissions($user_id, $user_status)
393{
394  $private_array = array();
395  $authorized_array = array();
396
397  $query = '
398SELECT id
399  FROM '.CATEGORIES_TABLE.'
400  WHERE status = \'private\'
401;';
402  $result = pwg_query($query);
403  while ($row = mysql_fetch_array($result))
404  {
405    array_push($private_array, $row['id']);
406  }
407
408  // retrieve category ids directly authorized to the user
409  $query = '
410SELECT cat_id
411  FROM '.USER_ACCESS_TABLE.'
412  WHERE user_id = '.$user_id.'
413;';
414  $authorized_array = array_from_query($query, 'cat_id');
415
416  // retrieve category ids authorized to the groups the user belongs to
417  $query = '
418SELECT cat_id
419  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
420    ON ug.group_id = ga.group_id
421  WHERE ug.user_id = '.$user_id.'
422;';
423  $authorized_array =
424    array_merge(
425      $authorized_array,
426      array_from_query($query, 'cat_id')
427      );
428
429  // uniquify ids : some private categories might be authorized for the
430  // groups and for the user
431  $authorized_array = array_unique($authorized_array);
432
433  // only unauthorized private categories are forbidden
434  $forbidden_array = array_diff($private_array, $authorized_array);
435
436  // if user is not an admin, locked categories are forbidden
437  if (!is_admin($user_status))
438  {
439    $query = '
440SELECT id
441  FROM '.CATEGORIES_TABLE.'
442  WHERE visible = \'false\'
443;';
444    $result = pwg_query($query);
445    while ($row = mysql_fetch_array($result))
446    {
447      array_push($forbidden_array, $row['id']);
448    }
449    $forbidden_array = array_unique($forbidden_array);
450  }
451
452  if ( empty($forbidden_array) )
453  {// at least, the list contains 0 value. This category does not exists so
454   // where clauses such as "WHERE category_id NOT IN(0)" will always be
455   // true.
456    array_push($forbidden_array, 0);
457  }
458
459  return implode(',', $forbidden_array);
460}
461
462/**
463 * compute data of categories branches (one branch only)
464 */
465function compute_branch_cat_data(&$cats, &$list_cat_id, &$level, &$ref_level)
466{
467  $date = '';
468  $count_images = 0;
469  $count_categories = 0;
470  do
471  {
472    $cat_id = array_pop($list_cat_id);
473    if (!is_null($cat_id))
474    {
475      // Count images and categories
476      $cats[$cat_id]['count_images'] += $count_images;
477      $cats[$cat_id]['count_categories'] += $count_categories;
478      $count_images = $cats[$cat_id]['count_images'];
479      $count_categories = $cats[$cat_id]['count_categories'] + 1;
480
481      if ((empty($cats[$cat_id]['max_date_last'])) or ($cats[$cat_id]['max_date_last'] < $date))
482      {
483        $cats[$cat_id]['max_date_last'] = $date;
484      }
485      else
486      {
487        $date = $cats[$cat_id]['max_date_last'];
488      }
489      $ref_level = substr_count($cats[$cat_id]['global_rank'], '.') + 1;
490    }
491    else
492    {
493      $ref_level = 0;
494    }
495  } while ($level <= $ref_level);
496
497  // Last cat updating must be added to list for next branch
498  if ($ref_level <> 0)
499  {
500    array_push($list_cat_id, $cat_id);
501  }
502}
503
504/**
505 * compute data of categories branches
506 */
507function compute_categories_data(&$cats)
508{
509  $ref_level = 0;
510  $level = 0;
511  $list_cat_id = array();
512
513  foreach ($cats as $id => $category)
514  {
515    // Compute
516    $level = substr_count($category['global_rank'], '.') + 1;
517    if ($level > $ref_level)
518    {
519      array_push($list_cat_id, $id);
520    }
521    else
522    {
523      compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
524      array_push($list_cat_id, $id);
525    }
526    $ref_level = $level;
527  }
528
529  $level = 1;
530  compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
531}
532
533/**
534 * get computed array of categories
535 *
536 * @param array userdata
537 * @param int filter_days number of recent days to filter on or null
538 * @return array
539 */
540function get_computed_categories($userdata, $filter_days=null)
541{
542  $group_by = '';
543
544  $query = 'SELECT c.id cat_id, global_rank';
545  if ( !isset($filter_days) )
546  {
547    $query .= ',
548    date_last cat_date_last,
549    nb_images cat_nb_images
550  FROM '.CATEGORIES_TABLE.' as c';
551  }
552  else
553  {
554    // Count by date_available to avoid count null
555    $query .= ',
556    MAX(date_available) cat_date_last,
557    COUNT(date_available) cat_nb_images
558  FROM '.CATEGORIES_TABLE.' as c
559    LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
560    LEFT JOIN '.IMAGES_TABLE.' AS i
561      ON ic.image_id = i.id AND
562          i.date_available > SUBDATE(CURRENT_DATE,INTERVAL '.$filter_days.' DAY)';
563    $group_by = 'c.id';
564  }
565
566  if ( !empty($userdata['forbidden_categories']) )
567  {
568    $query.= '
569  WHERE c.id NOT IN ('.$userdata['forbidden_categories'].')';
570  }
571
572  if ( !empty($group_by) )
573  {
574    $query.= '
575  GROUP BY '.$group_by;
576  }
577
578  $result = pwg_query($query);
579
580  $cats = array();
581  while ($row = mysql_fetch_assoc($result))
582  {
583    $row['user_id'] = $userdata['id'];
584    $row['count_categories'] = 0;
585    $row['count_images'] = $row['cat_nb_images'];
586    $row['max_date_last'] = $row['cat_date_last'];
587
588    $cats += array($row['cat_id'] => $row);
589  }
590  usort($cats, 'global_rank_compare');
591
592  compute_categories_data($cats);
593
594  if ( isset($filter_days) )
595  {
596    $cat_tmp = $cats;
597    $cats = array();
598
599    foreach ($cat_tmp as $category)
600    {
601      if (!empty($category['max_date_last']))
602      {
603        // Re-init counters
604        $category['count_categories'] = 0;
605        $category['count_images'] = $category['cat_nb_images'];
606        // next line for update_cats_with_filtered_data
607        $category['nb_images'] = $category['cat_nb_images'];
608        // Keep category
609        $cats[$category['cat_id']] = $category;
610      }
611    }
612    // Compute a second time
613    compute_categories_data($cats);
614  }
615  return $cats;
616}
617
618/**
619 * update data of user_cache_categories
620 *
621 * @param array userdata
622 * @return null
623 */
624function update_user_cache_categories($userdata)
625{
626  // delete user cache
627  $query = '
628DELETE FROM '.USER_CACHE_CATEGORIES_TABLE.'
629  WHERE user_id = '.$userdata['id'].'
630;';
631  pwg_query($query);
632
633  $cats = get_computed_categories($userdata, null);
634
635  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
636  mass_inserts
637  (
638    USER_CACHE_CATEGORIES_TABLE,
639    array
640    (
641      'user_id', 'cat_id',
642      'max_date_last', 'count_images', 'count_categories'
643    ),
644    $cats
645  );
646}
647
648/**
649 * returns the username corresponding to the given user identifier if exists
650 *
651 * @param int user_id
652 * @return mixed
653 */
654function get_username($user_id)
655{
656  global $conf;
657
658  $query = '
659SELECT '.$conf['user_fields']['username'].'
660  FROM '.USERS_TABLE.'
661  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
662;';
663  $result = pwg_query($query);
664  if (mysql_num_rows($result) > 0)
665  {
666    list($username) = mysql_fetch_row($result);
667  }
668  else
669  {
670    return false;
671  }
672
673  return $username;
674}
675
676/**
677 * returns user identifier thanks to his name, false if not found
678 *
679 * @param string username
680 * @param int user identifier
681 */
682function get_userid($username)
683{
684  global $conf;
685
686  $username = mysql_escape_string($username);
687
688  $query = '
689SELECT '.$conf['user_fields']['id'].'
690  FROM '.USERS_TABLE.'
691  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
692;';
693  $result = pwg_query($query);
694
695  if (mysql_num_rows($result) == 0)
696  {
697    return false;
698  }
699  else
700  {
701    list($user_id) = mysql_fetch_row($result);
702    return $user_id;
703  }
704}
705
706/**
707 * search an available feed_id
708 *
709 * @return string feed identifier
710 */
711function find_available_feed_id()
712{
713  while (true)
714  {
715    $key = generate_key(50);
716    $query = '
717SELECT COUNT(*)
718  FROM '.USER_FEED_TABLE.'
719  WHERE id = \''.$key.'\'
720;';
721    list($count) = mysql_fetch_row(pwg_query($query));
722    if (0 == $count)
723    {
724      return $key;
725    }
726  }
727}
728
729/**
730 * add user informations based on default values
731 *
732 * @param int user_id
733 */
734function create_user_infos($user_id)
735{
736  global $conf;
737
738  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
739
740  if ($user_id == $conf['webmaster_id'])
741  {
742    $status = 'webmaster';
743  }
744  else if ($user_id == $conf['guest_id'])
745  {
746    $status = 'guest';
747  }
748  else
749  {
750    $status = 'normal';
751  }
752
753  $insert =
754    array(
755      'user_id' => $user_id,
756      'status' => $status,
757      'template' => $conf['default_template'],
758      'nb_image_line' => $conf['nb_image_line'],
759      'nb_line_page' => $conf['nb_line_page'],
760      'language' => $conf['default_language'],
761      'recent_period' => $conf['recent_period'],
762      'expand' => boolean_to_string($conf['auto_expand']),
763      'show_nb_comments' => boolean_to_string($conf['show_nb_comments']),
764      'show_nb_hits' => boolean_to_string($conf['show_nb_hits']),
765      'maxwidth' => $conf['default_maxwidth'],
766      'maxheight' => $conf['default_maxheight'],
767      'registration_date' => $dbnow,
768      'enabled_high' =>
769        boolean_to_string($conf['newuser_default_enabled_high']),
770      );
771
772  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
773  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
774}
775
776/**
777 * returns the groupname corresponding to the given group identifier if
778 * exists
779 *
780 * @param int group_id
781 * @return mixed
782 */
783function get_groupname($group_id)
784{
785  $query = '
786SELECT name
787  FROM '.GROUPS_TABLE.'
788  WHERE id = '.intval($group_id).'
789;';
790  $result = pwg_query($query);
791  if (mysql_num_rows($result) > 0)
792  {
793    list($groupname) = mysql_fetch_row($result);
794  }
795  else
796  {
797    return false;
798  }
799
800  return $groupname;
801}
802
803/**
804 * return the file path of the given language filename, depending on the
805 * availability of the file
806 *
807 * in descending order of preference:
808 *   param language, user language, default language
809 * PhpWebGallery default language.
810 *
811 * @param string filename
812 * @param string dirname
813 * @param string language
814 * @return string filepath
815 */
816function get_language_filepath($filename, $dirname = '', $language = '')
817{
818  global $user, $conf;
819
820  if (empty($dirname))
821  {
822    $dirname = PHPWG_ROOT_PATH;
823  }
824  $dirname .= 'language'.'/';
825
826  $directories = array();
827  if ( !empty($language) )
828  {
829    $directories[] = $dirname.$language;
830  }
831
832  {
833    $directories[] = $dirname.$user['language'];
834  }
835  $directories[] = $dirname.$conf['default_language'];
836  $directories[] = $dirname.PHPWG_DEFAULT_LANGUAGE;
837
838  foreach ($directories as $directory)
839  {
840    $filepath = $directory.'/'.$filename;
841
842    if (file_exists($filepath))
843    {
844      return $filepath;
845    }
846  }
847
848  return false;
849}
850
851/**
852 * returns the auto login key or false on error
853 * @param int user_id
854 * @param string [out] username
855*/
856function calculate_auto_login_key($user_id, &$username)
857{
858  global $conf;
859  $query = '
860SELECT '.$conf['user_fields']['username'].' AS username
861  , '.$conf['user_fields']['password'].' AS password
862FROM '.USERS_TABLE.'
863WHERE '.$conf['user_fields']['id'].' = '.$user_id;
864  $result = pwg_query($query);
865  if (mysql_num_rows($result) > 0)
866  {
867    $row = mysql_fetch_assoc($result);
868    $username = $row['username'];
869    $data = $row['username'].$row['password'];
870    $key = base64_encode(
871      pack('H*', sha1($data))
872      .hash_hmac('md5', $data, $conf['secret_key'],true)
873      );
874    return $key;
875  }
876  return false;
877}
878
879/*
880 * Performs all required actions for user login
881 * @param int user_id
882 * @param bool remember_me
883 * @return void
884*/
885function log_user($user_id, $remember_me)
886{
887  global $conf, $user;
888
889  if ($remember_me and $conf['authorize_remembering'])
890  {
891    $key = calculate_auto_login_key($user_id, $username);
892    if ($key!==false)
893    {
894      $cookie = array('id' => (int)$user_id, 'key' => $key);
895      setcookie($conf['remember_me_name'],
896                serialize($cookie),
897                time()+$conf['remember_me_length'],
898                cookie_path()
899              );
900        }
901  }
902  else
903  { // make sure we clean any remember me ...
904    setcookie($conf['remember_me_name'], '', 0, cookie_path());
905  }
906  if ( session_id()!="" )
907  { // we regenerate the session for security reasons
908    // see http://www.acros.si/papers/session_fixation.pdf
909    session_regenerate_id();
910  }
911  else
912  {
913    session_start();
914  }
915  $_SESSION['pwg_uid'] = (int)$user_id;
916
917  $user['id'] = $_SESSION['pwg_uid'];
918}
919
920/*
921 * Performs auto-connexion when cookie remember_me exists
922 * @return true/false
923*/
924function auto_login() {
925  global $conf;
926
927  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
928  {
929    $cookie = unserialize(stripslashes($_COOKIE[$conf['remember_me_name']]));
930    if ($cookie!==false and is_numeric(@$cookie['id']) )
931    {
932      $key = calculate_auto_login_key( $cookie['id'], $username );
933      if ($key!==false and $key===$cookie['key'])
934      {
935        log_user($cookie['id'], true);
936        trigger_action('login_success', $username);
937        return true;
938      }
939    }
940    setcookie($conf['remember_me_name'], '', 0, cookie_path());
941  }
942  return false;
943}
944
945/**
946 * Tries to login a user given username and password (must be MySql escaped)
947 * return true on success
948 */
949function try_log_user($username, $password, $remember_me)
950{
951  global $conf;
952  // retrieving the encrypted password of the login submitted
953  $query = '
954SELECT '.$conf['user_fields']['id'].' AS id,
955       '.$conf['user_fields']['password'].' AS password
956  FROM '.USERS_TABLE.'
957  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
958;';
959  $row = mysql_fetch_assoc(pwg_query($query));
960  if ($row['password'] == $conf['pass_convert']($password))
961  {
962    log_user($row['id'], $remember_me);
963    trigger_action('login_success', $username);
964    return true;
965  }
966  trigger_action('login_failure', $username);
967  return false;
968}
969
970/*
971 * Return access_type definition of uuser
972 * Test does with user status
973 * @return bool
974*/
975function get_access_type_status($user_status='')
976{
977  global $user, $conf;
978
979  if (empty($user_status))
980  {
981    if (isset($user['status']))
982    {
983      $user_status = $user['status'];
984    }
985    else
986    {
987      // swicth to default value
988      $user_status = '';
989    }
990  }
991
992  switch ($user_status)
993  {
994    case 'guest':
995    {
996      $access_type_status =
997        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_NONE);
998      break;
999    }
1000    case 'generic':
1001    {
1002      $access_type_status = ACCESS_GUEST;
1003      break;
1004    }
1005    case 'normal':
1006    {
1007      $access_type_status = ACCESS_CLASSIC;
1008      break;
1009    }
1010    case 'admin':
1011    {
1012      $access_type_status = ACCESS_ADMINISTRATOR;
1013      break;
1014    }
1015    case 'webmaster':
1016    {
1017      $access_type_status = ACCESS_WEBMASTER;
1018      break;
1019    }
1020    case 'default':
1021    {
1022      $access_type_status = ACCESS_NONE;
1023    }
1024  }
1025
1026  return $access_type_status;
1027}
1028
1029/*
1030 * Return if user have access to access_type definition
1031 * Test does with user status
1032 * @return bool
1033*/
1034function is_autorize_status($access_type, $user_status = '')
1035{
1036  return (get_access_type_status($user_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, $user_status = '')
1046{
1047  if (!is_autorize_status($access_type, $user_status))
1048  {
1049    access_denied();
1050  }
1051}
1052
1053/*
1054 * Return if user is an administrator
1055 * @return bool
1056*/
1057 function is_admin($user_status = '')
1058{
1059  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
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.