source: extensions/Ldap_Login/functions_user.inc.php @ 20461

Last change on this file since 20461 was 19261, checked in by 22decembre, 11 years ago

premier envoi des fichiers

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