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

Last change on this file since 6090 was 6090, checked in by plg, 14 years ago

bug 1648 fixed: add the pwg_db_check_version functions for pdo-sqlite, sqlite
and pgsql, also make the $pwg_db_link global in the install_db_connect function
so that it can be used in SQLite functions.

bug fixed: with pdo-sqlite, pwg_db_num_rows always returns 0, so when
initializing user data, it tries to insert the same row twice.

File size: 34.5 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24// validate_mail_address:
25//   o verifies whether the given mail address has the
26//     right format. ie someone@domain.com "someone" can contain ".", "-" or
27//     even "_". Exactly as "domain". The extension doesn't have to be
28//     "com". The mail address can also be empty.
29//   o check if address could be empty
30//   o check if address is not used by a other user
31// If the mail address doesn't correspond, an error message is returned.
32//
33function validate_mail_address($user_id, $mail_address)
34{
35  global $conf;
36
37  if (empty($mail_address) and
38      !($conf['obligatory_user_mail_address'] and
39      in_array(script_basename(), array('register', 'profile'))))
40  {
41    return '';
42  }
43
44  $atom   = '[-a-z0-9!#$%&\'*+\\/=?^_`{|}~]';   // before  arobase
45  $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // domain name
46  $regex = '/^' . $atom . '+' . '(\.' . $atom . '+)*' . '@' . '(' . $domain . '{1,63}\.)+' . $domain . '{2,63}$/i';
47
48  if ( !preg_match( $regex, $mail_address ) )
49  {
50    return l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
51  }
52
53  if (defined("PHPWG_INSTALLED") and !empty($mail_address))
54  {
55    $query = '
56select count(*)
57from '.USERS_TABLE.'
58where upper('.$conf['user_fields']['email'].') = upper(\''.$mail_address.'\')
59'.(is_numeric($user_id) ? 'and '.$conf['user_fields']['id'].' != \''.$user_id.'\'' : '').'
60;';
61    list($count) = pwg_db_fetch_row(pwg_query($query));
62    if ($count != 0)
63    {
64      return l10n('a user use already this mail address');
65    }
66  }
67}
68
69// validate_login_case:
70//   o check if login is not used by a other user
71// If the login doesn't correspond, an error message is returned.
72//
73function validate_login_case($login)
74{
75  global $conf;
76 
77  if (defined("PHPWG_INSTALLED"))
78  {
79    $query = "
80SELECT ".$conf['user_fields']['username']."
81FROM ".USERS_TABLE."
82WHERE LOWER(".stripslashes($conf['user_fields']['username']).") = '".strtolower($login)."'
83;";
84
85    $count = pwg_db_num_rows(pwg_query($query));
86
87    if ($count > 0)
88    {
89      return l10n('this login is already used');
90    }
91  }
92}
93
94function register_user($login, $password, $mail_address,
95  $with_notification = true, $errors = array())
96{
97  global $conf;
98
99  if ($login == '')
100  {
101    array_push($errors, l10n('Please, enter a login'));
102  }
103  if (preg_match('/^.* $/', $login))
104  {
105    array_push($errors, l10n('login mustn\'t end with a space character'));
106  }
107  if (preg_match('/^ .*$/', $login))
108  {
109    array_push($errors, l10n('login mustn\'t start with a space character'));
110  }
111  if (get_userid($login))
112  {
113    array_push($errors, l10n('this login is already used'));
114  }
115  $mail_error = validate_mail_address(null, $mail_address);
116  if ('' != $mail_error)
117  {
118    array_push($errors, $mail_error);
119  }
120
121  if ($conf['insensitive_case_logon'] == true)
122  {
123    $login_error = validate_login_case($login);
124    if ($login_error != '')
125    {
126      array_push($errors, $login_error);
127    }
128  }
129
130  $errors = trigger_event('register_user_check',
131              $errors,
132              array(
133                'username'=>$login,
134                'password'=>$password,
135                'email'=>$mail_address,
136              )
137            );
138
139  // if no error until here, registration of the user
140  if (count($errors) == 0)
141  {
142    // what will be the inserted id ?
143    $query = '
144SELECT MAX('.$conf['user_fields']['id'].') + 1
145  FROM '.USERS_TABLE.'
146;';
147    list($next_id) = pwg_db_fetch_row(pwg_query($query));
148
149    $insert =
150      array(
151        $conf['user_fields']['id'] => $next_id,
152        $conf['user_fields']['username'] => pwg_db_real_escape_string($login),
153        $conf['user_fields']['password'] => $conf['pass_convert']($password),
154        $conf['user_fields']['email'] => $mail_address
155        );
156
157    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
158    mass_inserts(USERS_TABLE, array_keys($insert), array($insert));
159
160    // Assign by default groups
161    {
162      $query = '
163SELECT id
164  FROM '.GROUPS_TABLE.'
165  WHERE is_default = \''.boolean_to_string(true).'\'
166  ORDER BY id ASC
167;';
168      $result = pwg_query($query);
169
170      $inserts = array();
171      while ($row = pwg_db_fetch_assoc($result))
172      {
173        array_push
174        (
175          $inserts,
176          array
177          (
178            'user_id' => $next_id,
179            'group_id' => $row['id']
180          )
181        );
182      }
183    }
184
185    if (count($inserts) != 0)
186    {
187      include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
188      mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts);
189    }
190
191    $override = null;
192    if ($with_notification and $conf['browser_language'])
193    {
194      if ( !get_browser_language($override['language']) )
195        $override=null;
196    }
197    create_user_infos($next_id, $override);
198
199    if ($with_notification and $conf['email_admin_on_new_user'])
200    {
201      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
202      $admin_url = get_absolute_root_url()
203                   .'admin.php?page=user_list&username='.$login;
204
205      $keyargs_content = array
206      (
207        get_l10n_args('User: %s', stripslashes($login)),
208        get_l10n_args('Email: %s', $_POST['mail_address']),
209        get_l10n_args('', ''),
210        get_l10n_args('Admin: %s', $admin_url)
211      );
212
213      pwg_mail_notification_admins
214      (
215        get_l10n_args('Registration of %s', stripslashes($login)),
216        $keyargs_content
217      );
218    }
219
220    trigger_action('register_user',
221      array(
222        'id'=>$next_id,
223        'username'=>$login,
224        'email'=>$mail_address,
225       )
226      );
227  }
228
229  return $errors;
230}
231
232function build_user( $user_id, $use_cache )
233{
234  global $conf;
235
236  $user['id'] = $user_id;
237  $user = array_merge( $user, getuserdata($user_id, $use_cache) );
238
239  if ($user['id'] == $conf['guest_id'] and $user['status'] <> 'guest')
240  {
241    $user['status'] = 'guest';
242    $user['internal_status']['guest_must_be_guest'] = true;
243  }
244
245  // calculation of the number of picture to display per page
246  $user['nb_image_page'] = $user['nb_image_line'] * $user['nb_line_page'];
247
248  // Check user theme
249  if (!isset($user['theme_name']))
250  {
251    $user['theme'] = get_default_theme();
252  }
253
254  return $user;
255}
256
257/**
258 * find informations related to the user identifier
259 *
260 * @param int user identifier
261 * @param boolean use_cache
262 * @param array
263 */
264function getuserdata($user_id, $use_cache)
265{
266  global $conf;
267
268  $userdata = array();
269
270  $query = '
271SELECT ';
272  $is_first = true;
273  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
274  {
275    if ($is_first)
276    {
277      $is_first = false;
278    }
279    else
280    {
281      $query.= '
282     , ';
283    }
284    $query.= $dbfield.' AS '.$pwgfield;
285  }
286  $query.= '
287  FROM '.USERS_TABLE.'
288  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'';
289
290  $row = pwg_db_fetch_assoc(pwg_query($query));
291
292  while (true)
293  {
294    $query = '
295SELECT ui.*, uc.*, t.name AS theme_name
296  FROM '.USER_INFOS_TABLE.' AS ui
297    LEFT JOIN '.USER_CACHE_TABLE.' AS uc ON ui.user_id = uc.user_id
298    LEFT JOIN '.THEMES_TABLE.' AS t ON t.id = ui.theme
299  WHERE ui.user_id = \''.$user_id.'\'';
300    $result = pwg_query($query);
301    if ($result)
302    {
303      break;
304    }
305    else
306    {
307      create_user_infos($user_id);
308    }
309  }
310
311  $row = array_merge($row, pwg_db_fetch_assoc($result));
312
313  foreach ($row as $key => $value)
314  {
315    if (!is_numeric($key))
316    {
317      // If the field is true or false, the variable is transformed into a
318      // boolean value.
319      if ($value == 'true' or $value == 'false')
320      {
321        $userdata[$key] = get_boolean($value);
322      }
323      else
324      {
325        $userdata[$key] = $value;
326      }
327    }
328  }
329
330  if ($use_cache)
331  {
332    if (!isset($userdata['need_update'])
333        or !is_bool($userdata['need_update'])
334        or $userdata['need_update'] == true)
335    {
336      $userdata['cache_update_time'] = time();
337
338      // Set need update are done
339      $userdata['need_update'] = false;
340
341      $userdata['forbidden_categories'] =
342        calculate_permissions($userdata['id'], $userdata['status']);
343
344      /* now we build the list of forbidden images (this list does not contain
345      images that are not in at least an authorized category)*/
346      $query = '
347SELECT DISTINCT(id)
348  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
349  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
350    AND level>'.$userdata['level'];
351      $forbidden_ids = array_from_query($query, 'id');
352
353      if ( empty($forbidden_ids) )
354      {
355        array_push( $forbidden_ids, 0 );
356      }
357      $userdata['image_access_type'] = 'NOT IN'; //TODO maybe later
358      $userdata['image_access_list'] = implode(',',$forbidden_ids);
359
360
361      $query = '
362SELECT COUNT(DISTINCT(image_id)) as total
363  FROM '.IMAGE_CATEGORY_TABLE.'
364  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
365    AND image_id '.$userdata['image_access_type'].' ('.$userdata['image_access_list'].')';
366      list($userdata['nb_total_images']) = pwg_db_fetch_row(pwg_query($query));
367
368
369      // now we update user cache categories
370      $user_cache_cats = get_computed_categories($userdata, null);
371      if ( !is_admin($userdata['status']) )
372      { // for non admins we forbid categories with no image (feature 1053)
373        $forbidden_ids = array();
374        foreach ($user_cache_cats as $cat)
375        {
376          if ($cat['count_images']==0)
377          {
378            array_push($forbidden_ids, $cat['cat_id']);
379            unset( $user_cache_cats[$cat['cat_id']] );
380          }
381        }
382        if ( !empty($forbidden_ids) )
383        {
384          if ( empty($userdata['forbidden_categories']) )
385          {
386            $userdata['forbidden_categories'] = implode(',', $forbidden_ids);
387          }
388          else
389          {
390            $userdata['forbidden_categories'] .= ','.implode(',', $forbidden_ids);
391          }
392        }
393      }
394
395      // delete user cache
396      $query = '
397DELETE FROM '.USER_CACHE_CATEGORIES_TABLE.'
398  WHERE user_id = '.$userdata['id'];
399      pwg_query($query);
400
401      include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
402      mass_inserts
403      (
404        USER_CACHE_CATEGORIES_TABLE,
405        array
406        (
407          'user_id', 'cat_id',
408          'date_last', 'max_date_last', 'nb_images', 'count_images', 'count_categories'
409        ),
410        $user_cache_cats
411      );
412
413
414      // update user cache
415      $query = '
416DELETE FROM '.USER_CACHE_TABLE.'
417  WHERE user_id = '.$userdata['id'];
418      pwg_query($query);
419
420      $query = '
421INSERT INTO '.USER_CACHE_TABLE.'
422  (user_id, need_update, cache_update_time, forbidden_categories, nb_total_images,
423    image_access_type, image_access_list)
424  VALUES
425  ('.$userdata['id'].',\''.boolean_to_string($userdata['need_update']).'\','
426  .$userdata['cache_update_time'].',\''
427  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].',\''
428  .$userdata['image_access_type'].'\',\''.$userdata['image_access_list'].'\')';
429      pwg_query($query);
430    }
431  }
432
433  return $userdata;
434}
435
436/*
437 * deletes favorites of the current user if he's not allowed to see them
438 *
439 * @return void
440 */
441function check_user_favorites()
442{
443  global $user;
444
445  if ($user['forbidden_categories'] == '')
446  {
447    return;
448  }
449
450  // $filter['visible_categories'] and $filter['visible_images']
451  // must be not used because filter <> restriction
452  // retrieving images allowed : belonging to at least one authorized
453  // category
454  $query = '
455SELECT DISTINCT f.image_id
456  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
457    ON f.image_id = ic.image_id
458  WHERE f.user_id = '.$user['id'].'
459'.get_sql_condition_FandF
460  (
461    array
462      (
463        'forbidden_categories' => 'ic.category_id',
464      ),
465    'AND'
466  ).'
467;';
468  $result = pwg_query($query);
469  $authorizeds = array();
470  while ($row = pwg_db_fetch_assoc($result))
471  {
472    array_push($authorizeds, $row['image_id']);
473  }
474
475  $query = '
476SELECT image_id
477  FROM '.FAVORITES_TABLE.'
478  WHERE user_id = '.$user['id'].'
479;';
480  $result = pwg_query($query);
481  $favorites = array();
482  while ($row = pwg_db_fetch_assoc($result))
483  {
484    array_push($favorites, $row['image_id']);
485  }
486
487  $to_deletes = array_diff($favorites, $authorizeds);
488
489  if (count($to_deletes) > 0)
490  {
491    $query = '
492DELETE FROM '.FAVORITES_TABLE.'
493  WHERE image_id IN ('.implode(',', $to_deletes).')
494    AND user_id = '.$user['id'].'
495;';
496    pwg_query($query);
497  }
498}
499
500/**
501 * calculates the list of forbidden categories for a given user
502 *
503 * Calculation is based on private categories minus categories authorized to
504 * the groups the user belongs to minus the categories directly authorized
505 * to the user. The list contains at least -1 to be compliant with queries
506 * such as "WHERE category_id NOT IN ($forbidden_categories)"
507 *
508 * @param int user_id
509 * @param string user_status
510 * @return string forbidden_categories
511 */
512function calculate_permissions($user_id, $user_status)
513{
514  $private_array = array();
515  $authorized_array = array();
516
517  $query = '
518SELECT id
519  FROM '.CATEGORIES_TABLE.'
520  WHERE status = \'private\'
521;';
522  $result = pwg_query($query);
523  while ($row = pwg_db_fetch_assoc($result))
524  {
525    array_push($private_array, $row['id']);
526  }
527
528  // retrieve category ids directly authorized to the user
529  $query = '
530SELECT cat_id
531  FROM '.USER_ACCESS_TABLE.'
532  WHERE user_id = '.$user_id.'
533;';
534  $authorized_array = array_from_query($query, 'cat_id');
535
536  // retrieve category ids authorized to the groups the user belongs to
537  $query = '
538SELECT cat_id
539  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
540    ON ug.group_id = ga.group_id
541  WHERE ug.user_id = '.$user_id.'
542;';
543  $authorized_array =
544    array_merge(
545      $authorized_array,
546      array_from_query($query, 'cat_id')
547      );
548
549  // uniquify ids : some private categories might be authorized for the
550  // groups and for the user
551  $authorized_array = array_unique($authorized_array);
552
553  // only unauthorized private categories are forbidden
554  $forbidden_array = array_diff($private_array, $authorized_array);
555
556  // if user is not an admin, locked categories are forbidden
557  if (!is_admin($user_status))
558  {
559    $query = '
560SELECT id
561  FROM '.CATEGORIES_TABLE.'
562  WHERE visible = \'false\'
563;';
564    $result = pwg_query($query);
565    while ($row = pwg_db_fetch_assoc($result))
566    {
567      array_push($forbidden_array, $row['id']);
568    }
569    $forbidden_array = array_unique($forbidden_array);
570  }
571
572  if ( empty($forbidden_array) )
573  {// at least, the list contains 0 value. This category does not exists so
574   // where clauses such as "WHERE category_id NOT IN(0)" will always be
575   // true.
576    array_push($forbidden_array, 0);
577  }
578
579  return implode(',', $forbidden_array);
580}
581
582/**
583 * compute data of categories branches (one branch only)
584 */
585function compute_branch_cat_data(&$cats, &$list_cat_id, &$level, &$ref_level)
586{
587  $date = '';
588  $count_images = 0;
589  $count_categories = 0;
590  do
591  {
592    $cat_id = array_pop($list_cat_id);
593    if (!is_null($cat_id))
594    {
595      // Count images and categories
596      $cats[$cat_id]['count_images'] += $count_images;
597      $cats[$cat_id]['count_categories'] += $count_categories;
598      $count_images = $cats[$cat_id]['count_images'];
599      $count_categories = $cats[$cat_id]['count_categories'] + 1;
600
601      if ((empty($cats[$cat_id]['max_date_last'])) or ($cats[$cat_id]['max_date_last'] < $date))
602      {
603        $cats[$cat_id]['max_date_last'] = $date;
604      }
605      else
606      {
607        $date = $cats[$cat_id]['max_date_last'];
608      }
609      $ref_level = substr_count($cats[$cat_id]['global_rank'], '.') + 1;
610    }
611    else
612    {
613      $ref_level = 0;
614    }
615  } while ($level <= $ref_level);
616
617  // Last cat updating must be added to list for next branch
618  if ($ref_level <> 0)
619  {
620    array_push($list_cat_id, $cat_id);
621  }
622}
623
624/**
625 * compute data of categories branches
626 */
627function compute_categories_data(&$cats)
628{
629  $ref_level = 0;
630  $level = 0;
631  $list_cat_id = array();
632
633  foreach ($cats as $id => $category)
634  {
635    // Compute
636    $level = substr_count($category['global_rank'], '.') + 1;
637    if ($level > $ref_level)
638    {
639      array_push($list_cat_id, $id);
640    }
641    else
642    {
643      compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
644      array_push($list_cat_id, $id);
645    }
646    $ref_level = $level;
647  }
648
649  $level = 1;
650  compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
651}
652
653/**
654 * get computed array of categories
655 *
656 * @param array userdata
657 * @param int filter_days number of recent days to filter on or null
658 * @return array
659 */
660function get_computed_categories($userdata, $filter_days=null)
661{
662  $query = 'SELECT c.id cat_id, global_rank';
663  // Count by date_available to avoid count null
664  $query .= ',
665  MAX(date_available) date_last, COUNT(date_available) nb_images
666FROM '.CATEGORIES_TABLE.' as c
667  LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
668  LEFT JOIN '.IMAGES_TABLE.' AS i
669    ON ic.image_id = i.id
670      AND i.level<='.$userdata['level'];
671
672  if ( isset($filter_days) )
673  {
674    $query .= ' AND i.date_available > '.pwg_db_get_recent_period_expression($filter_days);
675  }
676
677  if ( !empty($userdata['forbidden_categories']) )
678  {
679    $query.= '
680  WHERE c.id NOT IN ('.$userdata['forbidden_categories'].')';
681  }
682
683  $query.= '
684  GROUP BY c.id, c.global_rank';
685
686  $result = pwg_query($query);
687
688  $cats = array();
689  while ($row = pwg_db_fetch_assoc($result))
690  {
691    $row['user_id'] = $userdata['id'];
692    $row['count_categories'] = 0;
693    $row['count_images'] = (int)$row['nb_images'];
694    $row['max_date_last'] = $row['date_last'];
695
696    $cats += array($row['cat_id'] => $row);
697  }
698  uasort($cats, 'global_rank_compare');
699
700  compute_categories_data($cats);
701
702  if ( isset($filter_days) )
703  {
704    $cat_tmp = $cats;
705    $cats = array();
706
707    foreach ($cat_tmp as $category)
708    {
709      if (!empty($category['max_date_last']))
710      {
711        // Re-init counters
712        $category['count_categories'] = 0;
713        $category['count_images'] = (int)$category['nb_images'];
714        // Keep category
715        $cats[$category['cat_id']] = $category;
716      }
717    }
718    // Compute a second time
719    compute_categories_data($cats);
720  }
721  return $cats;
722}
723
724/**
725 * returns user identifier thanks to his name, false if not found
726 *
727 * @param string username
728 * @param int user identifier
729 */
730function get_userid($username)
731{
732  global $conf;
733
734  $username = pwg_db_real_escape_string($username);
735
736  $query = '
737SELECT '.$conf['user_fields']['id'].'
738  FROM '.USERS_TABLE.'
739  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
740;';
741  $result = pwg_query($query);
742
743  if (pwg_db_num_rows($result) == 0)
744  {
745    return false;
746  }
747  else
748  {
749    list($user_id) = pwg_db_fetch_row($result);
750    return $user_id;
751  }
752}
753
754/**
755 * search an available feed_id
756 *
757 * @return string feed identifier
758 */
759function find_available_feed_id()
760{
761  while (true)
762  {
763    $key = generate_key(50);
764    $query = '
765SELECT COUNT(*)
766  FROM '.USER_FEED_TABLE.'
767  WHERE id = \''.$key.'\'
768;';
769    list($count) = pwg_db_fetch_row(pwg_query($query));
770    if (0 == $count)
771    {
772      return $key;
773    }
774  }
775}
776
777/*
778 * Returns a array with default user value
779 *
780 * @param convert_str allows to convert string value if necessary
781 */
782function get_default_user_info($convert_str = true)
783{
784  global $cache, $conf;
785
786  if (!isset($cache['default_user']))
787  {
788    $query = 'SELECT * FROM '.USER_INFOS_TABLE.
789            ' WHERE user_id = '.$conf['default_user_id'].';';
790
791    $result = pwg_query($query);
792    $cache['default_user'] = pwg_db_fetch_assoc($result);
793
794    if ($cache['default_user'] !== false)
795    {
796      unset($cache['default_user']['user_id']);
797      unset($cache['default_user']['status']);
798      unset($cache['default_user']['registration_date']);
799    }
800  }
801
802  if (is_array($cache['default_user']) and $convert_str)
803  {
804    $default_user = array();
805    foreach ($cache['default_user'] as $name => $value)
806    {
807      // If the field is true or false, the variable is transformed into a
808      // boolean value.
809      if ($value == 'true' or $value == 'false')
810      {
811        $default_user[$name] = get_boolean($value);
812      }
813      else
814      {
815        $default_user[$name] = $value;
816      }
817    }
818    return $default_user;
819  }
820  else
821  {
822    return $cache['default_user'];
823  }
824}
825
826/*
827 * Returns a default user value
828 *
829 * @param value_name: name of value
830 * @param sos_value: value used if don't exist value
831 */
832function get_default_user_value($value_name, $sos_value)
833{
834  $default_user = get_default_user_info(true);
835  if ($default_user === false or empty($default_user[$value_name]))
836  {
837    return $sos_value;
838  }
839  else
840  {
841   return $default_user[$value_name];
842  }
843}
844
845/*
846 * Returns the default template value
847 *
848 */
849function get_default_theme()
850{
851  $theme = get_default_user_value('theme', PHPWG_DEFAULT_TEMPLATE);
852  if (check_theme_installed($theme))
853  {
854    return $theme;
855  }
856 
857  // let's find the first available theme
858  $active_themes = get_pwg_themes();
859  foreach (array_keys(get_pwg_themes()) as $theme_id)
860  {
861    if (check_theme_installed($theme_id))
862    {
863      return $theme_id;
864    }
865  }
866}
867
868/*
869 * Returns the default language value
870 *
871 */
872function get_default_language()
873{
874  return get_default_user_value('language', PHPWG_DEFAULT_LANGUAGE);
875}
876
877/**
878  * Returns true if the browser language value is set into param $lang
879  *
880  */
881function get_browser_language(&$lang)
882{
883  $browser_language = substr(@$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
884  foreach (get_languages() as $language_code => $language_name)
885  {
886    if (substr($language_code, 0, 2) == $browser_language)
887    {
888      $lang = $language_code;
889      return true;
890    }
891  }
892  return false;
893}
894
895/**
896 * add user informations based on default values
897 *
898 * @param int user_id / array of user_if
899 * @param array of values used to override default user values
900 */
901function create_user_infos($arg_id, $override_values = null)
902{
903  global $conf;
904
905  if (is_array($arg_id))
906  {
907    $user_ids = $arg_id;
908  }
909  else
910  {
911    $user_ids = array();
912    if (is_numeric($arg_id))
913    {
914      $user_ids[] = $arg_id;
915    }
916  }
917
918  if (!empty($user_ids))
919  {
920    $inserts = array();
921    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
922
923    $default_user = get_default_user_info(false);
924    if ($default_user === false)
925    {
926      // Default on structure are used
927      $default_user = array();
928    }
929
930    if (!is_null($override_values))
931    {
932      $default_user = array_merge($default_user, $override_values);
933    }
934
935    foreach ($user_ids as $user_id)
936    {
937      $level= isset($default_user['level']) ? $default_user['level'] : 0;
938      if ($user_id == $conf['webmaster_id'])
939      {
940        $status = 'webmaster';
941        $level = max( $conf['available_permission_levels'] );
942      }
943      else if (($user_id == $conf['guest_id']) or
944               ($user_id == $conf['default_user_id']))
945      {
946        $status = 'guest';
947      }
948      else
949      {
950        $status = 'normal';
951      }
952
953      $insert = array_merge(
954        $default_user,
955        array(
956          'user_id' => $user_id,
957          'status' => $status,
958          'registration_date' => $dbnow,
959          'level' => $level
960          ));
961
962      array_push($inserts, $insert);
963    }
964
965    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
966    mass_inserts(USER_INFOS_TABLE, array_keys($inserts[0]), $inserts);
967
968  }
969}
970
971/**
972 * returns the auto login key or false on error
973 * @param int user_id
974 * @param time_t time
975 * @param string [out] username
976*/
977function calculate_auto_login_key($user_id, $time, &$username)
978{
979  global $conf;
980  $query = '
981SELECT '.$conf['user_fields']['username'].' AS username
982  , '.$conf['user_fields']['password'].' AS password
983FROM '.USERS_TABLE.'
984WHERE '.$conf['user_fields']['id'].' = '.$user_id;
985  $result = pwg_query($query);
986  if (pwg_db_num_rows($result) > 0)
987  {
988    $row = pwg_db_fetch_assoc($result);
989    $username = stripslashes($row['username']);
990    $data = $time.stripslashes($row['username']).$row['password'];
991    $key = base64_encode(
992      pack('H*', sha1($data))
993      .hash_hmac('md5', $data, $conf['secret_key'],true)
994      );
995    return $key;
996  }
997  return false;
998}
999
1000/*
1001 * Performs all required actions for user login
1002 * @param int user_id
1003 * @param bool remember_me
1004 * @return void
1005*/
1006function log_user($user_id, $remember_me)
1007{
1008  global $conf, $user;
1009
1010  if ($remember_me and $conf['authorize_remembering'])
1011  {
1012    $now = time();
1013    $key = calculate_auto_login_key($user_id, $now, $username);
1014    if ($key!==false)
1015    {
1016      $cookie = $user_id.'-'.$now.'-'.$key;
1017      if (version_compare(PHP_VERSION, '5.2', '>=') )
1018      {
1019        setcookie($conf['remember_me_name'],
1020            $cookie,
1021            time()+$conf['remember_me_length'],
1022            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure'),
1023            ini_get('session.cookie_httponly')
1024          );
1025      }
1026      else
1027      {
1028        setcookie($conf['remember_me_name'],
1029            $cookie,
1030            time()+$conf['remember_me_length'],
1031            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure')
1032          );
1033      }
1034    }
1035  }
1036  else
1037  { // make sure we clean any remember me ...
1038    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
1039  }
1040  if ( session_id()!="" )
1041  { // we regenerate the session for security reasons
1042    // see http://www.acros.si/papers/session_fixation.pdf
1043    session_regenerate_id();
1044  }
1045  else
1046  {
1047    session_start();
1048  }
1049  $_SESSION['pwg_uid'] = (int)$user_id;
1050
1051  $user['id'] = $_SESSION['pwg_uid'];
1052}
1053
1054/*
1055 * Performs auto-connexion when cookie remember_me exists
1056 * @return true/false
1057*/
1058function auto_login() {
1059  global $conf;
1060
1061  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
1062  {
1063    $cookie = explode('-', stripslashes($_COOKIE[$conf['remember_me_name']]));
1064    if ( count($cookie)===3
1065        and is_numeric(@$cookie[0]) /*user id*/
1066        and is_numeric(@$cookie[1]) /*time*/
1067        and time()-$conf['remember_me_length']<=@$cookie[1]
1068        and time()>=@$cookie[1] /*cookie generated in the past*/ )
1069    {
1070      $key = calculate_auto_login_key( $cookie[0], $cookie[1], $username );
1071      if ($key!==false and $key===$cookie[2])
1072      {
1073        log_user($cookie[0], true);
1074        trigger_action('login_success', stripslashes($username));
1075        return true;
1076      }
1077    }
1078    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
1079  }
1080  return false;
1081}
1082
1083/**
1084 * Tries to login a user given username and password (must be MySql escaped)
1085 * return true on success
1086 */
1087function try_log_user($username, $password, $remember_me)
1088{
1089  global $conf;
1090  // retrieving the encrypted password of the login submitted
1091  $query = '
1092SELECT '.$conf['user_fields']['id'].' AS id,
1093       '.$conf['user_fields']['password'].' AS password
1094  FROM '.USERS_TABLE.'
1095  WHERE '.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\'
1096;';
1097  $row = pwg_db_fetch_assoc(pwg_query($query));
1098  if ($row['password'] == $conf['pass_convert']($password))
1099  {
1100    log_user($row['id'], $remember_me);
1101    trigger_action('login_success', stripslashes($username));
1102    return true;
1103  }
1104  trigger_action('login_failure', stripslashes($username));
1105  return false;
1106}
1107
1108/** Performs all the cleanup on user logout */
1109function logout_user()
1110{
1111  global $conf;
1112  $_SESSION = array();
1113  session_unset();
1114  session_destroy();
1115  setcookie(session_name(),'',0,
1116      ini_get('session.cookie_path'),
1117      ini_get('session.cookie_domain')
1118    );
1119  setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
1120}
1121
1122/*
1123 * Return user status used in this library
1124 * @return string
1125*/
1126function get_user_status($user_status)
1127{
1128  global $user;
1129
1130  if (empty($user_status))
1131  {
1132    if (isset($user['status']))
1133    {
1134      $user_status = $user['status'];
1135    }
1136    else
1137    {
1138      // swicth to default value
1139      $user_status = '';
1140    }
1141  }
1142  return $user_status;
1143}
1144
1145/*
1146 * Return access_type definition of user
1147 * Test does with user status
1148 * @return bool
1149*/
1150function get_access_type_status($user_status='')
1151{
1152  global $conf;
1153
1154  switch (get_user_status($user_status))
1155  {
1156    case 'guest':
1157    {
1158      $access_type_status =
1159        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_FREE);
1160      break;
1161    }
1162    case 'generic':
1163    {
1164      $access_type_status = ACCESS_GUEST;
1165      break;
1166    }
1167    case 'normal':
1168    {
1169      $access_type_status = ACCESS_CLASSIC;
1170      break;
1171    }
1172    case 'admin':
1173    {
1174      $access_type_status = ACCESS_ADMINISTRATOR;
1175      break;
1176    }
1177    case 'webmaster':
1178    {
1179      $access_type_status = ACCESS_WEBMASTER;
1180      break;
1181    }
1182    default:
1183    {
1184      $access_type_status = ACCESS_FREE;
1185      break;
1186    }
1187  }
1188
1189  return $access_type_status;
1190}
1191
1192/*
1193 * Return if user have access to access_type definition
1194 * Test does with user status
1195 * @return bool
1196*/
1197function is_autorize_status($access_type, $user_status = '')
1198{
1199  return (get_access_type_status($user_status) >= $access_type);
1200}
1201
1202/*
1203 * Check if user have access to access_type definition
1204 * Stop action if there are not access
1205 * Test does with user status
1206 * @return none
1207*/
1208function check_status($access_type, $user_status = '')
1209{
1210  if (!is_autorize_status($access_type, $user_status))
1211  {
1212    access_denied();
1213  }
1214}
1215
1216/*
1217 * Return if user is generic
1218 * @return bool
1219*/
1220 function is_generic($user_status = '')
1221{
1222  return get_user_status($user_status) == 'generic';
1223}
1224
1225/*
1226 * Return if user is only a guest
1227 * @return bool
1228*/
1229 function is_a_guest($user_status = '')
1230{
1231  return get_user_status($user_status) == 'guest';
1232}
1233
1234/*
1235 * Return if user is, at least, a classic user
1236 * @return bool
1237*/
1238 function is_classic_user($user_status = '')
1239{
1240  return is_autorize_status(ACCESS_CLASSIC, $user_status);
1241}
1242
1243/*
1244 * Return if user is, at least, an administrator
1245 * @return bool
1246*/
1247 function is_admin($user_status = '')
1248{
1249  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
1250}
1251
1252/*
1253 * Return if user is, at least, a webmaster
1254 * @return bool
1255*/
1256 function is_webmaster($user_status = '')
1257{
1258  return is_autorize_status(ACCESS_WEBMASTER, $user_status);
1259}
1260
1261/*
1262 * Return if current user is an adviser
1263 * @return bool
1264*/
1265function is_adviser()
1266{
1267  global $user;
1268
1269  return ($user['adviser'] == 'true');
1270}
1271
1272/*
1273 * Return if current user can edit/delete/validate a comment
1274 * @param action edit/delete/validate
1275 * @return bool
1276 */
1277function can_manage_comment($action, $comment_author_id)
1278{
1279  global $user, $conf;
1280 
1281  if (is_a_guest())
1282  {
1283    return false;
1284  }
1285 
1286  if (!in_array($action, array('delete','edit', 'validate')))
1287  {
1288    return false;
1289  }
1290
1291  if (is_admin())
1292  {
1293    return true;
1294  }
1295
1296  if ('edit' == $action and $conf['user_can_edit_comment'])
1297  {
1298    if ($comment_author_id == $user['id']) {
1299      return true;
1300    }
1301  }
1302
1303  if ('delete' == $action and $conf['user_can_delete_comment'])
1304  {
1305    if ($comment_author_id == $user['id']) {
1306      return true;
1307    }
1308  }
1309
1310  return false;
1311}
1312
1313/*
1314 * Return mail address as display text
1315 * @return string
1316*/
1317function get_email_address_as_display_text($email_address)
1318{
1319  global $conf;
1320
1321  if (!isset($email_address) or (trim($email_address) == ''))
1322  {
1323    return '';
1324  }
1325  else
1326  {
1327    if (defined('IN_ADMIN') and is_adviser())
1328    {
1329      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
1330    }
1331    else
1332    {
1333      return $email_address;
1334    }
1335  }
1336}
1337
1338/*
1339 * Compute sql where condition with restrict and filter data. "FandF" means
1340 * Forbidden and Filters.
1341 *
1342 * @param array condition_fields: read function body
1343 * @param string prefix_condition: prefixes sql if condition is not empty
1344 * @param boolean force_one_condition: use at least "1 = 1"
1345 *
1346 * @return string sql where/conditions
1347 */
1348function get_sql_condition_FandF(
1349  $condition_fields,
1350  $prefix_condition = null,
1351  $force_one_condition = false
1352  )
1353{
1354  global $user, $filter;
1355
1356  $sql_list = array();
1357
1358  foreach ($condition_fields as $condition => $field_name)
1359  {
1360    switch($condition)
1361    {
1362      case 'forbidden_categories':
1363      {
1364        if (!empty($user['forbidden_categories']))
1365        {
1366          $sql_list[] =
1367            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
1368        }
1369        break;
1370      }
1371      case 'visible_categories':
1372      {
1373        if (!empty($filter['visible_categories']))
1374        {
1375          $sql_list[] =
1376            $field_name.' IN ('.$filter['visible_categories'].')';
1377        }
1378        break;
1379      }
1380      case 'visible_images':
1381        if (!empty($filter['visible_images']))
1382        {
1383          $sql_list[] =
1384            $field_name.' IN ('.$filter['visible_images'].')';
1385        }
1386        // note there is no break - visible include forbidden
1387      case 'forbidden_images':
1388        if (
1389            !empty($user['image_access_list'])
1390            or $user['image_access_type']!='NOT IN'
1391            )
1392        {
1393          $table_prefix=null;
1394          if ($field_name=='id')
1395          {
1396            $table_prefix = '';
1397          }
1398          elseif ($field_name=='i.id')
1399          {
1400            $table_prefix = 'i.';
1401          }
1402          if ( isset($table_prefix) )
1403          {
1404            $sql_list[]=$table_prefix.'level<='.$user['level'];
1405          }
1406          else
1407          {
1408            $sql_list[]=$field_name.' '.$user['image_access_type']
1409                .' ('.$user['image_access_list'].')';
1410          }
1411        }
1412        break;
1413      default:
1414      {
1415        die('Unknow condition');
1416        break;
1417      }
1418    }
1419  }
1420
1421  if (count($sql_list) > 0)
1422  {
1423    $sql = '('.implode(' AND ', $sql_list).')';
1424  }
1425  else
1426  {
1427    $sql = $force_one_condition ? '1 = 1' : '';
1428  }
1429
1430  if (isset($prefix_condition) and !empty($sql))
1431  {
1432    $sql = $prefix_condition.' '.$sql;
1433  }
1434
1435  return $sql;
1436}
1437
1438?>
Note: See TracBrowser for help on using the repository browser.