source: tags/release-1_7_0RC1/include/functions_user.inc.php @ 21250

Last change on this file since 21250 was 1817, checked in by plg, 17 years ago

New: history logs high quality access via action.php. A new column
#history.is_high was added. Filter was added on administration history
detail view.

Modification: function get_sql_condition_FandF was slightly refactored for
presentation improvement.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.1 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2006 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: functions_user.inc.php 1817 2007-02-14 22:53:02Z plg $
9// | last update   : $Date: 2007-02-14 22:53:02 +0000 (Wed, 14 Feb 2007) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 1817 $
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  global $user;
396
397  $private_array = array();
398  $authorized_array = array();
399
400  $query = '
401SELECT id
402  FROM '.CATEGORIES_TABLE.'
403  WHERE status = \'private\'
404;';
405  $result = pwg_query($query);
406  while ($row = mysql_fetch_array($result))
407  {
408    array_push($private_array, $row['id']);
409  }
410
411  // retrieve category ids directly authorized to the user
412  $query = '
413SELECT cat_id
414  FROM '.USER_ACCESS_TABLE.'
415  WHERE user_id = '.$user_id.'
416;';
417  $authorized_array = array_from_query($query, 'cat_id');
418
419  // retrieve category ids authorized to the groups the user belongs to
420  $query = '
421SELECT cat_id
422  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
423    ON ug.group_id = ga.group_id
424  WHERE ug.user_id = '.$user_id.'
425;';
426  $authorized_array =
427    array_merge(
428      $authorized_array,
429      array_from_query($query, 'cat_id')
430      );
431
432  // uniquify ids : some private categories might be authorized for the
433  // groups and for the user
434  $authorized_array = array_unique($authorized_array);
435
436  // only unauthorized private categories are forbidden
437  $forbidden_array = array_diff($private_array, $authorized_array);
438
439  // if user is not an admin, locked categories are forbidden
440  if (!is_admin($user_status))
441  {
442    $query = '
443SELECT id
444  FROM '.CATEGORIES_TABLE.'
445  WHERE visible = \'false\'
446;';
447    $result = pwg_query($query);
448    while ($row = mysql_fetch_array($result))
449    {
450      array_push($forbidden_array, $row['id']);
451    }
452    $forbidden_array = array_unique($forbidden_array);
453  }
454
455  if ( empty($forbidden_array) )
456  {// at least, the list contains 0 value. This category does not exists so
457   // where clauses such as "WHERE category_id NOT IN(0)" will always be
458   // true.
459    array_push($forbidden_array, 0);
460  }
461
462  return implode(',', $forbidden_array);
463}
464
465/**
466 * compute data of categories branches (one branch only)
467 */
468function compute_branch_cat_data(&$cats, &$list_cat_id, &$level, &$ref_level)
469{
470  $date = '';
471  $count_images = 0;
472  $count_categories = 0;
473  do
474  {
475    $cat_id = array_pop($list_cat_id);
476    if (!is_null($cat_id))
477    {
478      // Count images and categories
479      $cats[$cat_id]['count_images'] += $count_images;
480      $cats[$cat_id]['count_categories'] += $count_categories;
481      $count_images = $cats[$cat_id]['count_images'];
482      $count_categories = $cats[$cat_id]['count_categories'] + 1;
483
484      if ((empty($cats[$cat_id]['max_date_last'])) or ($cats[$cat_id]['max_date_last'] < $date))
485      {
486        $cats[$cat_id]['max_date_last'] = $date;
487      }
488      else
489      {
490        $date = $cats[$cat_id]['max_date_last'];
491      }
492      $ref_level = substr_count($cats[$cat_id]['global_rank'], '.') + 1;
493    }
494    else
495    {
496      $ref_level = 0;
497    }
498  } while ($level <= $ref_level);
499
500  // Last cat updating must be added to list for next branch
501  if ($ref_level <> 0)
502  {
503    array_push($list_cat_id, $cat_id);
504  }
505}
506
507/**
508 * compute data of categories branches
509 */
510function compute_categories_data(&$cats)
511{
512  $ref_level = 0;
513  $level = 0;
514  $list_cat_id = array();
515
516  foreach ($cats as $id => $category)
517  {
518    // Compute
519    $level = substr_count($category['global_rank'], '.') + 1;
520    if ($level > $ref_level)
521    {
522      array_push($list_cat_id, $id);
523    }
524    else
525    {
526      compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
527      array_push($list_cat_id, $id);
528    }
529    $ref_level = $level;
530  }
531
532  $level = 1;
533  compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
534}
535
536/**
537 * get computed array of categories
538 *
539 * @param int user_id
540 * @param list user_forbidden_categories
541 * @param bool filter_enabled
542 * @param int recent_period
543 * @return array
544 */
545function get_computed_categories($user_id, $user_forbidden_categories, $filter_enabled, $recent_period = 0)
546{
547  $query = '
548SELECT
549  c.id cat_id,
550  date_last max_date_last,
551  nb_images count_images,
552  global_rank';
553
554  if (!$filter_enabled)
555  {
556    $query.= '
557FROM '.CATEGORIES_TABLE.' as c';
558  }
559  else
560  {
561    // Count by date_available to avoid count null
562    $query.= ',
563  count(date_available) filtered_count_images,
564  max(date_available) max_date_available
565FROM '.CATEGORIES_TABLE.' as c
566    LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
567    LEFT JOIN '.IMAGES_TABLE.' AS i
568      ON ic.image_id = i.id AND
569          i.date_available > SUBDATE(CURRENT_DATE,INTERVAL '.$recent_period.' DAY)';
570  }
571
572  if ($user_forbidden_categories != '')
573  {
574    $query.= '
575WHERE
576  c.id NOT IN ('.$user_forbidden_categories.')';
577  }
578
579  if ($filter_enabled)
580  {
581    $query.= '
582GROUP BY
583  c.id';
584  }
585  $query.= ';';
586
587  $result = pwg_query($query);
588
589  $cats = array();
590  while ($row = mysql_fetch_assoc($result))
591  {
592    $row['user_id'] = $user_id;
593    $row['count_categories'] = 0;
594    if ($filter_enabled)
595    {
596      $row['nb_images'] = $row['filtered_count_images'];
597      $row['count_images'] = $row['filtered_count_images'];
598      $row['max_date_last'] = $row['max_date_available'];
599    }
600    $cats += array($row['cat_id'] => $row);
601  }
602  usort($cats, 'global_rank_compare');
603
604  compute_categories_data($cats);
605
606  if ($filter_enabled)
607  {
608    $cat_tmp = $cats;
609    $cats = array();
610 
611    foreach ($cat_tmp as $category)
612    {
613      if (!empty($category['max_date_last']))
614      {
615        // Re-init counters
616        $category['count_categories'] = 0;
617        $category['nb_images'] = $category['filtered_count_images'];
618        $category['count_images'] = $category['filtered_count_images'];
619        // Keep category
620        $cats[$category['cat_id']] = $category;
621       
622      }
623    }
624    // Compute a second time
625    compute_categories_data($cats);
626  }
627
628  return $cats;
629}
630
631/**
632 * update data of user_cache_categories
633 *
634 * @param int user_id
635 * @param list user_forbidden_categories
636 * @param bool filter_enabled
637 * @return null
638 */
639function update_user_cache_categories($user_id, $user_forbidden_categories)
640{
641  // delete user cache
642  $query = '
643DELETE FROM '.USER_CACHE_CATEGORIES_TABLE.'
644  WHERE user_id = '.$user_id.'
645;';
646  pwg_query($query);
647
648  $cats = get_computed_categories($user_id, $user_forbidden_categories, false);
649
650  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
651  mass_inserts
652  (
653    USER_CACHE_CATEGORIES_TABLE,
654    array
655    (
656      'user_id', 'cat_id',
657      'max_date_last', 'count_images', 'count_categories'
658    ),
659    $cats
660  );
661}
662
663/**
664 * returns the username corresponding to the given user identifier if exists
665 *
666 * @param int user_id
667 * @return mixed
668 */
669function get_username($user_id)
670{
671  global $conf;
672
673  $query = '
674SELECT '.$conf['user_fields']['username'].'
675  FROM '.USERS_TABLE.'
676  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
677;';
678  $result = pwg_query($query);
679  if (mysql_num_rows($result) > 0)
680  {
681    list($username) = mysql_fetch_row($result);
682  }
683  else
684  {
685    return false;
686  }
687
688  return $username;
689}
690
691/**
692 * returns user identifier thanks to his name, false if not found
693 *
694 * @param string username
695 * @param int user identifier
696 */
697function get_userid($username)
698{
699  global $conf;
700
701  $username = mysql_escape_string($username);
702
703  $query = '
704SELECT '.$conf['user_fields']['id'].'
705  FROM '.USERS_TABLE.'
706  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
707;';
708  $result = pwg_query($query);
709
710  if (mysql_num_rows($result) == 0)
711  {
712    return false;
713  }
714  else
715  {
716    list($user_id) = mysql_fetch_row($result);
717    return $user_id;
718  }
719}
720
721/**
722 * search an available feed_id
723 *
724 * @return string feed identifier
725 */
726function find_available_feed_id()
727{
728  while (true)
729  {
730    $key = generate_key(50);
731    $query = '
732SELECT COUNT(*)
733  FROM '.USER_FEED_TABLE.'
734  WHERE id = \''.$key.'\'
735;';
736    list($count) = mysql_fetch_row(pwg_query($query));
737    if (0 == $count)
738    {
739      return $key;
740    }
741  }
742}
743
744/**
745 * add user informations based on default values
746 *
747 * @param int user_id
748 */
749function create_user_infos($user_id)
750{
751  global $conf;
752
753  list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
754
755  if ($user_id == $conf['webmaster_id'])
756  {
757    $status = 'webmaster';
758  }
759  else if ($user_id == $conf['guest_id'])
760  {
761    $status = 'guest';
762  }
763  else
764  {
765    $status = 'normal';
766  }
767
768  $insert =
769    array(
770      'user_id' => $user_id,
771      'status' => $status,
772      'template' => $conf['default_template'],
773      'nb_image_line' => $conf['nb_image_line'],
774      'nb_line_page' => $conf['nb_line_page'],
775      'language' => $conf['default_language'],
776      'recent_period' => $conf['recent_period'],
777      'expand' => boolean_to_string($conf['auto_expand']),
778      'show_nb_comments' => boolean_to_string($conf['show_nb_comments']),
779      'show_nb_hits' => boolean_to_string($conf['show_nb_hits']),
780      'maxwidth' => $conf['default_maxwidth'],
781      'maxheight' => $conf['default_maxheight'],
782      'registration_date' => $dbnow,
783      'enabled_high' =>
784        boolean_to_string($conf['newuser_default_enabled_high']),
785      );
786
787  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
788  mass_inserts(USER_INFOS_TABLE, array_keys($insert), array($insert));
789}
790
791/**
792 * returns the groupname corresponding to the given group identifier if
793 * exists
794 *
795 * @param int group_id
796 * @return mixed
797 */
798function get_groupname($group_id)
799{
800  $query = '
801SELECT name
802  FROM '.GROUPS_TABLE.'
803  WHERE id = '.intval($group_id).'
804;';
805  $result = pwg_query($query);
806  if (mysql_num_rows($result) > 0)
807  {
808    list($groupname) = mysql_fetch_row($result);
809  }
810  else
811  {
812    return false;
813  }
814
815  return $groupname;
816}
817
818/**
819 * return the file path of the given language filename, depending on the
820 * availability of the file
821 *
822 * in descending order of preference: user language, default language,
823 * PhpWebGallery default language.
824 *
825 * @param string filename
826 * @param string dirname
827 * @return string filepath
828 */
829function get_language_filepath($filename, $dirname = '')
830{
831  global $user, $conf;
832
833  if (empty($dirname))
834  {
835    $dirname = PHPWG_ROOT_PATH;
836  }
837  $dirname .= 'language'.'/';
838
839  $directories = array();
840  if ( isset($user['language']) )
841  {
842    $directories[] = $dirname.$user['language'];
843  }
844  $directories[] = $dirname.$conf['default_language'];
845  $directories[] = $dirname.PHPWG_DEFAULT_LANGUAGE;
846
847  foreach ($directories as $directory)
848  {
849    $filepath = $directory.'/'.$filename;
850
851    if (file_exists($filepath))
852    {
853      return $filepath;
854    }
855  }
856
857  return false;
858}
859
860/**
861 * returns the auto login key or false on error
862 * @param int user_id
863 * @param string [out] username
864*/
865function calculate_auto_login_key($user_id, &$username)
866{
867  global $conf;
868  $query = '
869SELECT '.$conf['user_fields']['username'].' AS username
870  , '.$conf['user_fields']['password'].' AS password
871FROM '.USERS_TABLE.'
872WHERE '.$conf['user_fields']['id'].' = '.$user_id;
873  $result = pwg_query($query);
874  if (mysql_num_rows($result) > 0)
875  {
876    $row = mysql_fetch_assoc($result);
877    $username = $row['username'];
878    $data = $row['username'].$row['password'];
879    $key = base64_encode(
880      pack('H*', sha1($data))
881      .hash_hmac('md5', $data, $conf['secret_key'],true)
882      );
883    return $key;
884  }
885  return false;
886}
887
888/*
889 * Performs all required actions for user login
890 * @param int user_id
891 * @param bool remember_me
892 * @return void
893*/
894function log_user($user_id, $remember_me)
895{
896  global $conf, $user;
897
898  if ($remember_me and $conf['authorize_remembering'])
899  {
900    $key = calculate_auto_login_key($user_id, $username);
901    if ($key!==false)
902    {
903      $cookie = array('id' => (int)$user_id, 'key' => $key);
904      setcookie($conf['remember_me_name'],
905                serialize($cookie),
906                time()+$conf['remember_me_length'],
907                cookie_path()
908              );
909        }
910  }
911  else
912  { // make sure we clean any remember me ...
913    setcookie($conf['remember_me_name'], '', 0, cookie_path());
914  }
915  if ( session_id()!="" )
916  { // we regenerate the session for security reasons
917    // see http://www.acros.si/papers/session_fixation.pdf
918    session_regenerate_id();
919  }
920  else
921  {
922    session_start();
923  }
924  $_SESSION['pwg_uid'] = (int)$user_id;
925
926  $user['id'] = $_SESSION['pwg_uid'];
927}
928
929/*
930 * Performs auto-connexion when cookie remember_me exists
931 * @return true/false
932*/
933function auto_login() {
934  global $conf;
935
936  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
937  {
938    $cookie = unserialize(stripslashes($_COOKIE[$conf['remember_me_name']]));
939    if ($cookie!==false and is_numeric(@$cookie['id']) )
940    {
941      $key = calculate_auto_login_key( $cookie['id'], $username );
942      if ($key!==false and $key===$cookie['key'])
943      {
944        log_user($cookie['id'], true);
945        trigger_action('login_success', $username);
946        return true;
947      }
948    }
949    setcookie($conf['remember_me_name'], '', 0, cookie_path());
950  }
951  return false;
952}
953
954/**
955 * Tries to login a user given username and password (must be MySql escaped)
956 * return true on success
957 */
958function try_log_user($username, $password, $remember_me)
959{
960  global $conf;
961  // retrieving the encrypted password of the login submitted
962  $query = '
963SELECT '.$conf['user_fields']['id'].' AS id,
964       '.$conf['user_fields']['password'].' AS password
965  FROM '.USERS_TABLE.'
966  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
967;';
968  $row = mysql_fetch_assoc(pwg_query($query));
969  if ($row['password'] == $conf['pass_convert']($password))
970  {
971    log_user($row['id'], $remember_me);
972    trigger_action('login_success', $username);
973    return true;
974  }
975  trigger_action('login_failure', $username);
976  return false;
977}
978
979/*
980 * Return access_type definition of uuser
981 * Test does with user status
982 * @return bool
983*/
984function get_access_type_status($user_status = '')
985{
986  global $user;
987
988  if (($user_status == '') and isset($user['status']))
989  {
990    $user_status = $user['status'];
991  }
992
993  $access_type_status = ACCESS_NONE;
994  switch ($user_status)
995  {
996    case 'guest':
997    case 'generic':
998    {
999      $access_type_status = ACCESS_GUEST;
1000      break;
1001    }
1002    case 'normal':
1003    {
1004      $access_type_status = ACCESS_CLASSIC;
1005      break;
1006    }
1007    case 'admin':
1008    {
1009      $access_type_status = ACCESS_ADMINISTRATOR;
1010      break;
1011    }
1012    case 'webmaster':
1013    {
1014      $access_type_status = ACCESS_WEBMASTER;
1015      break;
1016    }
1017  }
1018
1019  return $access_type_status;
1020}
1021
1022/*
1023 * Return if user have access to access_type definition
1024 * Test does with user status
1025 * @return bool
1026*/
1027function is_autorize_status($access_type, $user_status = '')
1028{
1029  return (get_access_type_status($user_status) >= $access_type);
1030}
1031
1032/*
1033 * Check if user have access to access_type definition
1034 * Stop action if there are not access
1035 * Test does with user status
1036 * @return none
1037*/
1038function check_status($access_type, $user_status = '')
1039{
1040  if (!is_autorize_status($access_type, $user_status))
1041  {
1042    access_denied();
1043  }
1044}
1045
1046/*
1047 * Return if user is an administrator
1048 * @return bool
1049*/
1050function is_admin($user_status = '')
1051{
1052  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
1053}
1054
1055/*
1056 * Return if current user is an adviser
1057 * @return bool
1058*/
1059function is_adviser()
1060{
1061  global $user;
1062
1063  return ($user['adviser'] == 'true');
1064}
1065
1066/*
1067 * Return mail address as display text
1068 * @return string
1069*/
1070function get_email_address_as_display_text($email_address)
1071{
1072  global $conf;
1073
1074  if (!isset($email_address) or (trim($email_address) == ''))
1075  {
1076    return '';
1077  }
1078  else
1079  {
1080    if (is_adviser())
1081    {
1082      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
1083    }
1084    else
1085    {
1086      return $email_address;
1087    }
1088  }
1089}
1090
1091/*
1092 * Compute sql where condition with restrict and filter data. "FandF" means
1093 * Forbidden and Filters.
1094 *
1095 * @param array condition_fields: read function body
1096 * @param string prefix_condition: prefixes sql if condition is not empty
1097 * @param boolean force_one_condition: use at least "1 = 1"
1098 *
1099 * @return string sql where/conditions
1100 */
1101function get_sql_condition_FandF(
1102  $condition_fields,
1103  $prefix_condition = null,
1104  $force_one_condition = false
1105  )
1106{
1107  global $user, $filter;
1108
1109  $sql_list = array();
1110
1111  foreach ($condition_fields as $condition => $field_name)
1112  {
1113    switch($condition)
1114    {
1115      case 'forbidden_categories':
1116      {
1117        if (!empty($user['forbidden_categories']))
1118        {
1119          $sql_list[] =
1120            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
1121        }
1122        break;
1123      }
1124      case 'visible_categories':
1125      {
1126        if (!empty($filter['visible_categories']))
1127        {
1128          $sql_list[] =
1129            $field_name.' IN ('.$filter['visible_categories'].')';
1130        }
1131        break;
1132      }
1133      case 'visible_images':
1134      {
1135        if (!empty($filter['visible_images']))
1136        {
1137          $sql_list[] =
1138            $field_name.' IN ('.$filter['visible_images'].')';
1139        }
1140        break;
1141      }
1142      default:
1143      {
1144        die('Unknow condition');
1145        break;
1146      }
1147    }
1148  }
1149
1150  if (count($sql_list) > 0)
1151  {
1152    $sql = '('.implode(' AND ', $sql_list).')';
1153  }
1154  else
1155  {
1156    if ($force_one_condition)
1157    {
1158      $sql = '1 = 1';
1159    }
1160    else
1161    {
1162      $sql = '';
1163    }
1164  }
1165
1166  if (isset($prefix_condition) and !empty($sql))
1167  {
1168    $sql = $prefix_condition.' '.$sql;
1169  }
1170
1171  return $sql;
1172}
1173
1174?>
Note: See TracBrowser for help on using the repository browser.