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

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

feature 2995: New email template
rewrite pwg_mail_group() and pwg_mail_notification_admins()
new function pwg_mail_admins()
add complete template management in pwg_mail()
TODO : font-size problem in Thunderbird

  • Property svn:eol-style set to LF
File size: 39.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24// validate_mail_address:
25//   o verifies whether the given mail address has the
26//     right format. ie someone@domain.com "someone" can contain ".", "-" or
27//     even "_". Exactly as "domain". The extension doesn't have to be
28//     "com". The mail address can also be empty.
29//   o check if address could be empty
30//   o check if address is not used by a other user
31// If the mail address doesn't correspond, an error message is returned.
32//
33function validate_mail_address($user_id, $mail_address)
34{
35  global $conf;
36
37  if (empty($mail_address) and
38      !($conf['obligatory_user_mail_address'] and
39      in_array(script_basename(), array('register', 'profile'))))
40  {
41    return '';
42  }
43
44  if ( !email_check_format($mail_address) )
45  {
46    return l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
47  }
48
49  if (defined("PHPWG_INSTALLED") and !empty($mail_address))
50  {
51    $query = '
52SELECT count(*)
53FROM '.USERS_TABLE.'
54WHERE upper('.$conf['user_fields']['email'].') = upper(\''.$mail_address.'\')
55'.(is_numeric($user_id) ? 'AND '.$conf['user_fields']['id'].' != \''.$user_id.'\'' : '').'
56;';
57    list($count) = pwg_db_fetch_row(pwg_query($query));
58    if ($count != 0)
59    {
60      return l10n('this email address is already in use');
61    }
62  }
63}
64
65// validate_login_case:
66//   o check if login is not used by a other user
67// If the login doesn't correspond, an error message is returned.
68//
69function validate_login_case($login)
70{
71  global $conf;
72
73  if (defined("PHPWG_INSTALLED"))
74  {
75    $query = "
76SELECT ".$conf['user_fields']['username']."
77FROM ".USERS_TABLE."
78WHERE LOWER(".stripslashes($conf['user_fields']['username']).") = '".strtolower($login)."'
79;";
80
81    $count = pwg_db_num_rows(pwg_query($query));
82
83    if ($count > 0)
84    {
85      return l10n('this login is already used');
86    }
87  }
88}
89/**
90 * For test on username case sensitivity
91 *
92 * @param : $username typed in by user for identification
93 *
94 * @return : $username found in database
95 *
96 */
97function search_case_username($username)
98{
99  global $conf;
100
101  $username_lo = strtolower($username);
102
103  $SCU_users = array();
104
105  $q = pwg_query("
106    SELECT ".$conf['user_fields']['username']." AS username
107    FROM `".USERS_TABLE."`;
108  ");
109  while ($r = pwg_db_fetch_assoc($q))
110   $SCU_users[$r['username']] = strtolower($r['username']);
111   // $SCU_users is now an associative table where the key is the account as
112   // registered in the DB, and the value is this same account, in lower case
113
114  $users_found = array_keys($SCU_users, $username_lo);
115  // $users_found is now a table of which the values are all the accounts
116  // which can be written in lowercase the same way as $username
117  if (count($users_found) != 1) // If ambiguous, don't allow lowercase writing
118   return $username; // but normal writing will work
119  else
120   return $users_found[0];
121}
122
123/**
124 * create a new user
125 * @param string $login
126 * @param string $password
127 * @param string $mail_adress
128 * @param bool $notify_admin
129 * @param &array $errors
130 * @param bool $notify_user
131 * @return int|bool
132 */
133function register_user($login, $password, $mail_address, $notify_admin=true, &$errors = array(), $notify_user=false)
134{
135  global $conf;
136
137  if ($login == '')
138  {
139    $errors[] = l10n('Please, enter a login');
140  }
141  if (preg_match('/^.* $/', $login))
142  {
143    $errors[] = l10n('login mustn\'t end with a space character');
144  }
145  if (preg_match('/^ .*$/', $login))
146  {
147    $errors[] = l10n('login mustn\'t start with a space character');
148  }
149  if (get_userid($login))
150  {
151    $errors[] = l10n('this login is already used');
152  }
153  if ($login != strip_tags($login))
154  {
155    $errors[] = l10n('html tags are not allowed in login');
156  }
157  $mail_error = validate_mail_address(null, $mail_address);
158  if ('' != $mail_error)
159  {
160    $errors[] = $mail_error;
161  }
162
163  if ($conf['insensitive_case_logon'] == true)
164  {
165    $login_error = validate_login_case($login);
166    if ($login_error != '')
167    {
168      $errors[] = $login_error;
169    }
170  }
171
172  $errors = trigger_event(
173    'register_user_check',
174    $errors,
175    array(
176      'username'=>$login,
177      'password'=>$password,
178      'email'=>$mail_address,
179      )
180    );
181
182  // if no error until here, registration of the user
183  if (count($errors) == 0)
184  {
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      );
190
191    single_insert(USERS_TABLE, $insert);
192    $user_id = pwg_db_insert_id();
193
194    // Assign by default groups
195    $query = '
196SELECT id
197  FROM '.GROUPS_TABLE.'
198  WHERE is_default = \''.boolean_to_string(true).'\'
199  ORDER BY id ASC
200;';
201    $result = pwg_query($query);
202
203    $inserts = array();
204    while ($row = pwg_db_fetch_assoc($result))
205    {
206      $inserts[] = array(
207        'user_id' => $user_id,
208        'group_id' => $row['id']
209        );
210    }
211
212    if (count($inserts) != 0)
213    {
214      mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts);
215    }
216
217    $override = null;
218    if ($notify_admin and $conf['browser_language'])
219    {
220      if (!get_browser_language($override['language']))
221      {
222        $override=null;
223      }
224    }
225    create_user_infos($user_id, $override);
226
227    if ($notify_admin and $conf['email_admin_on_new_user'])
228    {
229      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
230      $admin_url = get_absolute_root_url().'admin.php?page=user_list&username='.$login;
231
232      $content = array(
233        l10n('User: %s', stripslashes($login) ),
234        l10n('Email: %s', $_POST['mail_address']),
235        '',
236        l10n('Admin: %s', $admin_url),
237        );
238
239      pwg_mail_notification_admins(
240        l10n('Registration of %s', stripslashes($login) ),
241        implode("\n", $content)
242        );
243    }
244
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',
273      array(
274        'id'=>$user_id,
275        'username'=>$login,
276        'email'=>$mail_address,
277        )
278      );
279     
280    return $user_id;
281  }
282  else
283  {
284    return false;
285  }
286}
287
288function build_user( $user_id, $use_cache )
289{
290  global $conf;
291
292  $user['id'] = $user_id;
293  $user = array_merge( $user, getuserdata($user_id, $use_cache) );
294
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
301  // Check user theme
302  if (!isset($user['theme_name']))
303  {
304    $user['theme'] = get_default_theme();
305  }
306
307  return $user;
308}
309
310/**
311 * find informations related to the user identifier
312 *
313 * @param int user identifier
314 * @param boolean use_cache
315 * @param array
316 */
317function getuserdata($user_id, $use_cache)
318{
319  global $conf;
320
321  // retrieve basic user data
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.'
340  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'';
341
342  $row = pwg_db_fetch_assoc(pwg_query($query));
343
344  // retrieve additional user data ?
345  if ($conf['external_authentification'])
346  {
347    $query = '
348SELECT
349    COUNT(1) AS counter
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;';
356    list($counter) = pwg_db_fetch_row(pwg_query($query));
357    if ($counter != 1)
358    {
359      create_user_infos($user_id);
360    }
361  }
362
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
378  // then merge basic + additional user data
379  $userdata = array_merge($row, $user_infos_row);
380
381  foreach ($userdata as &$value)
382  {
383      // If the field is true or false, the variable is transformed into a boolean value.
384      if ($value == 'true')
385      {
386        $value = true;
387      }
388      elseif ($value == 'false')
389      {
390        $value = false;
391      }
392  }
393  unset($value);
394
395  if ($use_cache)
396  {
397    if (!isset($userdata['need_update'])
398        or !is_bool($userdata['need_update'])
399        or $userdata['need_update'] == true)
400    {
401      $userdata['cache_update_time'] = time();
402
403      // Set need update are done
404      $userdata['need_update'] = false;
405
406      $userdata['forbidden_categories'] =
407        calculate_permissions($userdata['id'], $userdata['status']);
408
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      {
420        $forbidden_ids[] = 0;
421      }
422      $userdata['image_access_type'] = 'NOT IN'; //TODO maybe later
423      $userdata['image_access_list'] = implode(',',$forbidden_ids);
424
425
426      $query = '
427SELECT COUNT(DISTINCT(image_id)) as total
428  FROM '.IMAGE_CATEGORY_TABLE.'
429  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
430    AND image_id '.$userdata['image_access_type'].' ('.$userdata['image_access_list'].')';
431      list($userdata['nb_total_images']) = pwg_db_fetch_row(pwg_query($query));
432
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();
439        foreach ($user_cache_cats as $cat)
440        {
441          if ($cat['count_images']==0)
442          {
443            $forbidden_ids[] = $cat['cat_id'];
444            remove_computed_category($user_cache_cats, $cat);
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
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".
469      mass_inserts(
470        USER_CACHE_CATEGORIES_TABLE,
471        array(
472          'user_id', 'cat_id',
473          'date_last', 'max_date_last', 'nb_images', 'count_images', 'nb_categories', 'count_categories'
474          ),
475        $user_cache_cats,
476        array('ignore' => true)
477      );
478
479
480      // update user cache
481      $query = '
482DELETE FROM '.USER_CACHE_TABLE.'
483  WHERE user_id = '.$userdata['id'];
484      pwg_query($query);
485
486      // for the same reason as user_cache_categories, we ignore error on
487      // this insert
488      $query = '
489INSERT IGNORE INTO '.USER_CACHE_TABLE.'
490  (user_id, need_update, cache_update_time, forbidden_categories, nb_total_images,
491    last_photo_date,
492    image_access_type, image_access_list)
493  VALUES
494  ('.$userdata['id'].',\''.boolean_to_string($userdata['need_update']).'\','
495  .$userdata['cache_update_time'].',\''
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'].'\')';
499      pwg_query($query);
500    }
501  }
502
503  return $userdata;
504}
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  }
519
520  // $filter['visible_categories'] and $filter['visible_images']
521  // must be not used because filter <> restriction
522  // retrieving images allowed : belonging to at least one authorized
523  // category
524  $query = '
525SELECT DISTINCT f.image_id
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'].'
529'.get_sql_condition_FandF
530  (
531    array
532      (
533        'forbidden_categories' => 'ic.category_id',
534      ),
535    'AND'
536  ).'
537;';
538  $authorizeds = array_from_query($query, 'image_id');
539
540  $query = '
541SELECT image_id
542  FROM '.FAVORITES_TABLE.'
543  WHERE user_id = '.$user['id'].'
544;';
545  $favorites = array_from_query($query, 'image_id');
546
547  $to_deletes = array_diff($favorites, $authorizeds);
548  if (count($to_deletes) > 0)
549  {
550    $query = '
551DELETE FROM '.FAVORITES_TABLE.'
552  WHERE image_id IN ('.implode(',', $to_deletes).')
553    AND user_id = '.$user['id'].'
554;';
555    pwg_query($query);
556  }
557}
558
559/**
560 * calculates the list of forbidden categories for a given user
561 *
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)"
566 *
567 * @param int user_id
568 * @param string user_status
569 * @return string forbidden_categories
570 */
571function calculate_permissions($user_id, $user_status)
572{
573  $query = '
574SELECT id
575  FROM '.CATEGORIES_TABLE.'
576  WHERE status = \'private\'
577;';
578  $private_array = array_from_query($query, 'id');
579
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;';
586  $authorized_array = array_from_query($query, 'cat_id');
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;';
595  $authorized_array =
596    array_merge(
597      $authorized_array,
598      array_from_query($query, 'cat_id')
599      );
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
608  // if user is not an admin, locked categories are forbidden
609  if (!is_admin($user_status))
610  {
611    $query = '
612SELECT id
613  FROM '.CATEGORIES_TABLE.'
614  WHERE visible = \'false\'
615;';
616    $result = pwg_query($query);
617    while ($row = pwg_db_fetch_assoc($result))
618    {
619      $forbidden_array[] = $row['id'];
620    }
621    $forbidden_array = array_unique($forbidden_array);
622  }
623
624  if ( empty($forbidden_array) )
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
627   // true.
628    $forbidden_array[] = 0;
629  }
630
631  return implode(',', $forbidden_array);
632}
633
634
635/*update counters with a category removal*/
636function remove_computed_category(&$cats, $cat)
637{
638  if ( isset( $cats[$cat['id_uppercat']] ) )
639  {
640    $parent = & $cats[ $cat['id_uppercat'] ];
641    $parent['nb_categories']--;
642
643    do
644    {
645
646      $parent['count_images'] -= $cat['nb_images'];
647      $parent['count_categories'] -= 1+$cat['count_categories'];
648
649      if ( !isset( $cats[$parent['id_uppercat']] ) )
650        break;
651      $parent = & $cats[$parent['id_uppercat']];
652    }
653    while (true);
654  }
655
656  unset($cats[$cat['cat_id']]);
657}
658
659/**
660 * get computed array of categories
661 *
662 * @param array userdata
663 * @param int filter_days number of recent days to filter on or null
664 * @return array
665 */
666function get_computed_categories(&$userdata, $filter_days=null)
667{
668  $query = 'SELECT c.id AS cat_id, id_uppercat';
669  // Count by date_available to avoid count null
670  $query .= ',
671  MAX(date_available) AS date_last, COUNT(date_available) AS nb_images
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) )
679  {
680    $query .= ' AND i.date_available > '.pwg_db_get_recent_period_expression($filter_days);
681  }
682
683  if ( !empty($userdata['forbidden_categories']) )
684  {
685    $query.= '
686  WHERE c.id NOT IN ('.$userdata['forbidden_categories'].')';
687  }
688
689  $query.= '
690  GROUP BY c.id';
691
692  $result = pwg_query($query);
693
694  $userdata['last_photo_date'] = null;
695  $cats = array();
696  while ($row = pwg_db_fetch_assoc($result))
697  {
698    $row['user_id'] = $userdata['id'];
699    $row['nb_categories'] = 0;
700    $row['count_categories'] = 0;
701    $row['count_images'] = (int)$row['nb_images'];
702    $row['max_date_last'] = $row['date_last'];
703    if ($row['date_last'] > $userdata['last_photo_date'])
704    {
705      $userdata['last_photo_date'] = $row['date_last'];
706    }
707
708    $cats[$row['cat_id']] = $row;
709  }
710
711  foreach ($cats as $cat)
712  {
713    if ( !isset( $cat['id_uppercat'] ) )
714      continue;
715
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
737  if ( isset($filter_days) )
738  {
739    foreach ($cats as $category)
740    {
741      if (empty($category['max_date_last']))
742      {
743        remove_computed_category($cats, $category);
744      }
745    }
746  }
747  return $cats;
748}
749
750/**
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
760  $username = pwg_db_real_escape_string($username);
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
769  if (pwg_db_num_rows($result) == 0)
770  {
771    return false;
772  }
773  else
774  {
775    list($user_id) = pwg_db_fetch_row($result);
776    return $user_id;
777  }
778}
779
780function get_userid_by_email($email)
781{
782  global $conf;
783
784  $email = pwg_db_real_escape_string($email);
785
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
805/*
806 * Returns a array with default user value
807 *
808 * @param convert_str allows to convert string value if necessary
809 */
810function get_default_user_info($convert_str = true)
811{
812  global $cache, $conf;
813
814  if (!isset($cache['default_user']))
815  {
816    $query = '
817SELECT *
818  FROM '.USER_INFOS_TABLE.'
819  WHERE user_id = '.$conf['default_user_id'].'
820;';
821
822    $result = pwg_query($query);
823
824    if (pwg_db_num_rows($result) > 0)
825    {
826      $cache['default_user'] = pwg_db_fetch_assoc($result);
827
828      unset($cache['default_user']['user_id']);
829      unset($cache['default_user']['status']);
830      unset($cache['default_user']['registration_date']);
831    }
832    else
833    {
834      $cache['default_user'] = false;
835    }
836  }
837
838  if (is_array($cache['default_user']) and $convert_str)
839  {
840    $default_user = $cache['default_user'];
841    foreach ($default_user as &$value)
842    {
843      // If the field is true or false, the variable is transformed into a boolean value.
844      if ($value == 'true')
845      {
846        $value = true;
847      }
848      elseif ($value == 'false')
849      {
850        $value = false;
851      }
852    }
853    return $default_user;
854  }
855  else
856  {
857    return $cache['default_user'];
858  }
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);
870  if ($default_user === false or empty($default_user[$value_name]))
871  {
872    return $sos_value;
873  }
874  else
875  {
876   return $default_user[$value_name];
877  }
878}
879
880/*
881 * Returns the default template value
882 *
883 */
884function get_default_theme()
885{
886  $theme = get_default_user_value('theme', PHPWG_DEFAULT_TEMPLATE);
887  if (check_theme_installed($theme))
888  {
889    return $theme;
890  }
891
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  {
896    return $theme_id;
897  }
898}
899
900/*
901 * Returns the default language value
902 *
903 */
904function get_default_language()
905{
906  return get_default_user_value('language', PHPWG_DEFAULT_LANGUAGE);
907}
908
909/**
910  * Returns true if the browser language value is set into param $lang
911  *
912  */
913function get_browser_language(&$lang)
914{
915  $browser_language = substr(@$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
916  foreach (get_languages() as $language_code => $language_name)
917  {
918    if (substr($language_code, 0, 2) == $browser_language)
919    {
920      $lang = $language_code;
921      return true;
922    }
923  }
924  return false;
925}
926
927/**
928 * add user informations based on default values
929 *
930 * @param int user_id / array of user_if
931 * @param array of values used to override default user values
932 */
933function create_user_infos($arg_id, $override_values = null)
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();
944    if (is_numeric($arg_id))
945    {
946      $user_ids[] = $arg_id;
947    }
948  }
949
950  if (!empty($user_ids))
951  {
952    $inserts = array();
953    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
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
962    if (!is_null($override_values))
963    {
964      $default_user = array_merge($default_user, $override_values);
965    }
966
967    foreach ($user_ids as $user_id)
968    {
969      $level= isset($default_user['level']) ? $default_user['level'] : 0;
970      if ($user_id == $conf['webmaster_id'])
971      {
972        $status = 'webmaster';
973        $level = max( $conf['available_permission_levels'] );
974      }
975      else if (($user_id == $conf['guest_id']) or
976               ($user_id == $conf['default_user_id']))
977      {
978        $status = 'guest';
979      }
980      else
981      {
982        $status = 'normal';
983      }
984
985      $insert = array_merge(
986        $default_user,
987        array(
988          'user_id' => $user_id,
989          'status' => $status,
990          'registration_date' => $dbnow,
991          'level' => $level
992          ));
993
994      $inserts[] = $insert;
995    }
996
997    mass_inserts(USER_INFOS_TABLE, array_keys($inserts[0]), $inserts);
998  }
999}
1000
1001/**
1002 * returns the auto login key or false on error
1003 * @param int user_id
1004 * @param time_t time
1005 * @param string [out] username
1006*/
1007function calculate_auto_login_key($user_id, $time, &$username)
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);
1016  if (pwg_db_num_rows($result) > 0)
1017  {
1018    $row = pwg_db_fetch_assoc($result);
1019    $username = stripslashes($row['username']);
1020    $data = $time.$user_id.$username;
1021    $key = base64_encode( hash_hmac('sha1', $data, $conf['secret_key'].$row['password'],true) );
1022    return $key;
1023  }
1024  return false;
1025}
1026
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{
1035  global $conf, $user;
1036
1037  if ($remember_me and $conf['authorize_remembering'])
1038  {
1039    $now = time();
1040    $key = calculate_auto_login_key($user_id, $now, $username);
1041    if ($key!==false)
1042    {
1043      $cookie = $user_id.'-'.$now.'-'.$key;
1044      if (version_compare(PHP_VERSION, '5.2', '>=') )
1045      {
1046        setcookie($conf['remember_me_name'],
1047            $cookie,
1048            time()+$conf['remember_me_length'],
1049            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure'),
1050            ini_get('session.cookie_httponly')
1051          );
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      }
1061    }
1062  }
1063  else
1064  { // make sure we clean any remember me ...
1065    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
1066  }
1067  if ( session_id()!="" )
1068  { // we regenerate the session for security reasons
1069    // see http://www.acros.si/papers/session_fixation.pdf
1070    session_regenerate_id(true);
1071  }
1072  else
1073  {
1074    session_start();
1075  }
1076  $_SESSION['pwg_uid'] = (int)$user_id;
1077
1078  $user['id'] = $_SESSION['pwg_uid'];
1079  trigger_action('user_login', $user['id']);
1080}
1081
1082/*
1083 * Performs auto-connexion when cookie remember_me exists
1084 * @return true/false
1085*/
1086function auto_login() {
1087  global $conf;
1088
1089  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
1090  {
1091    $cookie = explode('-', stripslashes($_COOKIE[$conf['remember_me_name']]));
1092    if ( count($cookie)===3
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*/ )
1097    {
1098      $key = calculate_auto_login_key( $cookie[0], $cookie[1], $username );
1099      if ($key!==false and $key===$cookie[2])
1100      {
1101        log_user($cookie[0], true);
1102        trigger_action('login_success', stripslashes($username));
1103        return true;
1104      }
1105    }
1106    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
1107  }
1108  return false;
1109}
1110
1111/**
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');
1126
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  }
1132
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
1150  // If the password has not been hashed with the current algorithm.
1151  if (strpos('$P', $hash) !== 0)
1152  {
1153    if (!empty($conf['pass_convert']))
1154    {
1155      $check = ($hash == $conf['pass_convert']($password));
1156    }
1157    else
1158    {
1159      $check = ($hash == md5($password));
1160    }
1161
1162    if ($check)
1163    {
1164      if (!isset($user_id) or $conf['external_authentification'])
1165      {
1166        return true;
1167      }
1168     
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');
1185
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/**
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{
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{
1206  if ($success===true)
1207  {
1208    return true;
1209  }
1210
1211  // we force the session table to be clean
1212  pwg_session_gc();
1213
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.'
1220  WHERE '.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\'
1221;';
1222  $row = pwg_db_fetch_assoc(pwg_query($query));
1223  if ($conf['password_verify']($password, $row['password'], $row['id']))
1224  {
1225    log_user($row['id'], $remember_me);
1226    trigger_action('login_success', stripslashes($username));
1227    return true;
1228  }
1229  trigger_action('login_failure', stripslashes($username));
1230  return false;
1231}
1232
1233/** Performs all the cleanup on user logout */
1234function logout_user()
1235{
1236  global $conf;
1237
1238  trigger_action('user_logout', @$_SESSION['pwg_uid']);
1239
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
1250/*
1251 * Return user status used in this library
1252 * @return string
1253*/
1254function get_user_status($user_status)
1255{
1256  global $user;
1257
1258  if (empty($user_status))
1259  {
1260    if (isset($user['status']))
1261    {
1262      $user_status = $user['status'];
1263    }
1264    else
1265    {
1266      // swicth to default value
1267      $user_status = '';
1268    }
1269  }
1270  return $user_status;
1271}
1272
1273/*
1274 * Return access_type definition of user
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))
1283  {
1284    case 'guest':
1285    {
1286      $access_type_status =
1287        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_FREE);
1288      break;
1289    }
1290    case 'generic':
1291    {
1292      $access_type_status = ACCESS_GUEST;
1293      break;
1294    }
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    }
1310    default:
1311    {
1312      $access_type_status = ACCESS_FREE;
1313      break;
1314    }
1315  }
1316
1317  return $access_type_status;
1318}
1319
1320/*
1321 * Return if user have access to access_type definition
1322 * Test does with user status
1323 * @return bool
1324*/
1325function is_autorize_status($access_type, $user_status = '')
1326{
1327  return (get_access_type_status($user_status) >= $access_type);
1328}
1329
1330/*
1331 * Check if user have access to access_type definition
1332 * Stop action if there are not access
1333 * Test does with user status
1334 * @return none
1335*/
1336function check_status($access_type, $user_status = '')
1337{
1338  if (!is_autorize_status($access_type, $user_status))
1339  {
1340    access_denied();
1341  }
1342}
1343
1344/*
1345 * Return if user is generic
1346 * @return bool
1347*/
1348 function is_generic($user_status = '')
1349{
1350  return get_user_status($user_status) == 'generic';
1351}
1352
1353/*
1354 * Return if user is only a guest
1355 * @return bool
1356*/
1357 function is_a_guest($user_status = '')
1358{
1359  return get_user_status($user_status) == 'guest';
1360}
1361
1362/*
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*/
1375 function is_admin($user_status = '')
1376{
1377  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
1378}
1379
1380/*
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/*
1390 * Adviser status is depreciated from piwigo 2.2
1391 * @return false
1392*/
1393function is_adviser()
1394{
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);
1398  return false;
1399}
1400
1401/*
1402 * Return if current user can edit/delete/validate a comment
1403 * @param action edit/delete/validate
1404 * @return bool
1405 */
1406function can_manage_comment($action, $comment_author_id)
1407{
1408  global $user, $conf;
1409
1410  if (is_a_guest())
1411  {
1412    return false;
1413  }
1414
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;
1440}
1441
1442/*
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
1450  if (!isset($email_address) or (trim($email_address) == ''))
1451  {
1452    return '';
1453  }
1454  else
1455  {
1456    return $email_address;
1457  }
1458}
1459
1460/*
1461 * Compute sql where condition with restrict and filter data. "FandF" means
1462 * Forbidden and Filters.
1463 *
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"
1467 *
1468 * @return string sql where/conditions
1469 */
1470function get_sql_condition_FandF(
1471  $condition_fields,
1472  $prefix_condition = null,
1473  $force_one_condition = false
1474  )
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':
1485      {
1486        if (!empty($user['forbidden_categories']))
1487        {
1488          $sql_list[] =
1489            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
1490        }
1491        break;
1492      }
1493      case 'visible_categories':
1494      {
1495        if (!empty($filter['visible_categories']))
1496        {
1497          $sql_list[] =
1498            $field_name.' IN ('.$filter['visible_categories'].')';
1499        }
1500        break;
1501      }
1502      case 'visible_images':
1503        if (!empty($filter['visible_images']))
1504        {
1505          $sql_list[] =
1506            $field_name.' IN ('.$filter['visible_images'].')';
1507        }
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          }
1528          elseif ( !empty($user['image_access_list']) and !empty($user['image_access_type']) )
1529          {
1530            $sql_list[]=$field_name.' '.$user['image_access_type']
1531                .' ('.$user['image_access_list'].')';
1532          }
1533        }
1534        break;
1535      default:
1536      {
1537        die('Unknow condition');
1538        break;
1539      }
1540    }
1541  }
1542
1543  if (count($sql_list) > 0)
1544  {
1545    $sql = '('.implode(' AND ', $sql_list).')';
1546  }
1547  else
1548  {
1549    $sql = $force_one_condition ? '1 = 1' : '';
1550  }
1551
1552  if (isset($prefix_condition) and !empty($sql))
1553  {
1554    $sql = $prefix_condition.' '.$sql;
1555  }
1556
1557  return $sql;
1558}
1559
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
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
1596?>
Note: See TracBrowser for help on using the repository browser.