source: extensions/NBC_UserAdvManager/trunk/include/functions.inc.php @ 8087

Last change on this file since 8087 was 8087, checked in by Eric, 13 years ago

Pre Branch 2.16 modifications in trunk:

  • Automation of user cleanup and downgrade tasks step 2
  • Property svn:eol-style set to LF
File size: 55.6 KB
Line 
1<?php
2include_once (UAM_PATH.'include/constants.php');
3load_language('plugin.lang', UAM_PATH);
4
5/**
6 * Triggered on get_admin_plugin_menu_links
7 *
8 * Plugin's administration menu
9 */
10function UAM_admin_menu($menu)
11{
12// +-----------------------------------------------------------------------+
13// |                      Getting plugin name                              |
14// +-----------------------------------------------------------------------+
15  $plugin =  PluginInfos(UAM_PATH);
16  $name = $plugin['name'];
17 
18  array_push($menu,
19    array(
20      'NAME' => $name,
21      'URL'  => get_admin_plugin_menu_link(UAM_PATH.'/admin/UAM_admin.php')
22    )
23  );
24
25  return $menu;
26}
27
28/**
29 * Triggered on loc_begin_index
30 *
31 * Initiating GhostTracker
32 */
33function UAM_GhostTracker()
34{
35  global $conf, $user;
36
37  $conf_UAM = unserialize($conf['UserAdvManager']);
38
39  // Admins, Guests and Adult_Content users are not tracked for Ghost Tracker or Users Tracker
40  if (!is_admin() and !is_a_guest() and $user['username'] != "16" and $user['username'] != "18")
41  {
42    if ((isset($conf_UAM[16]) and $conf_UAM[16] == 'true') or (isset($conf_UAM[19]) and $conf_UAM[19] == 'true'))
43    {
44
45      $userid = get_userid($user['username']);
46         
47      // Looking for existing entry in last visit table
48      $query = '
49SELECT *
50FROM '.USER_LASTVISIT_TABLE.'
51WHERE user_id = '.$userid.'
52;';
53       
54      $count = pwg_db_num_rows(pwg_query($query));
55         
56      if ($count == 0)
57      {
58        // If not, data are inserted in table
59        $query = '
60INSERT INTO '.USER_LASTVISIT_TABLE.' (user_id, lastvisit, reminder)
61VALUES ('.$userid.', now(), "false")
62;';
63        pwg_query($query);
64      }
65      else if ($count > 0)
66      {
67        // If yes, data are updated in table
68        $query = '
69UPDATE '.USER_LASTVISIT_TABLE.'
70SET lastvisit = now(), reminder = "false"
71WHERE user_id = '.$userid.'
72LIMIT 1
73;';
74        pwg_query($query);
75      }
76    }
77  }
78}
79
80/**
81 * Triggered on register_user
82 *
83 * Additional controls on user registration
84 */
85function UAM_Adduser($register_user)
86{
87  global $conf;
88
89  $conf_UAM = unserialize($conf['UserAdvManager']);
90
91  // Exclusion of Adult_Content users
92  if ($register_user['username'] != "16" and $register_user['username'] != "18")
93  {
94    if ((isset($conf_UAM[0]) and $conf_UAM[0] == 'true') and (isset($conf_UAM[1]) and $conf_UAM[1] == 'local'))
95    {
96      // This is to send an information email and set user to "waiting" group or status until admin validation
97      $passwd = (isset($_POST['password'])) ? $_POST['password'] : '';
98      SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], false);
99      setgroup($register_user['id']);// Set to "waiting" group or status until admin validation
100    }
101    elseif ((isset($conf_UAM[0]) and $conf_UAM[0] == 'false') and (isset($conf_UAM[1]) and $conf_UAM[1] == 'local'))
102    {
103      // This is to set user to "waiting" group or status until admin validation
104      setgroup($register_user['id']);// Set to "waiting" group or status until admin validation
105    }
106    elseif ((isset($conf_UAM[0]) and $conf_UAM[0] == 'true') and (isset($conf_UAM[1]) and $conf_UAM[1] == 'false'))
107    {
108      // This is to send an information email without validation key
109      $passwd = (isset($_POST['password'])) ? $_POST['password'] : '';
110      SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], false);
111    }
112    // Sending registration confirmation by email
113    elseif ((isset($conf_UAM[0]) and $conf_UAM[0] == 'true' or $conf_UAM[0] == 'false') and (isset($conf_UAM[1]) and $conf_UAM[1] == 'true'))
114    {
115      if (is_admin() and isset($conf_UAM[20]) and $conf_UAM[20] == 'true')
116      {
117        $passwd = (isset($_POST['password'])) ? $_POST['password'] : '';
118        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], true); 
119      }
120      elseif (is_admin() and isset($conf_UAM[20]) and $conf_UAM[20] == 'false')
121      {
122        $passwd = (isset($_POST['password'])) ? $_POST['password'] : '';
123        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], false);
124      }
125      elseif (!is_admin())
126      {
127        $passwd = (isset($_POST['password'])) ? $_POST['password'] : '';
128        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], true);
129      }
130    }
131  }
132}
133
134/**
135 * Triggered on delete_user
136 *
137 * Database cleanup on user deletion
138 */
139function UAM_Deluser($user_id)
140{
141  // Cleanup for ConfirmMail table
142  DeleteConfirmMail($user_id);
143  // Cleanup for LastVisit table
144  DeleteLastVisit($user_id);
145  // Cleanup Redirection settings
146  DeleteRedir($user_id);
147}
148
149/**
150 * Triggered on register_user_check
151 *
152 * Additional controls on user registration check
153 */
154function UAM_RegistrationCheck($errors, $user)
155{
156  global $conf;
157
158  // Exclusion of Adult_Content users
159  if ($user['username'] != "16" and $user['username'] != "18")
160  {
161    load_language('plugin.lang', UAM_PATH);
162
163    $PasswordCheck = 0;
164
165    $conf_UAM = unserialize($conf['UserAdvManager']);
166
167    // Password enforcement control
168    if (isset($conf_UAM[13]) and $conf_UAM[13] == 'true' and !empty($conf_UAM[14]))
169    {
170      if (!empty($user['password']) and !is_admin())
171      {
172        $PasswordCheck = testpassword($user['password']);
173 
174        if ($PasswordCheck < $conf_UAM[14])
175        {
176          $message = get_l10n_args('reg_err_login4_%s', $PasswordCheck);
177          $lang['reg_err_pass'] = l10n_args($message).$conf_UAM[14];
178          array_push($errors, $lang['reg_err_pass']);
179        }
180      }
181      else if (!empty($user['password']) and is_admin() and isset($conf_UAM[15]) and $conf_UAM[15] == 'true')
182      {
183        $PasswordCheck = testpassword($user['password']);
184 
185        if ($PasswordCheck < $conf_UAM[14])
186        {
187          $message = get_l10n_args('reg_err_login4_%s', $PasswordCheck);
188          $lang['reg_err_pass'] = l10n_args($message).$conf_UAM[14];
189          array_push($errors, $lang['reg_err_pass']);
190        }
191      }
192    }
193
194    // Username without forbidden keys
195    if (isset($conf_UAM[6]) and $conf_UAM[6] == 'true' and !empty($user['username']) and ValidateUsername($user['username']) and !is_admin())
196    {
197      $lang['reg_err_login1'] = l10n('reg_err_login6')."'".$conf_UAM[7]."'";
198      array_push($errors, $lang['reg_err_login1']);
199    }
200
201    // Email without forbidden domains
202    if (isset($conf_UAM[11]) and $conf_UAM[11] == 'true' and !empty($user['email']) and ValidateEmailProvider($user['email']) and !is_admin())
203    {
204      $lang['reg_err_login1'] = l10n('reg_err_login7')."'".$conf_UAM[12]."'";
205      array_push($errors, $lang['reg_err_login1']);
206    }
207    return $errors;
208  }
209}
210
211/**
212 * Triggered on loc_begin_profile
213 */
214function UAM_Profile_Init()
215{
216  global $conf, $user, $template;
217
218  $conf_UAM = unserialize($conf['UserAdvManager']);
219   
220  if ((isset($conf_UAM[21]) and $conf_UAM[21] == 'true'))
221  {
222    $user_idsOK = array();
223    if (!UAM_check_profile($user['id'], $user_idsOK))
224    {
225      $user_idsOK[] = $user['id'];
226
227      $query = "
228UPDATE ".CONFIG_TABLE."
229SET value = \"".implode(',', $user_idsOK)."\"
230WHERE param = 'UserAdvManager_Redir';";
231         
232      pwg_query($query);
233    }
234  }
235
236  if (isset($_POST['validate']) and !is_admin())
237  {
238    // Email without forbidden domains
239    if (isset($conf_UAM[11]) and $conf_UAM[11] == 'true' and !empty($_POST['mail_address']))
240    {
241      if (ValidateEmailProvider($_POST['mail_address']))
242      {
243        $template->append('errors', l10n('reg_err_login7')."'".$conf_UAM[12]."'");
244        unset($_POST['validate']);
245      }
246    }
247
248    $typemail = 3;
249
250    if (!empty($_POST['use_new_pwd']))
251    {
252      $typemail = 2;
253
254      // Password enforcement control
255      if (isset($conf_UAM[13]) and $conf_UAM[13] == 'true' and !empty($conf_UAM[14]))
256      {
257        $PasswordCheck = testpassword($_POST['use_new_pwd']);
258
259        if ($PasswordCheck < $conf_UAM[14])
260        {
261          $message = get_l10n_args('reg_err_login4_%s', $PasswordCheck);
262          $template->append('errors', l10n_args($message).$conf_UAM[14]);
263          unset($_POST['use_new_pwd']);
264          unset($_POST['validate']);
265        }
266      }
267    }
268
269    // Sending registration confirmation by email
270    if ((isset($conf_UAM[0]) and $conf_UAM[0] == 'true') or (isset($conf_UAM[1]) and $conf_UAM[1] == 'true') or (isset($conf_UAM[1]) and $conf_UAM[1] == 'local'))
271    {
272      $confirm_mail_need = false;
273
274      if (!empty($_POST['mail_address']))
275      {
276        $query = '
277SELECT '.$conf['user_fields']['email'].' AS email
278FROM '.USERS_TABLE.'
279WHERE '.$conf['user_fields']['id'].' = \''.$user['id'].'\'
280;';
281
282        list($current_email) = pwg_db_fetch_row(pwg_query($query));
283
284        // This is to send a new validation key
285        if ($_POST['mail_address'] != $current_email and (isset($conf_UAM[1]) and $conf_UAM[1] == 'true'))
286       
287          $confirm_mail_need = true;
288
289        // This is to set the user to "waiting" group or status until admin validation
290        if ($_POST['mail_address'] != $current_email and (isset($conf_UAM[1]) and $conf_UAM[1] == 'local'))
291       
292          setgroup($register_user['id']);// Set to "waiting" group or status until admin validation
293          $confirm_mail_need = false;
294      }
295       
296      if ((!empty($_POST['use_new_pwd']) and (isset($conf_UAM[0]) and $conf_UAM[0] == 'true') or $confirm_mail_need))
297      {
298        $query = '
299SELECT '.$conf['user_fields']['username'].'
300FROM '.USERS_TABLE.'
301WHERE '.$conf['user_fields']['id'].' = \''.$user['id'].'\'
302;';
303       
304        list($username) = pwg_db_fetch_row(pwg_query($query));
305        SendMail2User($typemail, $user['id'], $username, $_POST['use_new_pwd'], $_POST['mail_address'], $confirm_mail_need);
306      }
307    }
308  }
309}
310
311/**
312 * Triggered on login_success
313 *
314 * Triggers scheduled tasks at login
315 * Redirects a visitor (except for admins, webmasters and generic statuses) to his profile.php page (Thx to LucMorizur)
316 *
317 */
318function UAM_LoginTasks()
319{
320  global $conf, $user;
321 
322  $conf_UAM = unserialize($conf['UserAdvManager']);
323 
324  // Performing scheduled tasks
325  if ((isset($conf_UAM[22]) and $conf_UAM[22] == 'true'))
326  {
327    UAM_ScheduledTasks();
328  }
329
330  if ((isset($conf_UAM[21]) and $conf_UAM[21] == 'true'))
331  {
332    // Performing redirection 
333    $query ='
334SELECT user_id, status
335FROM '.USER_INFOS_TABLE.'
336WHERE user_id = '.$user['id'].'
337;';
338    $data = pwg_db_fetch_assoc(pwg_query($query));
339
340    if ($data['status'] <> "admin" and $data['status'] <> "webmaster" and $data['status'] <> "generic")
341    {
342      $user_idsOK = array();
343      if (!UAM_check_profile($user['id'], $user_idsOK))
344        redirect(PHPWG_ROOT_PATH.'profile.php');
345    }
346  }
347}
348
349/**
350 * Triggered on UAM_LoginTasks()
351 *
352 * Executes optional post-login tasks
353 *
354 */
355function UAM_ScheduledTasks()
356{
357  global $conf, $user, $page;
358 
359  $conf_UAM = unserialize($conf['UserAdvManager']);
360 
361  $collection = array();
362  $reminder = false;
363 
364  $page['filtered_users'] = get_ghosts_autotasks();
365
366  foreach($page['filtered_users'] as $listed_user)
367  {
368    array_push($collection, $listed_user['id']);
369  }
370
371  // Ghost accounts auto deletion
372  if ((isset($conf_UAM[22]) and $conf_UAM[22] == 'true') and (isset($conf_UAM[23]) and $conf_UAM[23] == 'true'))
373  {
374    if (count($collection) > 0)
375        {
376        if (in_array($user['id'], $collection))
377        {
378        invalidate_user_cache();
379       
380        foreach ($collection as $user_id)
381        {
382          delete_user($user_id);
383        }
384        logout_user();
385        redirect(UAM_PATH.'del_account.php');
386        }
387      else
388      {
389        foreach ($collection as $user_id)
390        {
391          delete_user($user_id);
392        }
393      }
394    }
395  }
396
397  // Ghost accounts auto group or status downgrade with or without information email sending and autodeletion if user already reminded
398  if ((isset($conf_UAM[22]) and $conf_UAM[22] == 'true') and (isset($conf_UAM[23]) and $conf_UAM[23] == 'false') and ((isset($conf_UAM[27]) and $conf_UAM[27] <> -1) or (isset($conf_UAM[28]) and $conf_UAM[28] <> -1)))
399  {
400    if (count($collection) > 0)
401        {
402      // Process if a non-admin nor webmaster user is logged
403      if (in_array($user['id'], $collection))
404        {
405        foreach ($collection as $user_id)
406        {
407          // Check lastvisit reminder state
408          $query = '
409SELECT reminder
410FROM '.USER_LASTVISIT_TABLE.'
411WHERE user_id = '.$user_id.';';
412
413          $result = pwg_db_fetch_assoc(pwg_query($query));
414
415          if (isset($result['reminder']) and $result['reminder'] == 'true')
416          {
417            $reminder = true;
418          }
419          else
420          {
421            $reminder = false;
422          }
423
424          // If never reminded before, set reminder True
425          if (!$reminder)
426          {
427            // Reset of lastvisit date
428            list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
429
430                        $query = "
431UPDATE ".USER_LASTVISIT_TABLE."
432SET lastvisit='".$dbnow."'
433WHERE user_id = '".$user_id."'
434;";
435            pwg_query($query);
436
437          // Auto change group and / or status
438            // Delete user from all groups
439            $query = "
440DELETE FROM ".USER_GROUP_TABLE."
441WHERE user_id = '".$user_id."'
442  AND (
443    group_id = '".$conf_UAM[2]."'
444  OR
445    group_id = '".$conf_UAM[3]."'
446  )
447;";
448
449            pwg_query($query);
450
451            // Change user status
452            if ($conf_UAM[28] <> -1)
453            {
454              $query = "
455UPDATE ".USER_INFOS_TABLE."
456SET status = '".$conf_UAM[28]."'
457WHERE user_id = '".$user_id."'
458;";
459              pwg_query($query);
460            }
461
462            // Change user group
463            if ($conf_UAM[27] <> -1)
464            {
465              $query = "
466INSERT INTO ".USER_GROUP_TABLE."
467  (user_id, group_id)
468VALUES
469  ('".$user_id."', '".$conf_UAM[27]."')
470;";
471              pwg_query($query);
472            }
473         
474            // Auto send email notification on group / status downgrade only if never reminded before
475            if (isset($conf_UAM[24]) and $conf_UAM[24] == 'true')
476            {
477              // Set reminder true
478              $query = "
479UPDATE ".USER_LASTVISIT_TABLE."
480SET reminder = 'true'
481WHERE user_id = '".$user_id."'
482;";
483              pwg_query($query);
484
485              // Reset confirmed user date_check
486              $query = '
487UPDATE '.USER_CONFIRM_MAIL_TABLE.'
488SET date_check = NULL
489WHERE user_id = "'.$user_id.'"
490;';
491                                                  pwg_query($query);
492
493              // Get users information for email notification
494                                                  $query = '
495SELECT username, mail_address
496FROM '.USERS_TABLE.'
497WHERE id = '.$user_id.'
498;';
499                                                  $data = pwg_db_fetch_assoc(pwg_query($query));
500           
501              demotion_mail($user_id, $data['username'], $data['mail_address']);
502            }
503          }
504          elseif ($reminder) // If user already reminded for ghost account
505          {
506            // delete account
507            delete_user($user_id);
508          }
509        }
510        // Logged-in user cleanup
511        invalidate_user_cache();
512        log_user($user['id'], false);
513        redirect(make_index_url());
514        }
515      else // Process if an admin or webmaster user is logged
516      {
517        foreach ($collection as $user_id)
518        {
519          // Check lastvisit reminder state
520          $query = '
521SELECT reminder
522FROM '.USER_LASTVISIT_TABLE.'
523WHERE user_id = '.$user_id.';';
524
525          $result = pwg_db_fetch_assoc(pwg_query($query));
526
527          if (isset($result['reminder']) and $result['reminder'] == 'true')
528          {
529            $reminder = true;
530          }
531          else
532          {
533            $reminder = false;
534          }
535
536          // If never reminded before
537          if (!$reminder)
538          {
539            // Reset of lastvisit date
540            list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
541
542                        $query = "
543UPDATE ".USER_LASTVISIT_TABLE."
544SET lastvisit='".$dbnow."'
545WHERE user_id = '".$user_id."'
546;";
547            pwg_query($query);
548
549          // Auto change group and / or status
550            // Delete user from all groups
551            $query = "
552DELETE FROM ".USER_GROUP_TABLE."
553WHERE user_id = '".$user_id."'
554  AND (
555    group_id = '".$conf_UAM[2]."'
556  OR
557    group_id = '".$conf_UAM[3]."'
558  )
559;";
560            pwg_query($query);
561
562            // Change user status
563            if ($conf_UAM[28] <> -1)
564            {
565              $query = "
566UPDATE ".USER_INFOS_TABLE."
567SET status = '".$conf_UAM[28]."'
568WHERE user_id = '".$user_id."'
569;";
570              pwg_query($query);
571            }
572
573            // Change user group
574            if ($conf_UAM[27] <> -1)
575            {
576              $query = "
577INSERT INTO ".USER_GROUP_TABLE."
578  (user_id, group_id)
579VALUES
580  ('".$user_id."', '".$conf_UAM[27]."')
581;";
582              pwg_query($query);
583            }
584
585            // Auto send email notification on group / status downgrade
586            if (isset($conf_UAM[24]) and $conf_UAM[24] == 'true')
587            {
588              // Set reminder true
589              $query = "
590UPDATE ".USER_LASTVISIT_TABLE."
591SET reminder = 'true'
592WHERE user_id = '".$user_id."'
593;";
594              pwg_query($query);
595           
596              // Reset confirmed user status to unvalidated
597                                                  $query = '
598UPDATE '.USER_CONFIRM_MAIL_TABLE.'
599SET date_check = NULL
600WHERE user_id = "'.$user_id.'"
601;';
602                                                  pwg_query($query);
603
604              // Get users information for email notification
605                                                  $query = '
606SELECT id, username, mail_address
607FROM '.USERS_TABLE.'
608WHERE id = '.$user_id.'
609;';
610                                                  $data = pwg_db_fetch_assoc(pwg_query($query));
611           
612              demotion_mail($user_id, $data['username'], $data['mail_address']);
613            }
614          }
615          elseif ($reminder) // If user already reminded for ghost account
616          {
617            // delete account
618            delete_user($user_id);
619          }
620        }
621      }
622    }
623  }
624}
625
626/**
627 * Triggered on init
628 *
629 * Check for forbidden email domains in admin's users management panel
630 */
631function UAM_InitPage()
632{
633  load_language('plugin.lang', UAM_PATH);
634  global $conf, $template, $page, $lang, $errors;
635
636  $conf_UAM = unserialize($conf['UserAdvManager']);
637
638// Admin user management
639  if (script_basename() == 'admin' and isset($_GET['page']) and $_GET['page'] == 'user_list')
640  {
641    if (isset($_POST['submit_add']))
642    {
643      // Email without forbidden domains
644      if (isset($conf_UAM[11]) and $conf_UAM[11] == 'true' and !empty($_POST['email']) and ValidateEmailProvider($_POST['email']))
645      {
646        $template->append('errors', l10n('reg_err_login7')."'".$conf_UAM[12]."'");
647        unset($_POST['submit_add']);
648      }
649    }
650  }
651}
652
653/**
654 * Triggered on user_comment_check
655 *
656 * checks if author is mandatory and set on comments post
657 *
658 * @param : comment action, comment
659 *
660 * @return : comment action
661 *
662 */
663function UAM_CheckEmptyCommentAuthor($comment_action, $comm)
664{
665  load_language('plugin.lang', UAM_PATH);
666  global $infos, $conf, $template;
667
668  $conf_UAM = unserialize($conf['UserAdvManager']);
669
670// User creation OR update
671  if (isset($conf_UAM[5]) and $conf_UAM[5] == 'true' and $conf['comments_forall'] == 'true' and $comm['author'] == 'guest')
672  {
673    $comment_action = 'reject';
674
675    array_push($infos, l10n('UAM_Empty Author'));
676  }
677
678  return $comment_action;
679}
680
681/**
682 * Function called from main.inc.php to send validation email
683 *
684 * @param : Type of email, user id, username, email address, confirmation (optional)
685 *
686 */
687function SendMail2User($typemail, $id, $username, $password, $email, $confirm)
688{
689  global $conf;
690
691  $conf_UAM = unserialize($conf['UserAdvManager']);
692 
693        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
694 
695        $infos1_perso = "";
696  $infos2_perso = "";
697
698// We have to get the user's language in database
699  $query ='
700SELECT user_id, language
701FROM '.USER_INFOS_TABLE.'
702WHERE user_id = '.$id.'
703;';
704  $data = pwg_db_fetch_assoc(pwg_query($query));
705
706// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
707  if (empty($data))
708  {
709// And switch gallery to this language before using personalized and multilangual contents
710    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
711    switch_lang_to($language);
712  }
713  else
714  {
715// And switch gallery to this language before using personalized and multilangual contents
716    $language = $data['language']; // Usefull for debugging
717    switch_lang_to($data['language']);
718    load_language('plugin.lang', UAM_PATH);
719  }
720
721  switch($typemail)
722  {
723    case 1:
724      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Add of %s', stripslashes($username)));
725      $password = $password <> '' ? $password : l10n('UAM_empty_pwd');
726     
727      if (isset($conf_UAM[9]) and $conf_UAM[9] <> '')
728      {
729        if (function_exists('get_user_language_desc'))
730        {
731          $infos1_perso = get_user_language_desc($conf_UAM[9])."\n\n";
732        }
733        else $infos1_perso = l10n($conf_UAM[9])."\n\n"; 
734      }
735     
736      break;
737     
738    case 2:
739      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Update of %s', stripslashes($username)));
740      $password = $password <> '' ? $password : l10n('UAM_empty_pwd');
741
742      break;
743       
744    case 3:
745      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Update of %s', stripslashes($username)));
746      $password = $password <> '' ? $password : l10n('UAM_no_update_pwd');
747
748      break;
749  }
750
751  if (isset($conf_UAM[0]) and $conf_UAM[0] == 'true')
752  {
753    $infos1 = array(
754      get_l10n_args('infos_mail %s', stripslashes($username)),
755      get_l10n_args('User: %s', stripslashes($username)),
756      get_l10n_args('Password: %s', $password),
757      get_l10n_args('Email: %s', $email),
758      get_l10n_args('', ''),
759    );
760  }
761
762
763  if ( isset($conf_UAM[1]) and $conf_UAM[1] == 'true' and $confirm)
764  {
765    $infos2 = array
766    (
767      get_l10n_args('Link: %s', AddConfirmMail($id, $email)),
768      get_l10n_args('', ''),
769    );
770
771    if (isset($conf_UAM[10]) and $conf_UAM[10] <> '')
772    {
773      if (function_exists('get_user_language_desc'))
774      {
775        $infos2_perso = get_user_language_desc($conf_UAM[10])."\n\n";
776      }
777      else $infos2_perso = l10n($conf_UAM[10])."\n\n";
778    }
779  }
780
781// ********************************************************
782// **** Pending code since to find how to make it work ****
783// ********************************************************
784// Testing if FCK Editor is used. Then decoding htmlchars to avoid problems with pwg_mail()
785/*$areas = array();
786array_push( $areas,'UAM_MailInfo_Text','UAM_ConfirmMail_Text');
787
788if (function_exists('set_fckeditor_instance'))
789{
790  $fcke_config = unserialize($conf['FCKEditor']);
791  foreach($areas as $area)
792  {
793    if (isset($fcke_config['UAM_MailInfo_Text']) and $fcke_config['UAM_MailInfo_Text'] = true)
794    {
795      $infos1_perso = html_entity_decode($infos1_perso,ENT_QUOTES,UTF-8);
796    }
797   
798    if (isset($fcke_config['UAM_ConfirmMail_Text']) and $fcke_config['UAM_ConfirmMail_Text'] = true)
799    {
800      $infos2_perso = html_entity_decode($infos2_perso,ENT_QUOTES,UTF-8);
801    }
802  }
803}*/
804
805
806// Sending the email with subject and contents
807  pwg_mail($email, array(
808    'subject' => $subject,
809    'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
810  ));
811
812// **********************
813// Email sending debugger
814// This is only to trace
815// the send of emails for
816// debugging             
817// **********************
818//$content = (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url();   
819//MailLog($email,$subject,$content,$language);
820// **********************
821
822// Switching back to default language
823switch_lang_back();
824}
825
826/**
827 * Function called from UAM_admin.php to resend validation email with or without new validation key
828 *
829 * @param : Type of email, user id, username, email address, confirmation (optional)
830 *
831 */
832function ResendMail2User($typemail, $user_id, $username, $email, $confirm)
833{
834  global $conf;
835
836  $conf_UAM = unserialize($conf['UserAdvManager']);
837
838  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
839 
840        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
841 
842// We have to get the user's language in database
843  $query ='
844SELECT user_id, language
845FROM '.USER_INFOS_TABLE.'
846WHERE user_id = '.$user_id.'
847;';
848  $data = pwg_db_fetch_assoc(pwg_query($query));
849  $language = $data['language'];
850 
851// And switch gallery to this language before using personalized and multilangual contents
852  switch_lang_to($data['language']);
853   
854  load_language('plugin.lang', UAM_PATH);
855
856  switch($typemail)
857  {
858    case 1:
859      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Reminder_with_key_of_%s', $username));
860     
861      if (isset($conf_UAM_ConfirmMail[2]) and $conf_UAM_ConfirmMail[2] <> '' and isset($conf_UAM_ConfirmMail[3]) and $conf_UAM_ConfirmMail[3] == 'true' and $confirm)
862      {
863        if (function_exists('get_user_language_desc'))
864        {
865          $infos1 = get_user_language_desc($conf_UAM_ConfirmMail[2])."\n\n";
866        }
867                                else $infos1 = l10n($conf_UAM_ConfirmMail[2])."\n\n";
868
869        $infos2 = array
870        (
871          get_l10n_args('Link: %s', ResetConfirmMail($user_id)),
872          get_l10n_args('', ''),
873        );       
874                        }
875
876// Set reminder true     
877      $query = "
878UPDATE ".USER_CONFIRM_MAIL_TABLE."
879SET reminder = 'true'
880WHERE user_id = '".$user_id."'
881;";
882      pwg_query($query);
883     
884                break;
885     
886    case 2:
887      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Reminder_without_key_of_%s',$username));
888     
889      if (isset($conf_UAM_ConfirmMail[2]) and $conf_UAM_ConfirmMail[2] <> '' and isset($conf_UAM_ConfirmMail[3]) and $conf_UAM_ConfirmMail[3] == 'true' and !$confirm)
890      {
891        if (function_exists('get_user_language_desc'))
892        {
893          $infos1 = get_user_language_desc($conf_UAM_ConfirmMail[2])."\n\n";
894        }
895        else $infos1 = l10n($conf_UAM_ConfirmMail[2])."\n\n";
896      }
897     
898// Set reminder true     
899      $query = "
900UPDATE ".USER_CONFIRM_MAIL_TABLE."
901SET reminder = 'true'
902WHERE user_id = '".$user_id."'
903;";
904      pwg_query($query);
905     
906    break;
907        }
908 
909  pwg_mail($email, array(
910    'subject' => $subject,
911    'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
912  ));
913
914// **********************
915// Email sending debugger
916// This is only to trace
917// the send of emails for
918// debugging             
919// **********************
920//$content = ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url();
921//MailLog($email,$subject,$content,$language);
922// **********************
923
924// Switching back to default language
925switch_lang_back();
926}
927
928/**
929 * Function called from UAM_admin.php to send a reminder mail for ghost users
930 *
931 * @param : User id, username, email address
932 *
933 */
934function ghostreminder($user_id, $username, $email)
935{
936  global $conf;
937
938  $conf_UAM = unserialize($conf['UserAdvManager']);
939 
940        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
941 
942        $infos1_perso = "";
943
944// We have to get the user's language in database
945  $query ='
946SELECT user_id, language
947FROM '.USER_INFOS_TABLE.'
948WHERE user_id = '.$user_id.'
949;';
950  $data = pwg_db_fetch_assoc(pwg_query($query));
951  $language = $data['language'];
952
953// And switch gallery to this language before using personalized and multilangual contents
954  switch_lang_to($data['language']);
955   
956  load_language('plugin.lang', UAM_PATH);
957 
958  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Ghost_reminder_of_%s', $username));     
959
960  if (isset($conf_UAM[18]) and $conf_UAM[18] <> '' and isset($conf_UAM[16]) and $conf_UAM[16] == 'true')
961  {
962    if (function_exists('get_user_language_desc'))
963    {
964      $infos1 = get_user_language_desc($conf_UAM[18])."\n\n";
965    }
966    else
967    {
968      $infos1 = l10n($conf_UAM[18])."\n\n";
969    }
970
971    resetlastvisit($user_id);
972  }
973
974  pwg_mail($email, array(
975    'subject' => $subject,
976    'content' => $infos1.get_absolute_root_url(),
977  ));
978
979// **********************
980// Email sending debugger
981// This is only to trace
982// the send of emails for
983// debugging             
984// **********************
985//$content = get_user_language_desc($conf_UAM[19])."\n\n"; 
986//MailLog($email,$subject,$content,$language);
987// **********************
988
989// Switching back to default language
990switch_lang_back();
991}
992
993/**
994 * Function called from functions.inc.php to send notification email when user have been downgraded
995 *
996 * @param : user id, username, email address, confirmation
997 *
998 */
999function demotion_mail($id, $username, $email)
1000{
1001  global $conf;
1002
1003  $conf_UAM = unserialize($conf['UserAdvManager']);
1004 
1005        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1006 
1007        $custom_txt = "";
1008
1009// We have to get the user's language in database
1010  $query ='
1011SELECT user_id, language
1012FROM '.USER_INFOS_TABLE.'
1013WHERE user_id = '.$id.'
1014;';
1015  $data = pwg_db_fetch_assoc(pwg_query($query));
1016
1017// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1018  if (empty($data))
1019  {
1020// And switch gallery to this language before using personalized and multilangual contents
1021    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1022    switch_lang_to($language);
1023  }
1024  else
1025  {
1026// And switch gallery to this language before using personalized and multilangual contents
1027    $language = $data['language']; // Usefull for debugging
1028    switch_lang_to($data['language']);
1029    load_language('plugin.lang', UAM_PATH);
1030  }
1031
1032  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('Demotion of %s', stripslashes($username)));
1033     
1034  if (isset($conf_UAM[26]) and $conf_UAM[26] <> '')
1035  {
1036    if (function_exists('get_user_language_desc'))
1037    {
1038      $custom_txt = get_user_language_desc($conf_UAM[26])."\n\n";
1039    }
1040    else $custom_txt = l10n($conf_UAM[26])."\n\n"; 
1041  }
1042
1043  $infos1 = array(
1044    get_l10n_args('User: %s', stripslashes($username)),
1045    get_l10n_args('Email: %s', $email),
1046    get_l10n_args('', ''),
1047  );
1048
1049  $infos2 = array
1050  (
1051    get_l10n_args('Link: %s', ResetConfirmMail($id)),
1052    get_l10n_args('', ''),
1053  ); 
1054
1055
1056// Sending the email with subject and contents
1057  pwg_mail($email, array(
1058    'subject' => $subject,
1059    'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url(),
1060  ));
1061
1062// **********************
1063// Email sending debugger
1064// This is only to trace
1065// the send of emails for
1066// debugging             
1067// **********************
1068//$content = ($infos1."\n\n".$infos2."\n\n").get_absolute_root_url();   
1069//MailLog($email,$subject,$content,$language);
1070// **********************
1071
1072// Switching back to default language
1073switch_lang_back();
1074}
1075
1076/**
1077 * Function called from functions AddConfirmMail and ResetConfirmMail for validation key generation
1078 *
1079 * @return : validation key
1080 *
1081 */
1082function FindAvailableConfirmMailID()
1083{
1084  while (true)
1085  {
1086    $id = generate_key(16);
1087    $query = "
1088SELECT COUNT(*)
1089  FROM ".USER_CONFIRM_MAIL_TABLE."
1090WHERE id = '".$id."'
1091;";
1092    list($count) = pwg_db_fetch_row(pwg_query($query));
1093
1094    if ($count == 0)
1095      return $id;
1096  }
1097}
1098
1099/**
1100 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
1101 *
1102 * @param : User id, email address
1103 *
1104 * @return : Build validation key in URL
1105 *
1106 */
1107function AddConfirmMail($user_id, $email)
1108{
1109  global $conf;
1110
1111  $conf_UAM = unserialize($conf['UserAdvManager']);
1112  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1113
1114  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1115 
1116  if (isset($Confirm_Mail_ID))
1117  {
1118    $query = "
1119SELECT status
1120  FROM ".USER_INFOS_TABLE."
1121WHERE user_id = '".$user_id."'
1122;";
1123    list($status) = pwg_db_fetch_row(pwg_query($query));
1124   
1125    $query = "
1126INSERT INTO ".USER_CONFIRM_MAIL_TABLE."
1127  (id, user_id, mail_address, status, date_check)
1128VALUES
1129  ('".$Confirm_Mail_ID."', '".$user_id."', '".$email."', '".$status."', null)
1130;";
1131    pwg_query($query);
1132
1133    // Delete user from all groups
1134    $query = "
1135DELETE FROM ".USER_GROUP_TABLE."
1136WHERE user_id = '".$user_id."'
1137  AND (
1138    group_id = '".$conf_UAM[2]."'
1139  OR
1140    group_id = '".$conf_UAM[3]."'
1141  )
1142;";
1143    pwg_query($query);
1144
1145    // Set user unvalidated status
1146    if (!is_admin() and $conf_UAM[8] <> -1)
1147    {
1148      $query = "
1149UPDATE ".USER_INFOS_TABLE."
1150SET status = '".$conf_UAM[8]."'
1151WHERE user_id = '".$user_id."'
1152;";
1153      pwg_query($query);
1154    }
1155
1156    // Set user unvalidated group
1157    if (!is_admin() and $conf_UAM[2] <> -1)
1158    {
1159      $query = "
1160INSERT INTO ".USER_GROUP_TABLE."
1161  (user_id, group_id)
1162VALUES
1163  ('".$user_id."', '".$conf_UAM[2]."')
1164;";
1165      pwg_query($query);
1166    }
1167   
1168    return get_absolute_root_url().UAM_PATH.'ConfirmMail.php?key='.$Confirm_Mail_ID.'&userid='.$user_id;
1169  }
1170}
1171
1172/**
1173 * Function called from main.inc.php to set group to new users if manual validation is set
1174 *
1175 * @param : User id
1176 *
1177 *
1178 */
1179function setgroup($user_id)
1180{
1181  global $conf;
1182 
1183  $conf_UAM = unserialize($conf['UserAdvManager']);
1184
1185  $query = "
1186DELETE FROM ".USER_GROUP_TABLE."
1187WHERE user_id = '".$user_id."'
1188  AND (
1189    group_id = '".$conf_UAM[2]."'
1190  OR
1191    group_id = '".$conf_UAM[3]."'
1192  )
1193;";
1194  pwg_query($query);
1195
1196  if (!is_admin() and $conf_UAM[8] <> -1)
1197  {
1198    $query = "
1199UPDATE ".USER_INFOS_TABLE."
1200SET status = '".$conf_UAM[8]."'
1201WHERE user_id = '".$user_id."'
1202;";
1203    pwg_query($query);
1204  }
1205
1206  if (!is_admin() and $conf_UAM[2] <> -1)
1207  {
1208    $query = "
1209INSERT INTO ".USER_GROUP_TABLE."
1210  (user_id, group_id)
1211VALUES
1212  ('".$user_id."', '".$conf_UAM[2]."')
1213;";
1214    pwg_query($query);
1215  }
1216}
1217
1218/**
1219 * Function called from UAM_admin.php to reset validation key
1220 *
1221 * @param : User id
1222 *
1223 * @return : Build validation key in URL
1224 *
1225 */
1226function ResetConfirmMail($user_id)
1227{
1228  global $conf;
1229 
1230  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1231
1232  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1233 
1234  if (isset($Confirm_Mail_ID))
1235  { 
1236    $query = "
1237UPDATE ".USER_CONFIRM_MAIL_TABLE."
1238SET id = '".$Confirm_Mail_ID."'
1239WHERE user_id = '".$user_id."'
1240;";
1241    pwg_query($query);
1242
1243                $query = "
1244UPDATE ".USER_INFOS_TABLE."
1245SET registration_date = '".$dbnow."'
1246WHERE user_id = '".$user_id."'
1247;";
1248                pwg_query($query);
1249   
1250    return get_absolute_root_url().UAM_PATH.'ConfirmMail.php?key='.$Confirm_Mail_ID.'&userid='.$user_id;
1251  }
1252}
1253
1254/**
1255 * Function called from functions.inc.php to reset last visit date after sending a reminder
1256 *
1257 * @param : User id
1258 *
1259 */
1260function resetlastvisit($user_id)
1261{
1262  global $conf;
1263
1264  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1265
1266  $query = "
1267UPDATE ".USER_LASTVISIT_TABLE."
1268SET lastvisit = '".$dbnow."', reminder = 'true'
1269WHERE user_id = '".$user_id."'
1270;";
1271  pwg_query($query);
1272}
1273
1274
1275/**
1276 * Function called from main.inc.php - Triggered on user deletion
1277 *
1278 */
1279function DeleteConfirmMail($user_id)
1280{
1281  $query = "
1282DELETE FROM ".USER_CONFIRM_MAIL_TABLE."
1283WHERE user_id = '".$user_id."'
1284;";
1285  pwg_query($query);
1286}
1287
1288/**
1289 * Function called from main.inc.php - Triggered on user deletion
1290 *
1291 */
1292function DeleteLastVisit($user_id)
1293{
1294  $query = "
1295DELETE FROM ".USER_LASTVISIT_TABLE."
1296WHERE user_id = '".$user_id."'
1297;";
1298  pwg_query($query);
1299}
1300
1301/**
1302 * Function called from main.inc.php - Triggered on user deletion
1303 *
1304 * @param : User id
1305 *
1306 */
1307function DeleteRedir($user_id)
1308{
1309  $tab = array();
1310
1311  $query = '
1312SELECT value
1313FROM '.CONFIG_TABLE.'
1314WHERE param = "UserAdvManager_Redir"
1315;';
1316
1317  $tab = pwg_db_fetch_row(pwg_query($query));
1318 
1319  $values = explode(',', $tab[0]);
1320
1321  unset($values[array_search($user_id, $values)]);
1322     
1323  $query = "
1324UPDATE ".CONFIG_TABLE."
1325SET value = \"".implode(',', $values)."\"
1326WHERE param = 'UserAdvManager_Redir';";
1327
1328  pwg_query($query);
1329}
1330
1331/**
1332 * Function called from ConfirmMail.php to verify validation key used by user according time limit
1333 * Return true is key validation is OK else return false
1334 *
1335 * @param : User id
1336 *
1337 * @return : Bool
1338 *
1339 */
1340function VerifyConfirmMail($id)
1341{
1342  global $conf;
1343
1344  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1345 
1346  $conf_UAM = unserialize($conf['UserAdvManager']);
1347
1348  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1349
1350  $query = "
1351SELECT COUNT(*)
1352FROM ".USER_CONFIRM_MAIL_TABLE."
1353WHERE id = '".$id."'
1354;";
1355  list($count) = pwg_db_fetch_row(pwg_query($query));
1356
1357  if ($count == 1)
1358  {
1359    $query = "
1360SELECT user_id, status, date_check
1361FROM ".USER_CONFIRM_MAIL_TABLE."
1362WHERE id = '".$id."'
1363;";
1364    $data = pwg_db_fetch_assoc(pwg_query($query));
1365       
1366    //if (!empty($data) and isset($data['user_id']) and !isset($data['date_check']))
1367    if (!empty($data) and isset($data['user_id']))
1368    {
1369      $query = "
1370SELECT registration_date
1371FROM ".USER_INFOS_TABLE."
1372WHERE user_id = '".$data['user_id']."'
1373;";
1374      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
1375
1376//              Time limit process             
1377// ******************************************** 
1378      if (!empty($registration_date))
1379      {
1380                                // Verify Confirmmail with time limit ON
1381                                if (isset ($conf_UAM_ConfirmMail[1]))
1382                                {
1383                                        // dates formating and compare
1384                                        $today = date("d-m-Y"); // Get today's date
1385                                        list($day, $month, $year) = explode('-', $today); // explode date of today                                               
1386                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
1387                       
1388                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
1389                                        list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
1390                                        $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
1391                       
1392                                        $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
1393                                        $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
1394
1395                                        // Condition with the value set for time limit
1396                                        if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
1397                                        {
1398                                                list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1399
1400                                                $query = '
1401UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1402SET date_check="'.$dbnow.'"
1403WHERE id = "'.$id.'"
1404;';
1405                                                pwg_query($query);
1406     
1407                                                if ($conf_UAM[2] <> -1) // Delete user from unvalidated users group
1408                                                {
1409                                                        $query = "
1410DELETE FROM ".USER_GROUP_TABLE."
1411WHERE user_id = '".$data['user_id']."'
1412  AND group_id = '".$conf_UAM[2]."'
1413;";
1414                                                        pwg_query($query);
1415                                                }
1416           
1417                                                if ($conf_UAM[3] <> -1) // Add user to validated users group
1418                                                {
1419                                                        $query = "
1420INSERT INTO ".USER_GROUP_TABLE."
1421  (user_id, group_id)
1422VALUES
1423  ('".$data['user_id']."', '".$conf_UAM[3]."')
1424;";
1425                                                        pwg_query($query);
1426                                                }
1427
1428                                                if (($conf_UAM[4] <> -1 or isset($data['status']))) // Change user's status
1429                                                {
1430                                                        $query = "
1431UPDATE ".USER_INFOS_TABLE."
1432SET status = '".(isset($data['status']) ? $data['status'] : $conf_UAM[4])."'
1433WHERE user_id = '".$data['user_id']."'
1434;";
1435                                                        pwg_query($query);
1436                                                }
1437                                                // Refresh user's category cache
1438                                                invalidate_user_cache();
1439 
1440                                                return true;
1441                                        }
1442                                        elseif ($deltadays > $conf_UAM_ConfirmMail[1]) // If timelimit exeeds
1443                                        {
1444                                                return false;
1445                                        }
1446                                }
1447                                // Verify Confirmmail with time limit OFF
1448                                else
1449                                {
1450                                        list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1451
1452                                        $query = '
1453UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1454SET date_check="'.$dbnow.'"
1455WHERE id = "'.$id.'"
1456;';
1457                                        pwg_query($query);
1458     
1459                                        if ($conf_UAM[2] <> -1)
1460                                        {
1461                                                $query = "
1462DELETE FROM ".USER_GROUP_TABLE."
1463WHERE user_id = '".$data['user_id']."'
1464AND group_id = '".$conf_UAM[2]."'
1465;";
1466                                                pwg_query($query);
1467                                        }
1468   
1469                                        if ($conf_UAM[3] <> -1)
1470                                        {
1471                                                $query = "
1472DELETE FROM ".USER_GROUP_TABLE."
1473WHERE user_id = '".$data['user_id']."'
1474AND group_id = '".$conf_UAM[3]."'
1475;";
1476                                                pwg_query($query);
1477
1478                                                $query = "
1479INSERT INTO ".USER_GROUP_TABLE."
1480  (user_id, group_id)
1481VALUES
1482  ('".$data['user_id']."', '".$conf_UAM[3]."')
1483;";
1484                                                pwg_query($query);
1485                                        }
1486
1487                                        if (($conf_UAM[4] <> -1 or isset($data['status'])))
1488                                        {
1489                                                $query = "
1490UPDATE ".USER_INFOS_TABLE."
1491SET status = '".(isset($data['status']) ? $data['status'] : $conf_UAM[4])."'
1492WHERE user_id = '".$data['user_id']."'
1493;";
1494                                                pwg_query($query);
1495                                        }
1496                                        // Refresh user's category cache
1497                                        invalidate_user_cache();
1498 
1499                                        return true;
1500                                }
1501                        }
1502                }
1503        }
1504  else
1505    return false;
1506}
1507
1508/**
1509 * Function called from UAM_admin.php to force users validation by admin
1510 *
1511 * @param : User id
1512 *
1513 */
1514function ForceValidation($id)
1515{
1516  global $conf;
1517
1518  $conf_UAM = unserialize($conf['UserAdvManager']);
1519
1520  if (isset($conf_UAM[1]) and $conf_UAM[1] == 'true')
1521  {
1522    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1523
1524                $query = "
1525UPDATE ".USER_CONFIRM_MAIL_TABLE."
1526SET date_check='".$dbnow."'
1527WHERE user_id = '".$id."'
1528;";
1529    pwg_query($query);
1530             
1531                if ($conf_UAM[2] <> -1)
1532                {
1533                        $query = "
1534DELETE FROM ".USER_GROUP_TABLE."
1535WHERE user_id = '".$id."'
1536  AND group_id = '".$conf_UAM[2]."'
1537;";
1538                        pwg_query($query);
1539                }
1540 
1541                if ($conf_UAM[3] <> -1)
1542                {
1543                        $query = "
1544DELETE FROM ".USER_GROUP_TABLE."
1545WHERE user_id = '".$id."'
1546  AND group_id = '".$conf_UAM[3]."'
1547;";
1548      pwg_query($query);
1549       
1550                        $query = "
1551INSERT INTO ".USER_GROUP_TABLE."
1552  (user_id, group_id)
1553VALUES
1554  ('".$id."', '".$conf_UAM[3]."')
1555;";
1556                        pwg_query($query);
1557    }
1558
1559                if ($conf_UAM[4] <> -1)
1560                {
1561                        $query = "
1562UPDATE ".USER_INFOS_TABLE."
1563SET status = '".$conf_UAM[4]."'
1564WHERE user_id = '".$id."'
1565;";
1566                        pwg_query($query);
1567                }
1568  }
1569  elseif (isset($conf_UAM[1]) and $conf_UAM[1] == 'local')
1570  {
1571    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1572
1573    if ($conf_UAM[2] <> -1)
1574    {
1575                  $query = "
1576DELETE FROM ".USER_GROUP_TABLE."
1577WHERE user_id = '".$id."'
1578  AND group_id = '".$conf_UAM[2]."'
1579;";
1580                  pwg_query($query);
1581    }
1582
1583    if ($conf_UAM[3] <> -1)
1584    {
1585      $query = "
1586DELETE FROM ".USER_GROUP_TABLE."
1587WHERE user_id = '".$id."'
1588  AND group_id = '".$conf_UAM[3]."'
1589;";
1590      pwg_query($query);
1591       
1592                  $query = "
1593INSERT INTO ".USER_GROUP_TABLE."
1594  (user_id, group_id)
1595VALUES
1596  ('".$id."', '".$conf_UAM[3]."')
1597;";
1598                  pwg_query($query);
1599    }
1600
1601    if ($conf_UAM[4] <> -1)
1602    {
1603                  $query = "
1604UPDATE ".USER_INFOS_TABLE."
1605SET status = '".$conf_UAM[4]."'
1606WHERE user_id = '".$id."'
1607;";
1608      pwg_query($query);
1609    }
1610  }
1611}
1612
1613/**
1614 * Function called from main.inc.php - Check if username matches forbidden caracters
1615 *
1616 * @param : User login
1617 *
1618 * @return : Bool
1619 *
1620 */
1621function ValidateUsername($login)
1622{
1623  global $conf;
1624
1625  $conf_UAM = unserialize($conf['UserAdvManager']);
1626
1627  if (isset($login) and isset($conf_UAM[7]) and $conf_UAM[7] <> '')
1628  {
1629    $conf_CharExclusion = preg_split("/,/",$conf_UAM[7]);
1630    for ($i = 0 ; $i < count($conf_CharExclusion) ; $i++)
1631    {
1632      $pattern = '/'.$conf_CharExclusion[$i].'/i';
1633      if (preg_match($pattern, $login))
1634      {
1635        return true;
1636      }
1637    }
1638  }
1639  else
1640  {
1641    return false;
1642  }
1643}
1644
1645/**
1646 * Function called from main.inc.php - Check if user's email is in excluded email providers list
1647 * Doesn't work on call - Must be copied in main.inc.php to work
1648 *
1649 * @param : Email address
1650 *
1651 * @return : Bool
1652 *
1653 */
1654function ValidateEmailProvider($email)
1655{
1656  global $conf;
1657
1658  $conf_UAM = unserialize($conf['UserAdvManager']);
1659 
1660        if (isset($email) and isset($conf_UAM[12]) and $conf_UAM[12] <> '')
1661        {
1662                $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM[12]);
1663                for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
1664                {
1665                        $pattern = '/'.$conf_MailExclusion[$i].'/i';
1666                        if (preg_match($pattern, $email))
1667      {
1668                        return true;
1669      }
1670                }
1671        }
1672  else
1673  {
1674    return false;
1675  }
1676}
1677
1678/**
1679 * Function called from UAM_admin.php - Get unvalidated users according time limit
1680 *
1681 * @return : List of users
1682 *
1683 */
1684function get_unvalid_user_list()
1685{
1686        global $conf, $page;
1687         
1688        // Get ConfirmMail configuration
1689  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1690  // Get UAM configuration
1691  $conf_UAM = unserialize($conf['UserAdvManager']);
1692 
1693  $users = array();
1694
1695        // search users depending expiration date
1696  $query = '
1697SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
1698                u.'.$conf['user_fields']['username'].' AS username,
1699                u.'.$conf['user_fields']['email'].' AS email,
1700                ui.status,
1701                ui.adviser,
1702                ui.enabled_high,
1703                ui.level,
1704                ui.registration_date
1705FROM '.USERS_TABLE.' AS u
1706  INNER JOIN '.USER_INFOS_TABLE.' AS ui
1707    ON u.'.$conf['user_fields']['id'].' = ui.user_id
1708  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
1709    ON u.'.$conf['user_fields']['id'].' = ug.user_id
1710WHERE u.'.$conf['user_fields']['id'].' >= 3
1711  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'"
1712  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail[1].'")';
1713
1714        if ($conf_UAM[2] <> '-1' and $conf_UAM[8] == '-1')
1715  {
1716    $query.= '
1717  AND ug.group_id = '.$conf_UAM[2];
1718  }
1719  if ($conf_UAM[2] == '-1' and $conf_UAM[8] <> '-1')
1720  {
1721    $query.= '
1722  AND ui.status = \''.$conf_UAM[8]."'";
1723  }
1724  if ($conf_UAM[2] <> '-1' and $conf_UAM[8] <> '-1')
1725  {
1726    $query.= '
1727  AND ug.group_id = \''.$conf_UAM[2]."'";
1728  }
1729  $query.= '
1730ORDER BY ui.registration_date ASC
1731;';
1732
1733        $result = pwg_query($query);
1734     
1735  while ($row = pwg_db_fetch_assoc($result))
1736  {
1737        $user = $row;
1738    $user['groups'] = array();
1739
1740    array_push($users, $user);
1741        }
1742
1743        // add group lists
1744  $user_ids = array();
1745  foreach ($users as $i => $user)
1746  {
1747        $user_ids[$i] = $user['id'];
1748        }
1749       
1750        $user_nums = array_flip($user_ids);
1751
1752  if (count($user_ids) > 0)
1753  {
1754        $query = '
1755SELECT user_id, group_id
1756  FROM '.USER_GROUP_TABLE.'
1757WHERE user_id IN ('.implode(',', $user_ids).')
1758;';
1759       
1760                $result = pwg_query($query);
1761       
1762    while ($row = pwg_db_fetch_assoc($result))
1763    {
1764        array_push(
1765        $users[$user_nums[$row['user_id']]]['groups'],
1766        $row['group_id']
1767                        );
1768                }
1769        }
1770
1771        return $users;
1772}
1773
1774/**
1775 * Function called from UAM_admin.php - Get ghost users
1776 *
1777 * @return : List of users
1778 *
1779 */
1780function get_ghost_user_list()
1781{
1782        global $conf, $page;
1783
1784  $conf_UAM = unserialize($conf['UserAdvManager']);
1785 
1786  $users = array();
1787
1788        // search users depending expiration date
1789  $query = '
1790SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
1791                u.'.$conf['user_fields']['username'].' AS username,
1792                u.'.$conf['user_fields']['email'].' AS email,
1793                lv.lastvisit,
1794                lv.reminder
1795FROM '.USERS_TABLE.' AS u
1796  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
1797    ON u.'.$conf['user_fields']['id'].' = lv.user_id
1798WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[17].'")
1799ORDER BY lv.lastvisit ASC;';
1800
1801        $result = pwg_query($query);
1802     
1803  while ($row = pwg_db_fetch_assoc($result))
1804  {
1805        $user = $row;
1806    $user['groups'] = array();
1807
1808    array_push($users, $user);
1809        }
1810
1811        // add group lists
1812  $user_ids = array();
1813  foreach ($users as $i => $user)
1814  {
1815        $user_ids[$i] = $user['id'];
1816        }
1817
1818        return $users;
1819}
1820
1821
1822/**
1823 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
1824 *
1825 * @return : List of users to delete or downgrade automatically
1826 *
1827 */
1828function get_ghosts_autotasks()
1829{
1830        global $conf, $page;
1831
1832  $conf_UAM = unserialize($conf['UserAdvManager']);
1833 
1834  $users = array();
1835 
1836        // search users depending expiration date and reminder sent
1837  $query = '
1838SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
1839                lv.lastvisit
1840FROM '.USERS_TABLE.' AS u
1841  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
1842    ON u.'.$conf['user_fields']['id'].' = lv.user_id
1843WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[17].'")
1844ORDER BY lv.lastvisit ASC;';
1845
1846        $result = pwg_query($query);
1847     
1848  while ($row = pwg_db_fetch_assoc($result))
1849  {
1850        $user = $row;
1851    $user['groups'] = array();
1852
1853    array_push($users, $user);
1854        }
1855
1856        // add group lists
1857  $user_ids = array();
1858  foreach ($users as $i => $user)
1859  {
1860        $user_ids[$i] = $user['id'];
1861        }
1862 
1863        return $users;
1864}
1865
1866
1867/**
1868 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
1869 *
1870 * @return : List of users
1871 *
1872 */
1873function get_user_list()
1874{
1875        global $conf, $page;
1876 
1877  $users = array();
1878
1879        // search users depending expiration date
1880  $query = '
1881SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
1882                u.'.$conf['user_fields']['username'].' AS username,
1883                u.'.$conf['user_fields']['email'].' AS email,
1884                ug.lastvisit
1885FROM '.USERS_TABLE.' AS u
1886  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
1887    ON u.'.$conf['user_fields']['id'].' = ug.user_id
1888WHERE u.'.$conf['user_fields']['id'].' >= 3
1889ORDER BY ug.lastvisit DESC
1890;';
1891
1892        $result = pwg_query($query);
1893     
1894  while ($row = pwg_db_fetch_assoc($result))
1895  {
1896        $user = $row;
1897    $user['groups'] = array();
1898
1899    array_push($users, $user);
1900        }
1901
1902        // add group lists
1903  $user_ids = array();
1904  foreach ($users as $i => $user)
1905  {
1906        $user_ids[$i] = $user['id'];
1907        }
1908
1909        return $users;
1910}
1911
1912/**
1913 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
1914 *
1915 * @param : user id
1916 *
1917 * @return : Bool
1918 *
1919 */
1920function expiration($id)
1921{
1922        global $conf, $page;
1923         
1924        // Get ConfirmMail configuration
1925  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1926         
1927        // Get UAM configuration
1928  $conf_UAM = unserialize($conf['UserAdvManager']);
1929       
1930        $query = "
1931SELECT registration_date
1932  FROM ".USER_INFOS_TABLE."
1933WHERE user_id = '".$id."'
1934;";
1935        list($registration_date) = pwg_db_fetch_row(pwg_query($query));
1936
1937//              Time limit process             
1938// ******************************************** 
1939        if (!empty($registration_date))
1940  {
1941                // dates formating and compare
1942                $today = date("d-m-Y"); // Get today's date
1943                list($day, $month, $year) = explode('-', $today); // explode date of today                                               
1944                $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
1945               
1946          list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
1947                list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
1948                $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
1949                       
1950                $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
1951                $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
1952
1953                // Condition with the value set for time limit
1954                if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
1955                {
1956                        return false;
1957                }
1958                else
1959                {
1960                        return true;
1961                }
1962        }
1963}
1964
1965
1966/**
1967 * Returns a password's score for password complexity check
1968 *
1969 * @param : password filled by user
1970 *
1971 * @return : Score calculation
1972 *
1973 * Thanx to MathieuGut from http://m-gut.developpez.com
1974 */
1975function testpassword($password) // Le mot de passe passé en paramètre - $password given by user
1976{
1977
1978  // Initialisation des variables - Variables initiation
1979  $points = 0;
1980  $point_lowercase = 0;
1981  $point_uppercase = 0;
1982  $point_numbers = 0;
1983  $point_characters = 0;
1984
1985  // On récupère la longueur du mot de passe - Getting password lengh   
1986  $length = strlen($password);
1987 
1988  // On fait une boucle pour lire chaque lettre - Loop to read password characters
1989  for($i = 0; $i < $length; $i++)
1990  {
1991    // On sélectionne une à une chaque lettre - Select each letters
1992    // $i étant à 0 lors du premier passage de la boucle - $i is 0 at first turn
1993    $letters = $password[$i];
1994
1995    if ($letters>='a' && $letters<='z')
1996    {
1997      // On ajoute 1 point pour une minuscule - Adding 1 point to score for a lowercase
1998                  $points = $points + 1;
1999
2000                  // On rajoute le bonus pour une minuscule - Adding bonus points for lowercase
2001                  $point_lowercase = 1;
2002    }
2003    else if ($letters>='A' && $letters <='Z')
2004    {
2005      // On ajoute 2 points pour une majuscule - Adding 2 points to score for uppercase
2006      $points = $points + 2;
2007               
2008      // On rajoute le bonus pour une majuscule - Adding bonus points for uppercase
2009      $point_uppercase = 2;
2010    }
2011    else if ($letters>='0' && $letters<='9')
2012    {
2013      // On ajoute 3 points pour un chiffre - Adding 3 points to score for numbers
2014      $points = $points + 3;
2015               
2016      // On rajoute le bonus pour un chiffre - Adding bonus points for numbers
2017      $point_numbers = 3;
2018    }
2019    else
2020    {
2021      // On ajoute 5 points pour un caractère autre - Adding 5 points to score for special characters
2022      $points = $points + 5;
2023               
2024      // On rajoute le bonus pour un caractère autre - Adding bonus points for special characters
2025      $point_characters = 5;
2026    }
2027  }
2028
2029  // Calcul du coefficient points/longueur - calculating the coefficient points/length
2030  $step1 = $points / $length;
2031
2032  // Calcul du coefficient de la diversité des types de caractères... - Calculation of the diversity of character types...
2033  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
2034
2035  // Multiplication du coefficient de diversité avec celui de la longueur - Multiplying the coefficient of diversity with that of the length
2036  $score = $step1 * $step2;
2037
2038  // Multiplication du résultat par la longueur de la chaîne - Multiplying the result by the length of the chain
2039  $finalscore = $score * $length;
2040
2041  return $finalscore;
2042}
2043
2044/**
2045 * Function called from maintain.inc.php - to check if database upgrade is needed
2046 *
2047 * @param : table name
2048 *
2049 * @return : boolean
2050 *
2051 */
2052function table_exist($table)
2053{
2054  $query = 'DESC '.$table.';';
2055  return (bool)($res=pwg_query($query));
2056}
2057
2058// Email sending debugger function
2059function MailLog($to, $subject, $content, $language)
2060{
2061   $fo=fopen (UAM_PATH.'admin/maillog.txt','a') ;
2062   fwrite($fo,"======================\n") ;
2063   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
2064   fwrite($fo,$to . "\n" . $subject . "\r\n") ;
2065   fwrite($fo, "\n" . $content . "\r\n") ;
2066   fwrite($fo, 'Langue : '."\n" . $language . "\r\n") ;
2067   fclose($fo) ;
2068   //return mail ($to,$subject) ;
2069}
2070
2071/**
2072 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
2073 *
2074 * @param : plugin directory
2075 *
2076 * @return : plugin's version and name
2077 *
2078 */
2079function PluginInfos($dir)
2080{
2081  $path = $dir;
2082
2083  $plg_data = implode( '', file($path.'main.inc.php') );
2084  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
2085  {
2086    $plugin['name'] = trim( $val[1] );
2087  }
2088  if (preg_match("|Version: (.*)|", $plg_data, $val))
2089  {
2090    $plugin['version'] = trim($val[1]);
2091  }
2092  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
2093  {
2094    $plugin['uri'] = trim($val[1]);
2095  }
2096  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
2097  {
2098    $plugin['description'] = trim($desc);
2099  }
2100  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
2101  {
2102    $plugin['description'] = trim($val[1]);
2103  }
2104  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
2105  {
2106    $plugin['author'] = trim($val[1]);
2107  }
2108  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
2109  {
2110    $plugin['author uri'] = trim($val[1]);
2111  }
2112  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
2113  {
2114    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
2115    if (is_numeric($extension)) $plugin['extension'] = $extension;
2116  }
2117// IMPORTANT SECURITY !
2118  $plugin = array_map('htmlspecialchars', $plugin);
2119
2120  return $plugin ;
2121}
2122
2123
2124function clean_obsolete_files()
2125{
2126  if (file_exists(UAM_PATH.'obsolete.list')
2127    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
2128    and !empty($old_files))
2129  {
2130    array_push($old_files, 'obsolete.list');
2131    foreach($old_files as $old_file)
2132    {
2133      $path = UAM_PATH.$old_file;
2134      if (is_file($path))
2135      {
2136        @unlink($path);
2137      }
2138    }
2139  }
2140}
2141
2142/**
2143 * UAM_check_profile - Thx to LucMorizur
2144 * checks if a user id is registered as having already
2145 * visited his profile.php page.
2146 *
2147 * @uid        : the user id
2148 *
2149 * @user_idsOK : (returned) array of all users ids having already visited
2150 *               their profile.php pages
2151 *
2152 * @returns    : true or false whether the users has already visited his
2153 *               profile.php page or not
2154 *
2155 */
2156function UAM_check_profile($uid, &$user_idsOK)
2157{
2158  $t = array();
2159  $v = false;
2160 
2161  $query = "
2162SELECT value
2163FROM ".CONFIG_TABLE."
2164WHERE param = 'UserAdvManager_Redir'
2165;";
2166 
2167  if ($v = (($t = pwg_db_fetch_row(pwg_query($query))) !== false))
2168  {
2169    $user_idsOK = explode(',', $t[0]);
2170    $v = (in_array($uid, $user_idsOK));
2171  }
2172  return $v;
2173}
2174?>
Note: See TracBrowser for help on using the repository browser.