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

Last change on this file since 2362 was 2325, checked in by rub, 16 years ago

Resolved issue 0000823: Enhance upload functionalities

First commit, others will be follow.
Not hesitate to change my translations.

Add upload configuration tabsheet (move and add configuration)
Change and add define for access level
Can show upload link every time
Can restrict access upload.class.php
Can choice category on upload page
Add upload class not use for the moment
Review quickly and temporary style of upload.tpl

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