source: tags/release-2_0_0RC3/include/functions_user.inc.php @ 20987

Last change on this file since 20987 was 2572, checked in by rvelices, 16 years ago
  • removed #debug css rule (why would we need that in default-layout?)
  • order by rank is not available in calendar/chronology mode
  • small non-functional change in functions_search.inc.php (handy for plugin)
  • unused variables/smaller code/unused params in func call
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 32.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      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('reg_err_mail_address');
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) = mysql_fetch_array(pwg_query($query));
62    if ($count != 0)
63    {
64      return l10n('reg_err_mail_address_dbl');
65    }
66  }
67}
68
69function register_user($login, $password, $mail_address,
70  $with_notification = true, $errors = array())
71{
72  global $conf;
73
74  if ($login == '')
75  {
76    array_push($errors, l10n('reg_err_login1'));
77  }
78  if (ereg("^.* $", $login))
79  {
80    array_push($errors, l10n('reg_err_login2'));
81  }
82  if (ereg("^ .*$", $login))
83  {
84    array_push($errors, l10n('reg_err_login3'));
85  }
86  if (get_userid($login))
87  {
88    array_push($errors, l10n('reg_err_login5'));
89  }
90  $mail_error = validate_mail_address(null, $mail_address);
91  if ('' != $mail_error)
92  {
93    array_push($errors, $mail_error);
94  }
95
96  $errors = trigger_event('register_user_check',
97              $errors,
98              array(
99                'username'=>$login,
100                'password'=>$password,
101                'email'=>$mail_address,
102              )
103            );
104
105  // if no error until here, registration of the user
106  if (count($errors) == 0)
107  {
108    // what will be the inserted id ?
109    $query = '
110SELECT MAX('.$conf['user_fields']['id'].') + 1
111  FROM '.USERS_TABLE.'
112;';
113    list($next_id) = mysql_fetch_array(pwg_query($query));
114
115    $insert =
116      array(
117        $conf['user_fields']['id'] => $next_id,
118        $conf['user_fields']['username'] => mysql_escape_string($login),
119        $conf['user_fields']['password'] => $conf['pass_convert']($password),
120        $conf['user_fields']['email'] => $mail_address
121        );
122
123    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
124    mass_inserts(USERS_TABLE, array_keys($insert), array($insert));
125
126    // Assign by default groups
127    {
128      $query = '
129SELECT id
130  FROM '.GROUPS_TABLE.'
131  WHERE is_default = \''.boolean_to_string(true).'\'
132  ORDER BY id ASC
133;';
134      $result = pwg_query($query);
135
136      $inserts = array();
137      while ($row = mysql_fetch_array($result))
138      {
139        array_push
140        (
141          $inserts,
142          array
143          (
144            'user_id' => $next_id,
145            'group_id' => $row['id']
146          )
147        );
148      }
149    }
150
151    if (count($inserts) != 0)
152    {
153      include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
154      mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts);
155    }
156
157    $override = null;
158    if ($with_notification and $conf['browser_language'])
159    {
160      if ( !get_browser_language($override['language']) )
161        $override=null;
162    }
163    create_user_infos($next_id, $override);
164
165    if ($with_notification and $conf['email_admin_on_new_user'])
166    {
167      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
168      $admin_url = get_absolute_root_url()
169                   .'admin.php?page=user_list&username='.$login;
170
171      $keyargs_content = array
172      (
173        get_l10n_args('User: %s', $login),
174        get_l10n_args('Email: %s', $_POST['mail_address']),
175        get_l10n_args('', ''),
176        get_l10n_args('Admin: %s', $admin_url)
177      );
178
179      pwg_mail_notification_admins
180      (
181        get_l10n_args('Registration of %s', $login),
182        $keyargs_content
183      );
184    }
185
186    trigger_action('register_user',
187      array(
188        'id'=>$next_id,
189        'username'=>$login,
190        'email'=>$mail_address,
191       )
192      );
193  }
194
195  return $errors;
196}
197
198function build_user( $user_id, $use_cache )
199{
200  global $conf;
201
202  $user['id'] = $user_id;
203  $user = array_merge( $user, getuserdata($user_id, $use_cache) );
204
205  if ($user['id'] == $conf['guest_id'] and $user['status'] <> 'guest')
206  {
207    $user['status'] = 'guest';
208    $user['internal_status']['guest_must_be_guest'] = true;
209  }
210
211  // calculation of the number of picture to display per page
212  $user['nb_image_page'] = $user['nb_image_line'] * $user['nb_line_page'];
213
214  if (is_admin($user['status']))
215  {
216    list($user['admin_template'], $user['admin_theme']) =
217      explode ('/', $conf['admin_layout']);
218  }
219
220  list($user['template'], $user['theme']) = explode('/', $user['template']);
221
222  return $user;
223}
224
225/**
226 * find informations related to the user identifier
227 *
228 * @param int user identifier
229 * @param boolean use_cache
230 * @param array
231 */
232function getuserdata($user_id, $use_cache)
233{
234  global $conf;
235
236  $userdata = array();
237
238  $query = '
239SELECT ';
240  $is_first = true;
241  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
242  {
243    if ($is_first)
244    {
245      $is_first = false;
246    }
247    else
248    {
249      $query.= '
250     , ';
251    }
252    $query.= $dbfield.' AS '.$pwgfield;
253  }
254  $query.= '
255  FROM '.USERS_TABLE.'
256  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'
257;';
258
259  $row = mysql_fetch_array(pwg_query($query));
260
261  while (true)
262  {
263    $query = '
264SELECT ui.*, uc.*
265  FROM '.USER_INFOS_TABLE.' AS ui LEFT JOIN '.USER_CACHE_TABLE.' AS uc
266    ON ui.user_id = uc.user_id
267  WHERE ui.user_id = \''.$user_id.'\'
268;';
269    $result = pwg_query($query);
270    if (mysql_num_rows($result) > 0)
271    {
272      break;
273    }
274    else
275    {
276      create_user_infos($user_id);
277    }
278  }
279
280  $row = array_merge($row, mysql_fetch_array($result));
281
282  foreach ($row as $key => $value)
283  {
284    if (!is_numeric($key))
285    {
286      // If the field is true or false, the variable is transformed into a
287      // boolean value.
288      if ($value == 'true' or $value == 'false')
289      {
290        $userdata[$key] = get_boolean($value);
291      }
292      else
293      {
294        $userdata[$key] = $value;
295      }
296    }
297  }
298
299  if ($use_cache)
300  {
301    if (!isset($userdata['need_update'])
302        or !is_bool($userdata['need_update'])
303        or $userdata['need_update'] == true)
304    {
305      $userdata['cache_update_time'] = time();
306
307      // Set need update are done
308      $userdata['need_update'] = false;
309
310      $userdata['forbidden_categories'] =
311        calculate_permissions($userdata['id'], $userdata['status']);
312
313      /* now we build the list of forbidden images (this list does not contain
314      images that are not in at least an authorized category)*/
315      $query = '
316SELECT DISTINCT(id)
317  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
318  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
319    AND level>'.$userdata['level'];
320      $forbidden_ids = array_from_query($query, 'id');
321
322      if ( empty($forbidden_ids) )
323      {
324        array_push( $forbidden_ids, 0 );
325      }
326      $userdata['image_access_type'] = 'NOT IN'; //TODO maybe later
327      $userdata['image_access_list'] = implode(',',$forbidden_ids);
328
329      update_user_cache_categories($userdata);
330
331      $query = '
332SELECT COUNT(DISTINCT(image_id)) as total
333  FROM '.IMAGE_CATEGORY_TABLE.'
334  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
335    AND image_id '.$userdata['image_access_type'].' ('.$userdata['image_access_list'].')
336;';
337      list($userdata['nb_total_images']) = mysql_fetch_array(pwg_query($query));
338
339      // update user cache
340      $query = '
341DELETE FROM '.USER_CACHE_TABLE.'
342  WHERE user_id = '.$userdata['id'].'
343;';
344      pwg_query($query);
345
346      $query = '
347INSERT INTO '.USER_CACHE_TABLE.'
348  (user_id, need_update, cache_update_time, forbidden_categories, nb_total_images,
349    image_access_type, image_access_list)
350  VALUES
351  ('.$userdata['id'].',\''.boolean_to_string($userdata['need_update']).'\','
352  .$userdata['cache_update_time'].',\''
353  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].',"'
354  .$userdata['image_access_type'].'","'.$userdata['image_access_list'].'")
355;';
356      pwg_query($query);
357    }
358  }
359
360  return $userdata;
361}
362
363/*
364 * deletes favorites of the current user if he's not allowed to see them
365 *
366 * @return void
367 */
368function check_user_favorites()
369{
370  global $user;
371
372  if ($user['forbidden_categories'] == '')
373  {
374    return;
375  }
376
377  // $filter['visible_categories'] and $filter['visible_images']
378  // must be not used because filter <> restriction
379  // retrieving images allowed : belonging to at least one authorized
380  // category
381  $query = '
382SELECT DISTINCT f.image_id
383  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
384    ON f.image_id = ic.image_id
385  WHERE f.user_id = '.$user['id'].'
386'.get_sql_condition_FandF
387  (
388    array
389      (
390        'forbidden_categories' => 'ic.category_id',
391      ),
392    'AND'
393  ).'
394;';
395  $result = pwg_query($query);
396  $authorizeds = array();
397  while ($row = mysql_fetch_array($result))
398  {
399    array_push($authorizeds, $row['image_id']);
400  }
401
402  $query = '
403SELECT image_id
404  FROM '.FAVORITES_TABLE.'
405  WHERE user_id = '.$user['id'].'
406;';
407  $result = pwg_query($query);
408  $favorites = array();
409  while ($row = mysql_fetch_array($result))
410  {
411    array_push($favorites, $row['image_id']);
412  }
413
414  $to_deletes = array_diff($favorites, $authorizeds);
415
416  if (count($to_deletes) > 0)
417  {
418    $query = '
419DELETE FROM '.FAVORITES_TABLE.'
420  WHERE image_id IN ('.implode(',', $to_deletes).')
421    AND user_id = '.$user['id'].'
422;';
423    pwg_query($query);
424  }
425}
426
427/**
428 * calculates the list of forbidden categories for a given user
429 *
430 * Calculation is based on private categories minus categories authorized to
431 * the groups the user belongs to minus the categories directly authorized
432 * to the user. The list contains at least -1 to be compliant with queries
433 * such as "WHERE category_id NOT IN ($forbidden_categories)"
434 *
435 * @param int user_id
436 * @param string user_status
437 * @return string forbidden_categories
438 */
439function calculate_permissions($user_id, $user_status)
440{
441  $private_array = array();
442  $authorized_array = array();
443
444  $query = '
445SELECT id
446  FROM '.CATEGORIES_TABLE.'
447  WHERE status = \'private\'
448;';
449  $result = pwg_query($query);
450  while ($row = mysql_fetch_array($result))
451  {
452    array_push($private_array, $row['id']);
453  }
454
455  // retrieve category ids directly authorized to the user
456  $query = '
457SELECT cat_id
458  FROM '.USER_ACCESS_TABLE.'
459  WHERE user_id = '.$user_id.'
460;';
461  $authorized_array = array_from_query($query, 'cat_id');
462
463  // retrieve category ids authorized to the groups the user belongs to
464  $query = '
465SELECT cat_id
466  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
467    ON ug.group_id = ga.group_id
468  WHERE ug.user_id = '.$user_id.'
469;';
470  $authorized_array =
471    array_merge(
472      $authorized_array,
473      array_from_query($query, 'cat_id')
474      );
475
476  // uniquify ids : some private categories might be authorized for the
477  // groups and for the user
478  $authorized_array = array_unique($authorized_array);
479
480  // only unauthorized private categories are forbidden
481  $forbidden_array = array_diff($private_array, $authorized_array);
482
483  // if user is not an admin, locked categories are forbidden
484  if (!is_admin($user_status))
485  {
486    $query = '
487SELECT id
488  FROM '.CATEGORIES_TABLE.'
489  WHERE visible = \'false\'
490;';
491    $result = pwg_query($query);
492    while ($row = mysql_fetch_array($result))
493    {
494      array_push($forbidden_array, $row['id']);
495    }
496    $forbidden_array = array_unique($forbidden_array);
497  }
498
499  if ( empty($forbidden_array) )
500  {// at least, the list contains 0 value. This category does not exists so
501   // where clauses such as "WHERE category_id NOT IN(0)" will always be
502   // true.
503    array_push($forbidden_array, 0);
504  }
505
506  return implode(',', $forbidden_array);
507}
508
509/**
510 * compute data of categories branches (one branch only)
511 */
512function compute_branch_cat_data(&$cats, &$list_cat_id, &$level, &$ref_level)
513{
514  $date = '';
515  $count_images = 0;
516  $count_categories = 0;
517  do
518  {
519    $cat_id = array_pop($list_cat_id);
520    if (!is_null($cat_id))
521    {
522      // Count images and categories
523      $cats[$cat_id]['count_images'] += $count_images;
524      $cats[$cat_id]['count_categories'] += $count_categories;
525      $count_images = $cats[$cat_id]['count_images'];
526      $count_categories = $cats[$cat_id]['count_categories'] + 1;
527
528      if ((empty($cats[$cat_id]['max_date_last'])) or ($cats[$cat_id]['max_date_last'] < $date))
529      {
530        $cats[$cat_id]['max_date_last'] = $date;
531      }
532      else
533      {
534        $date = $cats[$cat_id]['max_date_last'];
535      }
536      $ref_level = substr_count($cats[$cat_id]['global_rank'], '.') + 1;
537    }
538    else
539    {
540      $ref_level = 0;
541    }
542  } while ($level <= $ref_level);
543
544  // Last cat updating must be added to list for next branch
545  if ($ref_level <> 0)
546  {
547    array_push($list_cat_id, $cat_id);
548  }
549}
550
551/**
552 * compute data of categories branches
553 */
554function compute_categories_data(&$cats)
555{
556  $ref_level = 0;
557  $level = 0;
558  $list_cat_id = array();
559
560  foreach ($cats as $id => $category)
561  {
562    // Compute
563    $level = substr_count($category['global_rank'], '.') + 1;
564    if ($level > $ref_level)
565    {
566      array_push($list_cat_id, $id);
567    }
568    else
569    {
570      compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
571      array_push($list_cat_id, $id);
572    }
573    $ref_level = $level;
574  }
575
576  $level = 1;
577  compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
578}
579
580/**
581 * get computed array of categories
582 *
583 * @param array userdata
584 * @param int filter_days number of recent days to filter on or null
585 * @return array
586 */
587function get_computed_categories($userdata, $filter_days=null)
588{
589  $query = 'SELECT c.id cat_id, global_rank';
590  // Count by date_available to avoid count null
591  $query .= ',
592  MAX(date_available) date_last, COUNT(date_available) nb_images
593FROM '.CATEGORIES_TABLE.' as c
594  LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
595  LEFT JOIN '.IMAGES_TABLE.' AS i
596    ON ic.image_id = i.id
597      AND i.level<='.$userdata['level'];
598
599  if ( isset($filter_days) )
600  {
601    $query .= ' AND i.date_available > SUBDATE(CURRENT_DATE,INTERVAL '.$filter_days.' DAY)';
602  }
603
604  if ( !empty($userdata['forbidden_categories']) )
605  {
606    $query.= '
607  WHERE c.id NOT IN ('.$userdata['forbidden_categories'].')';
608  }
609
610  $query.= '
611  GROUP BY c.id';
612
613  $result = pwg_query($query);
614
615  $cats = array();
616  while ($row = mysql_fetch_assoc($result))
617  {
618    $row['user_id'] = $userdata['id'];
619    $row['count_categories'] = 0;
620    $row['count_images'] = (int)$row['nb_images'];
621    $row['max_date_last'] = $row['date_last'];
622
623    $cats += array($row['cat_id'] => $row);
624  }
625  usort($cats, 'global_rank_compare');
626
627  compute_categories_data($cats);
628
629  if ( isset($filter_days) )
630  {
631    $cat_tmp = $cats;
632    $cats = array();
633
634    foreach ($cat_tmp as $category)
635    {
636      if (!empty($category['max_date_last']))
637      {
638        // Re-init counters
639        $category['count_categories'] = 0;
640        $category['count_images'] = (int)$category['nb_images'];
641        // Keep category
642        $cats[$category['cat_id']] = $category;
643      }
644    }
645    // Compute a second time
646    compute_categories_data($cats);
647  }
648  return $cats;
649}
650
651/**
652 * update data of user_cache_categories
653 *
654 * @param array userdata
655 * @return null
656 */
657function update_user_cache_categories($userdata)
658{
659  // delete user cache
660  $query = '
661DELETE FROM '.USER_CACHE_CATEGORIES_TABLE.'
662  WHERE user_id = '.$userdata['id'].'
663;';
664  pwg_query($query);
665
666  $cats = get_computed_categories($userdata, null);
667
668  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
669  mass_inserts
670  (
671    USER_CACHE_CATEGORIES_TABLE,
672    array
673    (
674      'user_id', 'cat_id',
675      'date_last', 'max_date_last', 'nb_images', 'count_images', 'count_categories'
676    ),
677    $cats
678  );
679}
680
681/**
682 * returns the username corresponding to the given user identifier if exists
683 *
684 * @param int user_id
685 * @return mixed
686 */
687function get_username($user_id)
688{
689  global $conf;
690
691  $query = '
692SELECT '.$conf['user_fields']['username'].'
693  FROM '.USERS_TABLE.'
694  WHERE '.$conf['user_fields']['id'].' = '.intval($user_id).'
695;';
696  $result = pwg_query($query);
697  if (mysql_num_rows($result) > 0)
698  {
699    list($username) = mysql_fetch_row($result);
700  }
701  else
702  {
703    return false;
704  }
705
706  return $username;
707}
708
709/**
710 * returns user identifier thanks to his name, false if not found
711 *
712 * @param string username
713 * @param int user identifier
714 */
715function get_userid($username)
716{
717  global $conf;
718
719  $username = mysql_escape_string($username);
720
721  $query = '
722SELECT '.$conf['user_fields']['id'].'
723  FROM '.USERS_TABLE.'
724  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
725;';
726  $result = pwg_query($query);
727
728  if (mysql_num_rows($result) == 0)
729  {
730    return false;
731  }
732  else
733  {
734    list($user_id) = mysql_fetch_row($result);
735    return $user_id;
736  }
737}
738
739/**
740 * search an available feed_id
741 *
742 * @return string feed identifier
743 */
744function find_available_feed_id()
745{
746  while (true)
747  {
748    $key = generate_key(50);
749    $query = '
750SELECT COUNT(*)
751  FROM '.USER_FEED_TABLE.'
752  WHERE id = \''.$key.'\'
753;';
754    list($count) = mysql_fetch_row(pwg_query($query));
755    if (0 == $count)
756    {
757      return $key;
758    }
759  }
760}
761
762/*
763 * Returns a array with default user value
764 *
765 * @param convert_str allows to convert string value if necessary
766 */
767function get_default_user_info($convert_str = true)
768{
769  global $page, $conf;
770
771  if (!isset($page['cache_default_user']))
772  {
773    $query = 'select * from '.USER_INFOS_TABLE.
774            ' where user_id = '.$conf['default_user_id'].';';
775
776    $result = pwg_query($query);
777    $page['cache_default_user'] = mysql_fetch_assoc($result);
778
779    if ($page['cache_default_user'] !== false)
780    {
781      unset($page['cache_default_user']['user_id']);
782      unset($page['cache_default_user']['status']);
783      unset($page['cache_default_user']['registration_date']);
784    }
785  }
786
787  if (is_array($page['cache_default_user']) and $convert_str)
788  {
789    $default_user = array();
790    foreach ($page['cache_default_user'] as $name => $value)
791    {
792      // If the field is true or false, the variable is transformed into a
793      // boolean value.
794      if ($value == 'true' or $value == 'false')
795      {
796        $default_user[$name] = get_boolean($value);
797      }
798      else
799      {
800        $default_user[$name] = $value;
801      }
802    }
803    return $default_user;
804  }
805  else
806  {
807    return $page['cache_default_user'];
808  }
809}
810
811/*
812 * Returns a default user value
813 *
814 * @param value_name: name of value
815 * @param sos_value: value used if don't exist value
816 */
817function get_default_user_value($value_name, $sos_value)
818{
819  $default_user = get_default_user_info(true);
820  if ($default_user === false or !isset($default_user[$value_name]))
821  {
822    return $sos_value;
823  }
824  else
825  {
826   return $default_user[$value_name];
827  }
828}
829
830/*
831 * Returns the default template value
832 *
833 */
834function get_default_template()
835{
836  return get_default_user_value('template', PHPWG_DEFAULT_TEMPLATE);
837}
838
839/*
840 * Returns the default language value
841 *
842 */
843function get_default_language()
844{
845  return get_default_user_value('language', PHPWG_DEFAULT_LANGUAGE);
846}
847
848/**
849  * Returns true if the browser language value is set into param $lang
850  *
851  */
852function get_browser_language(&$lang)
853{
854  $browser_language = substr(@$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
855  foreach (get_languages() as $language_code => $language_name)
856  {
857    if (substr($language_code, 0, 2) == $browser_language)
858    {
859      $lang = $language_code;
860      return true;
861    }
862  }
863  return false;
864}
865
866/**
867 * add user informations based on default values
868 *
869 * @param int user_id / array of user_if
870 * @param array of values used to override default user values
871 */
872function create_user_infos($arg_id, $override_values = null)
873{
874  global $conf;
875
876  if (is_array($arg_id))
877  {
878    $user_ids = $arg_id;
879  }
880  else
881  {
882    $user_ids = array();
883    if (is_numeric($arg_id))
884    {
885      $user_ids[] = $arg_id;
886    }
887  }
888
889  if (!empty($user_ids))
890  {
891    $inserts = array();
892    list($dbnow) = mysql_fetch_row(pwg_query('SELECT NOW();'));
893
894    $default_user = get_default_user_info(false);
895    if ($default_user === false)
896    {
897      // Default on structure are used
898      $default_user = array();
899    }
900
901    if (!is_null($override_values))
902    {
903      $default_user = array_merge($default_user, $override_values);
904    }
905
906    foreach ($user_ids as $user_id)
907    {
908      $level= isset($default_user['level']) ? $default_user['level'] : 0;
909      if ($user_id == $conf['webmaster_id'])
910      {
911        $status = 'webmaster';
912        $level = max( $conf['available_permission_levels'] );
913      }
914      else if (($user_id == $conf['guest_id']) or
915               ($user_id == $conf['default_user_id']))
916      {
917        $status = 'guest';
918      }
919      else
920      {
921        $status = 'normal';
922      }
923
924      $insert = array_merge(
925        $default_user,
926        array(
927          'user_id' => $user_id,
928          'status' => $status,
929          'registration_date' => $dbnow,
930          'level' => $level
931          ));
932
933      array_push($inserts, $insert);
934    }
935
936    include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
937    mass_inserts(USER_INFOS_TABLE, array_keys($inserts[0]), $inserts);
938
939  }
940}
941
942/**
943 * returns the groupname corresponding to the given group identifier if
944 * exists
945 *
946 * @param int group_id
947 * @return mixed
948 */
949function get_groupname($group_id)
950{
951  $query = '
952SELECT name
953  FROM '.GROUPS_TABLE.'
954  WHERE id = '.intval($group_id).'
955;';
956  $result = pwg_query($query);
957  if (mysql_num_rows($result) > 0)
958  {
959    list($groupname) = mysql_fetch_row($result);
960  }
961  else
962  {
963    return false;
964  }
965
966  return $groupname;
967}
968
969
970/**
971 * returns the auto login key or false on error
972 * @param int user_id
973 * @param time_t time
974 * @param string [out] username
975*/
976function calculate_auto_login_key($user_id, $time, &$username)
977{
978  global $conf;
979  $query = '
980SELECT '.$conf['user_fields']['username'].' AS username
981  , '.$conf['user_fields']['password'].' AS password
982FROM '.USERS_TABLE.'
983WHERE '.$conf['user_fields']['id'].' = '.$user_id;
984  $result = pwg_query($query);
985  if (mysql_num_rows($result) > 0)
986  {
987    $row = mysql_fetch_assoc($result);
988    $username = $row['username'];
989    $data = $time.$row['username'].$row['password'];
990    $key = base64_encode(
991      pack('H*', sha1($data))
992      .hash_hmac('md5', $data, $conf['secret_key'],true)
993      );
994    return $key;
995  }
996  return false;
997}
998
999/*
1000 * Performs all required actions for user login
1001 * @param int user_id
1002 * @param bool remember_me
1003 * @return void
1004*/
1005function log_user($user_id, $remember_me)
1006{
1007  global $conf, $user;
1008
1009  if ($remember_me and $conf['authorize_remembering'])
1010  {
1011    $now = time();
1012    $key = calculate_auto_login_key($user_id, $now, $username);
1013    if ($key!==false)
1014    {
1015      $cookie = $user_id.'-'.$now.'-'.$key;
1016      setcookie($conf['remember_me_name'],
1017            $cookie,
1018            time()+$conf['remember_me_length'],
1019            cookie_path()
1020          );
1021    }
1022  }
1023  else
1024  { // make sure we clean any remember me ...
1025    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1026  }
1027  if ( session_id()!="" )
1028  { // we regenerate the session for security reasons
1029    // see http://www.acros.si/papers/session_fixation.pdf
1030    session_regenerate_id();
1031  }
1032  else
1033  {
1034    session_start();
1035  }
1036  $_SESSION['pwg_uid'] = (int)$user_id;
1037
1038  $user['id'] = $_SESSION['pwg_uid'];
1039}
1040
1041/*
1042 * Performs auto-connexion when cookie remember_me exists
1043 * @return true/false
1044*/
1045function auto_login() {
1046  global $conf;
1047
1048  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
1049  {
1050    $cookie = explode('-', stripslashes($_COOKIE[$conf['remember_me_name']]));
1051    if ( count($cookie)===3
1052        and is_numeric(@$cookie[0]) /*user id*/
1053        and is_numeric(@$cookie[1]) /*time*/
1054        and time()-$conf['remember_me_length']<=@$cookie[1]
1055        and time()>=@$cookie[1] /*cookie generated in the past*/ )
1056    {
1057      $key = calculate_auto_login_key( $cookie[0], $cookie[1], $username );
1058      if ($key!==false and $key===$cookie[2])
1059      {
1060        log_user($cookie[0], true);
1061        trigger_action('login_success', $username);
1062        return true;
1063      }
1064    }
1065    setcookie($conf['remember_me_name'], '', 0, cookie_path());
1066  }
1067  return false;
1068}
1069
1070/**
1071 * Tries to login a user given username and password (must be MySql escaped)
1072 * return true on success
1073 */
1074function try_log_user($username, $password, $remember_me)
1075{
1076  global $conf;
1077  // retrieving the encrypted password of the login submitted
1078  $query = '
1079SELECT '.$conf['user_fields']['id'].' AS id,
1080       '.$conf['user_fields']['password'].' AS password
1081  FROM '.USERS_TABLE.'
1082  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
1083;';
1084  $row = mysql_fetch_assoc(pwg_query($query));
1085  if ($row['password'] == $conf['pass_convert']($password))
1086  {
1087    log_user($row['id'], $remember_me);
1088    trigger_action('login_success', $username);
1089    return true;
1090  }
1091  trigger_action('login_failure', $username);
1092  return false;
1093}
1094
1095/*
1096 * Return user status used in this library
1097 * @return string
1098*/
1099function get_user_status($user_status)
1100{
1101  global $user;
1102
1103  if (empty($user_status))
1104  {
1105    if (isset($user['status']))
1106    {
1107      $user_status = $user['status'];
1108    }
1109    else
1110    {
1111      // swicth to default value
1112      $user_status = '';
1113    }
1114  }
1115  return $user_status;
1116}
1117
1118/*
1119 * Return access_type definition of user
1120 * Test does with user status
1121 * @return bool
1122*/
1123function get_access_type_status($user_status='')
1124{
1125  global $conf;
1126
1127  switch (get_user_status($user_status))
1128  {
1129    case 'guest':
1130    {
1131      $access_type_status =
1132        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_FREE);
1133      break;
1134    }
1135    case 'generic':
1136    {
1137      $access_type_status = ACCESS_GUEST;
1138      break;
1139    }
1140    case 'normal':
1141    {
1142      $access_type_status = ACCESS_CLASSIC;
1143      break;
1144    }
1145    case 'admin':
1146    {
1147      $access_type_status = ACCESS_ADMINISTRATOR;
1148      break;
1149    }
1150    case 'webmaster':
1151    {
1152      $access_type_status = ACCESS_WEBMASTER;
1153      break;
1154    }
1155    default:
1156    {
1157      $access_type_status = ACCESS_FREE;
1158      break;
1159    }
1160  }
1161
1162  return $access_type_status;
1163}
1164
1165/*
1166 * Return if user have access to access_type definition
1167 * Test does with user status
1168 * @return bool
1169*/
1170function is_autorize_status($access_type, $user_status = '')
1171{
1172  return (get_access_type_status($user_status) >= $access_type);
1173}
1174
1175/*
1176 * Check if user have access to access_type definition
1177 * Stop action if there are not access
1178 * Test does with user status
1179 * @return none
1180*/
1181function check_status($access_type, $user_status = '')
1182{
1183  if (!is_autorize_status($access_type, $user_status))
1184  {
1185    access_denied();
1186  }
1187}
1188
1189/*
1190 * Return if user is generic
1191 * @return bool
1192*/
1193 function is_generic($user_status = '')
1194{
1195  return get_user_status($user_status) == 'generic';
1196}
1197
1198/*
1199 * Return if user is only a guest
1200 * @return bool
1201*/
1202 function is_a_guest($user_status = '')
1203{
1204  return get_user_status($user_status) == 'guest';
1205}
1206
1207/*
1208 * Return if user is, at least, a classic user
1209 * @return bool
1210*/
1211 function is_classic_user($user_status = '')
1212{
1213  return is_autorize_status(ACCESS_CLASSIC, $user_status);
1214}
1215
1216/*
1217 * Return if user is, at least, an administrator
1218 * @return bool
1219*/
1220 function is_admin($user_status = '')
1221{
1222  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
1223}
1224
1225/*
1226 * Return if current user is an adviser
1227 * @return bool
1228*/
1229function is_adviser()
1230{
1231  global $user;
1232
1233  return ($user['adviser'] == 'true');
1234}
1235
1236/*
1237 * Return mail address as display text
1238 * @return string
1239*/
1240function get_email_address_as_display_text($email_address)
1241{
1242  global $conf;
1243
1244  if (!isset($email_address) or (trim($email_address) == ''))
1245  {
1246    return '';
1247  }
1248  else
1249  {
1250    if (defined('IN_ADMIN') and is_adviser())
1251    {
1252      return 'adviser.mode@'.$_SERVER['SERVER_NAME'];
1253    }
1254    else
1255    {
1256      return $email_address;
1257    }
1258  }
1259}
1260
1261/*
1262 * Compute sql where condition with restrict and filter data. "FandF" means
1263 * Forbidden and Filters.
1264 *
1265 * @param array condition_fields: read function body
1266 * @param string prefix_condition: prefixes sql if condition is not empty
1267 * @param boolean force_one_condition: use at least "1 = 1"
1268 *
1269 * @return string sql where/conditions
1270 */
1271function get_sql_condition_FandF(
1272  $condition_fields,
1273  $prefix_condition = null,
1274  $force_one_condition = false
1275  )
1276{
1277  global $user, $filter;
1278
1279  $sql_list = array();
1280
1281  foreach ($condition_fields as $condition => $field_name)
1282  {
1283    switch($condition)
1284    {
1285      case 'forbidden_categories':
1286      {
1287        if (!empty($user['forbidden_categories']))
1288        {
1289          $sql_list[] =
1290            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
1291        }
1292        break;
1293      }
1294      case 'visible_categories':
1295      {
1296        if (!empty($filter['visible_categories']))
1297        {
1298          $sql_list[] =
1299            $field_name.' IN ('.$filter['visible_categories'].')';
1300        }
1301        break;
1302      }
1303      case 'visible_images':
1304        if (!empty($filter['visible_images']))
1305        {
1306          $sql_list[] =
1307            $field_name.' IN ('.$filter['visible_images'].')';
1308        }
1309        // note there is no break - visible include forbidden
1310      case 'forbidden_images':
1311        if (
1312            !empty($user['image_access_list'])
1313            or $user['image_access_type']!='NOT IN'
1314            )
1315        {
1316          $table_prefix=null;
1317          if ($field_name=='id')
1318          {
1319            $table_prefix = '';
1320          }
1321          elseif ($field_name=='i.id')
1322          {
1323            $table_prefix = 'i.';
1324          }
1325          if ( isset($table_prefix) )
1326          {
1327            $sql_list[]=$table_prefix.'level<='.$user['level'];
1328          }
1329          else
1330          {
1331            $sql_list[]=$field_name.' '.$user['image_access_type']
1332                .' ('.$user['image_access_list'].')';
1333          }
1334        }
1335        break;
1336      default:
1337      {
1338        die('Unknow condition');
1339        break;
1340      }
1341    }
1342  }
1343
1344  if (count($sql_list) > 0)
1345  {
1346    $sql = '('.implode(' AND ', $sql_list).')';
1347  }
1348  else
1349  {
1350    if ($force_one_condition)
1351    {
1352      $sql = '1 = 1';
1353    }
1354    else
1355    {
1356      $sql = '';
1357    }
1358  }
1359
1360  if (isset($prefix_condition) and !empty($sql))
1361  {
1362    $sql = $prefix_condition.' '.$sql;
1363  }
1364
1365  return $sql;
1366}
1367
1368?>
Note: See TracBrowser for help on using the repository browser.