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

Last change on this file since 22005 was 22005, checked in by plg, 11 years ago

merge r21236 from branch 2.5 to trunk

bug 2861: avoid "invalid password" with manual upgrade and admin session expired

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