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

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

Feature Issue ID 0000601: Filter all public pages with only recent elements

It's a finalized version.
Obsolete code of draft are removed.

You can filter categories and images with recent date period on your screen selection.
In the future, filter could be easy done on other type data (plugin?)

You can flat categories and sub-categories with a recent date period of your choice.

Next, perhaps, a panel to choice recent date for the 2 features.

On draft, there have problem with MySql 5, be careful!

Css problem not resolved:

  • Menu "Categories" is bad centered
  • Icon on dark too on the top
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 26.0 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 1677 2006-12-21 21:38:20Z rub $
9// | last update   : $Date: 2006-12-21 21:38:20 +0000 (Thu, 21 Dec 2006) $
10// | last modifier : $Author: rub $
11// | revision      : $Revision: 1677 $
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 * @return string filepath
825 */
826function get_language_filepath($filename)
827{
828  global $user, $conf;
829
830  $directories = array();
831  if ( isset($user['language']) )
832  {
833    $directories[] = PHPWG_ROOT_PATH.'language/'.$user['language'];
834  }
835  $directories[] = PHPWG_ROOT_PATH.'language/'.$conf['default_language'];
836  $directories[] = PHPWG_ROOT_PATH.'language/'.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*/
855function calculate_auto_login_key($user_id)
856{
857  global $conf;
858  $query = '
859SELECT '.$conf['user_fields']['username'].' AS username
860  , '.$conf['user_fields']['password'].' AS password
861FROM '.USERS_TABLE.'
862WHERE '.$conf['user_fields']['id'].' = '.$user_id;
863  $result = pwg_query($query);
864  if (mysql_num_rows($result) > 0)
865  {
866    $row = mysql_fetch_assoc($result);
867    $key = sha1( $row['username'].$row['password'] );
868    return $key;
869  }
870  return false;
871}
872
873/*
874 * Performs all required actions for user login
875 * @param int user_id
876 * @param bool remember_me
877 * @return void
878*/
879function log_user($user_id, $remember_me)
880{
881  global $conf, $user;
882
883  if ($remember_me and $conf['authorize_remembering'])
884  {
885    $key = calculate_auto_login_key($user_id);
886    if ($key!==false)
887    {
888      $cookie = array('id' => (int)$user_id, 'key' => $key);
889      setcookie($conf['remember_me_name'],
890                serialize($cookie),
891                time()+$conf['remember_me_length'],
892                cookie_path()
893              );
894        }
895  }
896  else
897  { // make sure we clean any remember me ...
898    setcookie($conf['remember_me_name'], '', 0, cookie_path());
899  }
900  if ( session_id()!="" )
901  { // we regenerate the session for security reasons
902    // see http://www.acros.si/papers/session_fixation.pdf
903    session_regenerate_id();
904  }
905  else
906  {
907    session_start();
908  }
909  $_SESSION['pwg_uid'] = (int)$user_id;
910
911  $user['id'] = $_SESSION['pwg_uid'];
912}
913
914/*
915 * Performs auto-connexion when cookie remember_me exists
916 * @return true/false
917*/
918function auto_login() {
919  global $conf;
920
921  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
922  {
923    $cookie = unserialize(stripslashes($_COOKIE[$conf['remember_me_name']]));
924    if ($cookie!==false)
925    {
926      $key = calculate_auto_login_key($cookie['id']);
927      if ($key!==false and $key===$cookie['key'])
928      {
929        log_user($cookie['id'], true);
930        return true;
931      }
932    }
933    setcookie($conf['remember_me_name'], '', 0, cookie_path());
934  }
935  return false;
936}
937
938/*
939 * Return access_type definition of uuser
940 * Test does with user status
941 * @return bool
942*/
943function get_access_type_status($user_status = '')
944{
945  global $user;
946
947  if (($user_status == '') and isset($user['status']))
948  {
949    $user_status = $user['status'];
950  }
951
952  $access_type_status = ACCESS_NONE;
953  switch ($user_status)
954  {
955    case 'guest':
956    case 'generic':
957    {
958      $access_type_status = ACCESS_GUEST;
959      break;
960    }
961    case 'normal':
962    {
963      $access_type_status = ACCESS_CLASSIC;
964      break;
965    }
966    case 'admin':
967    {
968      $access_type_status = ACCESS_ADMINISTRATOR;
969      break;
970    }
971    case 'webmaster':
972    {
973      $access_type_status = ACCESS_WEBMASTER;
974      break;
975    }
976  }
977
978  return $access_type_status;
979}
980
981/*
982 * Return if user have access to access_type definition
983 * Test does with user status
984 * @return bool
985*/
986function is_autorize_status($access_type, $user_status = '')
987{
988  return (get_access_type_status($user_status) >= $access_type);
989}
990
991/*
992 * Check if user have access to access_type definition
993 * Stop action if there are not access
994 * Test does with user status
995 * @return none
996*/
997function check_status($access_type, $user_status = '')
998{
999  if (!is_autorize_status($access_type, $user_status))
1000  {
1001    access_denied();
1002  }
1003}
1004
1005/*
1006 * Return if user is an administrator
1007 * @return bool
1008*/
1009function is_admin($user_status = '')
1010{
1011  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
1012}
1013
1014/*
1015 * Return if current user is an adviser
1016 * @return bool
1017*/
1018function is_adviser()
1019{
1020  global $user;
1021
1022  return ($user['adviser'] == 'true');
1023}
1024
1025/*
1026 * Return mail address as display text
1027 * @return string
1028*/
1029function get_email_address_as_display_text($email_address)
1030{
1031  global $conf;
1032
1033  if (!isset($email_address) or (trim($email_address) == ''))
1034  {
1035    return '';
1036  }
1037  else
1038  {
1039    if (is_adviser())
1040    {
1041      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
1042    }
1043    else
1044    {
1045      return $email_address;
1046    }
1047  }
1048}
1049
1050/*
1051 * Compute sql where condition with restrict and filter data
1052 *
1053 * FandF: Forbidden and Filters
1054 *
1055 * @param $condition_fields array:
1056 *            keys are condition to aply and
1057 *            values are sql field to use
1058 *            array('forbidden_categories' => 'ic.category_id')
1059 *        $prefix_condition string:
1060 *            this value are concatenated if sql is not empty
1061 *        $force_one_condition:
1062 *            if there are not condition , use this condition "1 = 1"
1063 *
1064 * @return string sql where/conditions
1065 */
1066function get_sql_condition_FandF($condition_fields, $prefix_condition = null, $force_one_condition = false)
1067{
1068  global $user, $filter;
1069
1070  $sql_list = array();
1071
1072  foreach ($condition_fields as $condition => $field_name)
1073  {
1074    switch($condition)
1075    {
1076      case 'forbidden_categories':
1077        if (!empty($user['forbidden_categories']))
1078        {
1079          $sql_list[] = $field_name.' NOT IN ('.$user['forbidden_categories'].')';
1080        }
1081        break;
1082
1083      case 'visible_categories':
1084        if (!empty($filter['visible_categories']))
1085        {
1086          $sql_list[] = $field_name.' IN ('.$filter['visible_categories'].')';
1087        }
1088        break;
1089
1090      case 'visible_images':
1091        if (!empty($filter['visible_images']))
1092        {
1093          $sql_list[] = $field_name.' IN ('.$filter['visible_images'].')';
1094        }
1095        break;
1096
1097      default:
1098        die('Unknow condition');
1099        break;
1100
1101    }
1102  }
1103
1104  if (count($sql_list) > 0)
1105  {
1106    $sql = '('.implode(' AND ', $sql_list).')';
1107  }
1108  else
1109  {
1110    if ($force_one_condition)
1111    {
1112      $sql = '1 = 1';
1113    }
1114    else
1115    {
1116      $sql = '';
1117    }
1118  }
1119
1120  if (isset($prefix_condition) and !empty($sql))
1121  {
1122    $sql = $prefix_condition.' '.$sql;
1123  }
1124
1125  return $sql;
1126}
1127
1128?>
Note: See TracBrowser for help on using the repository browser.