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

Last change on this file since 3445 was 3445, checked in by nikrou, 15 years ago

Feature 1026 : Modify / delete comments for users

+ update config table content
+ minor modification of Sylvia theme
+ need refactoring

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