source: extensions/UserAdvManager/trunk/include/functions.inc.php @ 12227

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

bug 2445 fixed : Duplicate key MySql error when a registered user tries to validate his registration twice

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