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

Last change on this file since 27158 was 27158, checked in by mistic100, 10 years ago

remove PHP < 5.2 code

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