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

Last change on this file since 25601 was 25360, checked in by mistic100, 11 years ago

feature 2995: New email template
restore get_l10n_args removed at r25357
apply changes to NBM

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