source: tags/build-A01/include/functions_user.inc.php @ 16897

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

Feature Issue ID 0000496: Integrate MOD add_index on PWG with plugin.lang.php

Add some plugin triggers:

o for help
o for language
o for site manager
o for advanced features

Allow to launch directly plugin page (without section key)

Add add_index plugin, available on site manager and advanced features

Configuration page and best help must be coming soon.

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