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

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