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

Last change on this file since 2297 was 2297, checked in by plg, 16 years ago

Modification: new header on PHP files, PhpWebGallery renamed Piwigo.

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