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

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

bug 2055 fixed : New automated task for unvalidated registers (auto email reminder sent and auto deletion if already reminded).
Localisation files cleanup : all keys for "enable" and "disable" options have been replaced by one unic key.

  • Property svn:eol-style set to LF
File size: 63.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('UAM_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('UAM_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('UAM_reg_err_login2')."'".$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('UAM_reg_err_login5')."'".$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('UAM_reg_err_login5')."'".$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('UAM_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 GhostTracker scheduled tasks
325  if ((isset($conf_UAM[22]) and $conf_UAM[22] == 'true'))
326  {
327    UAM_GT_ScheduledTasks();
328  }
329
330  // Performing User validation scheduled tasks
331  if ((isset($conf_UAM[31]) and $conf_UAM[31] == 'true'))
332  {
333    UAM_USR_ScheduledTasks();
334  }
335
336  if ((isset($conf_UAM[21]) and $conf_UAM[21] == 'true'))
337  {
338    // Performing redirection 
339    $query ='
340SELECT user_id, status
341FROM '.USER_INFOS_TABLE.'
342WHERE user_id = '.$user['id'].'
343;';
344    $data = pwg_db_fetch_assoc(pwg_query($query));
345
346    if ($data['status'] <> "admin" and $data['status'] <> "webmaster" and $data['status'] <> "generic")
347    {
348      $user_idsOK = array();
349      if (!UAM_check_profile($user['id'], $user_idsOK))
350        redirect(PHPWG_ROOT_PATH.'profile.php');
351    }
352  }
353}
354
355/**
356 * Triggered on UAM_LoginTasks()
357 *
358 * Executes optional post-login tasks for Ghost users
359 *
360 */
361function UAM_GT_ScheduledTasks()
362{
363  global $conf, $user, $page;
364
365  if (!defined('PHPWG_ROOT_PATH'))
366  {
367    die('Hacking attempt!');
368  }
369         
370  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
371
372  $conf_UAM = unserialize($conf['UserAdvManager']);
373 
374  $collection = array();
375  $reminder = false;
376 
377  $page['filtered_users'] = get_ghosts_autotasks();
378
379  foreach($page['filtered_users'] as $listed_user)
380  {
381    array_push($collection, $listed_user['id']);
382  }
383
384  // Ghost accounts auto group or status downgrade with or without information email sending and autodeletion if user already reminded
385  if ((isset($conf_UAM[22]) and $conf_UAM[22] == 'true') and ((isset($conf_UAM[26]) and $conf_UAM[26] <> -1) or (isset($conf_UAM[27]) and $conf_UAM[27] <> -1)))
386  {
387    if (count($collection) > 0)
388        {
389      // Process if a non-admin nor webmaster user is logged
390      if (in_array($user['id'], $collection))
391        {
392        // Check lastvisit reminder state
393        $query = '
394SELECT reminder
395FROM '.USER_LASTVISIT_TABLE.'
396WHERE user_id = '.$user['id'].';';
397
398        $result = pwg_db_fetch_assoc(pwg_query($query));
399
400        if (isset($result['reminder']) and $result['reminder'] == 'true')
401        {
402          $reminder = true;
403        }
404        else
405        {
406          $reminder = false;
407        }
408
409        // If user already reminded for ghost account
410        if ($reminder)
411        {
412          // delete account
413          delete_user($user['id']);
414
415          // Logged-in user cleanup, session destruction and redirected to custom page
416          invalidate_user_cache();
417          logout_user();
418          redirect(UAM_PATH.'GT_del_account.php');
419        }
420        }
421      else // Process if an admin or webmaster user is logged
422      {
423        foreach ($collection as $user_id)
424        {
425          // Check lastvisit reminder state
426          $query = '
427SELECT reminder
428FROM '.USER_LASTVISIT_TABLE.'
429WHERE user_id = '.$user_id.';';
430
431          $result = pwg_db_fetch_assoc(pwg_query($query));
432
433          if (isset($result['reminder']) and $result['reminder'] == 'true')
434          {
435            $reminder = true;
436          }
437          else
438          {
439            $reminder = false;
440          }
441
442          // If never reminded before
443          if (!$reminder)
444          {
445            // Reset of lastvisit date
446            list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
447
448                        $query = "
449UPDATE ".USER_LASTVISIT_TABLE."
450SET lastvisit='".$dbnow."'
451WHERE user_id = '".$user_id."'
452;";
453            pwg_query($query);
454
455          // Auto change group and / or status
456            // Delete user from all groups
457            $query = "
458DELETE FROM ".USER_GROUP_TABLE."
459WHERE user_id = '".$user_id."'
460  AND (
461    group_id = '".$conf_UAM[2]."'
462  OR
463    group_id = '".$conf_UAM[3]."'
464  )
465;";
466            pwg_query($query);
467
468            // Change user status
469            if ($conf_UAM[27] <> -1)
470            {
471              $query = "
472UPDATE ".USER_INFOS_TABLE."
473SET status = '".$conf_UAM[27]."'
474WHERE user_id = '".$user_id."'
475;";
476              pwg_query($query);
477            }
478
479            // Change user group
480            if ($conf_UAM[26] <> -1)
481            {
482              $query = "
483INSERT INTO ".USER_GROUP_TABLE."
484  (user_id, group_id)
485VALUES
486  ('".$user_id."', '".$conf_UAM[26]."')
487;";
488              pwg_query($query);
489            }
490
491            // Auto send email notification on group / status downgrade
492            if (isset($conf_UAM[23]) and $conf_UAM[23] == 'true')
493            {
494              // Set reminder true
495              $query = "
496UPDATE ".USER_LASTVISIT_TABLE."
497SET reminder = 'true'
498WHERE user_id = '".$user_id."'
499;";
500              pwg_query($query);
501           
502              // Reset confirmed user status to unvalidated
503                                                  $query = '
504UPDATE '.USER_CONFIRM_MAIL_TABLE.'
505SET date_check = NULL
506WHERE user_id = "'.$user_id.'"
507;';
508                                                  pwg_query($query);
509
510              // Get users information for email notification
511                                                  $query = '
512SELECT id, username, mail_address
513FROM '.USERS_TABLE.'
514WHERE id = '.$user_id.'
515;';
516                                                  $data = pwg_db_fetch_assoc(pwg_query($query));
517           
518              demotion_mail($user_id, $data['username'], $data['mail_address']);
519            }
520          }
521          elseif ($reminder) // If user already reminded for ghost account
522          {
523            // delete account
524            delete_user($user_id);
525          }
526        }
527      }
528    }
529  }
530}
531
532/**
533 * Triggered on UAM_LoginTasks()
534 *
535 * Executes optional post-login tasks for unvalidated users
536 *
537 */
538function UAM_USR_ScheduledTasks()
539{
540  global $conf, $user, $page;
541
542  if (!defined('PHPWG_ROOT_PATH'))
543  {
544    die('Hacking attempt!');
545  }
546         
547  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
548
549  $conf_UAM = unserialize($conf['UserAdvManager']);
550 
551  $collection = array();
552  $reminder = false;
553 
554  $page['filtered_users'] = get_unvalid_user_autotasks();
555
556  foreach($page['filtered_users'] as $listed_user)
557  {
558    array_push($collection, $listed_user['id']);
559  }
560
561  // Unvalidated accounts auto email sending and autodeletion if user already reminded
562  if ((isset($conf_UAM[31]) and $conf_UAM[31] == 'true'))
563  {
564    if (count($collection) > 0)
565        {
566      // Process if a non-admin nor webmaster user is logged
567      if (in_array($user['id'], $collection))
568        {
569        // Check ConfirmMail reminder state
570        $query = '
571SELECT reminder
572FROM '.USER_CONFIRM_MAIL_TABLE.'
573WHERE user_id = '.$user['id'].';';
574
575        $result = pwg_db_fetch_assoc(pwg_query($query));
576
577        if (isset($result['reminder']) and $result['reminder'] == 'true')
578        {
579          $reminder = true;
580        }
581        else
582        {
583          $reminder = false;
584        }
585
586        // If never reminded before, send reminder and set reminder True
587        if (!$reminder and isset($conf_UAM[33]) and $conf_UAM[33] == 'true')
588        {
589                  $typemail = 1;
590         
591          // Get current user informations
592          $query = "
593SELECT id, username, mail_address
594FROM ".USERS_TABLE."
595WHERE id = '".$user['id']."'
596;";
597          $data = pwg_db_fetch_assoc(pwg_query($query));
598
599          ResendMail2User($typemail,$user['id'],stripslashes($data['username']),$data['mail_address'],true);
600        }
601
602        // If already reminded before, delete user
603        if ($reminder)
604        {
605          // delete account
606          delete_user($user['id']);
607
608          // Logged-in user cleanup, session destruction and redirected to custom page
609          invalidate_user_cache();
610          logout_user();
611          redirect(UAM_PATH.'USR_del_account.php');
612        }
613        }
614      else // Process if an admin or webmaster user is logged
615      {
616        foreach ($collection as $user_id)
617        {
618          // Check reminder state
619          $query = '
620SELECT reminder
621FROM '.USER_CONFIRM_MAIL_TABLE.'
622WHERE user_id = '.$user_id.';';
623
624          $result = pwg_db_fetch_assoc(pwg_query($query));
625
626          if (isset($result['reminder']) and $result['reminder'] == 'true')
627          {
628            $reminder = true;
629          }
630          else
631          {
632            $reminder = false;
633          }
634
635          // If never reminded before, send reminder and set reminder True
636          if (!$reminder and isset($conf_UAM[33]) and $conf_UAM[33] == 'true')
637          {
638            $typemail = 1;
639         
640            // Get current user informations
641            $query = "
642SELECT id, username, mail_address
643FROM ".USERS_TABLE."
644WHERE id = '".$user_id."'
645;";
646            $data = pwg_db_fetch_assoc(pwg_query($query));
647
648            ResendMail2User($typemail,$user_id,stripslashes($data['username']),$data['mail_address'],true);
649          }
650          elseif ($reminder) // If user already reminded for account validation
651          {
652            // delete account
653            delete_user($user_id);
654          }
655        }
656      }
657    }
658  }
659}
660
661
662/**
663 * Triggered on init
664 *
665 * Check for forbidden email domains in admin's users management panel
666 */
667function UAM_InitPage()
668{
669  load_language('plugin.lang', UAM_PATH);
670  global $conf, $template, $page, $lang, $errors;
671
672  $conf_UAM = unserialize($conf['UserAdvManager']);
673
674// Admin user management
675  if (script_basename() == 'admin' and isset($_GET['page']) and $_GET['page'] == 'user_list')
676  {
677    if (isset($_POST['submit_add']))
678    {
679      // Email without forbidden domains
680      if (isset($conf_UAM[11]) and $conf_UAM[11] == 'true' and !empty($_POST['email']) and ValidateEmailProvider($_POST['email']))
681      {
682        $template->append('errors', l10n('UAM_reg_err_login5')."'".$conf_UAM[12]."'");
683        unset($_POST['submit_add']);
684      }
685    }
686  }
687}
688
689
690/**
691 * Triggered on render_lost_password_mail_content
692 *
693 * Adds a customized text in lost password email content
694 * Added text is inserted before users login name and new password
695 *
696 * @param : Standard Piwigo email content
697 *
698 * @return : Customized content added to standard content
699 *
700 */
701function UAM_lost_password_mail_content($infos)
702{
703  global $conf;
704 
705  load_language('plugin.lang', UAM_PATH);
706 
707  $conf_UAM = unserialize($conf['UserAdvManager']);
708 
709  if (isset($conf_UAM[29]) and $conf_UAM[29] == 'true')
710  {
711    // Management of Extension flags ([username], [mygallery], [myurl])
712    $patterns[] = '#\[username\]#i';
713    $replacements[] = stripslashes($row['username']);
714    $patterns[] = '#\[mygallery\]#i';
715    $replacements[] = $conf['gallery_title'];
716    $patterns[] = '#\[myurl\]#i';
717    $replacements[] = $conf['gallery_url'];
718   
719    $infos = preg_replace($patterns, $replacements, $conf_UAM[30])."\n"."\n".$infos;
720  }
721  return $infos;
722}
723
724
725/**
726 * Triggered on user_comment_check
727 *
728 * checks if author is mandatory and set on comments post
729 *
730 * @param : comment action, comment
731 *
732 * @return : comment action
733 *
734 */
735function UAM_CheckEmptyCommentAuthor($comment_action, $comm)
736{
737  load_language('plugin.lang', UAM_PATH);
738  global $infos, $conf, $template;
739
740  $conf_UAM = unserialize($conf['UserAdvManager']);
741
742// User creation OR update
743  if (isset($conf_UAM[5]) and $conf_UAM[5] == 'true' and $conf['comments_forall'] == 'true' and $comm['author'] == 'guest')
744  {
745    $comment_action = 'reject';
746
747    array_push($infos, l10n('UAM_Empty Author'));
748  }
749
750  return $comment_action;
751}
752
753/**
754 * Function called from main.inc.php to send validation email
755 *
756 * @param : Type of email, user id, username, email address, confirmation (optional)
757 *
758 */
759function SendMail2User($typemail, $id, $username, $password, $email, $confirm)
760{
761  global $conf;
762
763  $conf_UAM = unserialize($conf['UserAdvManager']);
764 
765        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
766 
767        $infos1_perso = "";
768  $infos2_perso = "";
769
770// We have to get the user's language in database
771  $query ='
772SELECT user_id, language
773FROM '.USER_INFOS_TABLE.'
774WHERE user_id = '.$id.'
775;';
776  $data = pwg_db_fetch_assoc(pwg_query($query));
777
778// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
779  if (empty($data))
780  {
781// And switch gallery to this language before using personalized and multilangual contents
782    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
783    switch_lang_to($language);
784  }
785  else
786  {
787// And switch gallery to this language before using personalized and multilangual contents
788    $language = $data['language']; // Usefull for debugging
789    switch_lang_to($data['language']);
790    load_language('plugin.lang', UAM_PATH);
791  }
792
793  switch($typemail)
794  {
795    case 1:
796      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Add of %s', stripslashes($username)));
797      $password = $password <> '' ? $password : l10n('UAM_empty_pwd');
798     
799      if (isset($conf_UAM[9]) and $conf_UAM[9] <> '')
800      {
801        // Management of Extension flags ([username], [mygallery], [myurl])
802        $patterns[] = '#\[username\]#i';
803        $replacements[] = $username;
804        $patterns[] = '#\[mygallery\]#i';
805        $replacements[] = $conf['gallery_title'];
806        $patterns[] = '#\[myurl\]#i';
807        $replacements[] = $conf['gallery_url'];
808   
809        if (function_exists('get_user_language_desc'))
810        {
811          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[9]))."\n\n";
812        }
813        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM[9]))."\n\n"; 
814      }
815     
816      break;
817     
818    case 2:
819      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Update of %s', stripslashes($username)));
820      $password = $password <> '' ? $password : l10n('UAM_empty_pwd');
821
822      break;
823       
824    case 3:
825      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Update of %s', stripslashes($username)));
826      $password = $password <> '' ? $password : l10n('UAM_no_update_pwd');
827
828      break;
829  }
830
831  if (isset($conf_UAM[0]) and $conf_UAM[0] == 'true')
832  {
833    $infos1 = array(
834      get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
835      get_l10n_args('UAM_User: %s', stripslashes($username)),
836      get_l10n_args('UAM_Password: %s', $password),
837      get_l10n_args('Email: %s', $email),
838      get_l10n_args('', ''),
839    );
840  }
841
842
843  if ( isset($conf_UAM[1]) and $conf_UAM[1] == 'true' and $confirm)
844  {
845    $infos2 = array
846    (
847      get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
848      get_l10n_args('', ''),
849    );
850
851    if (isset($conf_UAM[10]) and $conf_UAM[10] <> '')
852    {
853      // Management of Extension flags ([username], [mygallery], [myurl])
854      $patterns[] = '#\[username\]#i';
855      $replacements[] = $username;
856      $patterns[] = '#\[mygallery\]#i';
857      $replacements[] = $conf['gallery_title'];
858      $patterns[] = '#\[myurl\]#i';
859      $replacements[] = $conf['gallery_url'];
860     
861      if (function_exists('get_user_language_desc'))
862      {
863        $infos2_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[10]))."\n\n";
864      }
865      else $infos2_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM[10]))."\n\n";
866    }
867  }
868
869// ********************************************************
870// **** Pending code since to find how to make it work ****
871// ********************************************************
872// Testing if FCK Editor is used. Then decoding htmlchars to avoid problems with pwg_mail()
873/*$areas = array();
874array_push( $areas,'UAM_MailInfo_Text','UAM_ConfirmMail_Text');
875
876if (function_exists('set_fckeditor_instance'))
877{
878  $fcke_config = unserialize($conf['FCKEditor']);
879  foreach($areas as $area)
880  {
881    if (isset($fcke_config['UAM_MailInfo_Text']) and $fcke_config['UAM_MailInfo_Text'] = true)
882    {
883      $infos1_perso = html_entity_decode($infos1_perso,ENT_QUOTES,UTF-8);
884    }
885   
886    if (isset($fcke_config['UAM_ConfirmMail_Text']) and $fcke_config['UAM_ConfirmMail_Text'] = true)
887    {
888      $infos2_perso = html_entity_decode($infos2_perso,ENT_QUOTES,UTF-8);
889    }
890  }
891}*/
892
893
894// Sending the email with subject and contents
895  pwg_mail($email, array(
896    'subject' => $subject,
897    'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
898  ));
899
900// **********************
901// Email sending debugger
902// This is only to trace
903// the send of emails for
904// debugging             
905// **********************
906//$content = (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url();   
907//MailLog($email,$subject,$content,$language);
908// **********************
909
910// Switching back to default language
911switch_lang_back();
912}
913
914/**
915 * Function called from UAM_admin.php to resend validation email with or without new validation key
916 *
917 * @param : Type of email, user id, username, email address, confirmation (optional)
918 *
919 */
920function ResendMail2User($typemail, $user_id, $username, $email, $confirm)
921{
922  global $conf;
923
924  $conf_UAM = unserialize($conf['UserAdvManager']);
925
926  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
927 
928        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
929 
930// We have to get the user's language in database
931  $query ='
932SELECT user_id, language
933FROM '.USER_INFOS_TABLE.'
934WHERE user_id = '.$user_id.'
935;';
936  $data = pwg_db_fetch_assoc(pwg_query($query));
937  $language = $data['language'];
938 
939// And switch gallery to this language before using personalized and multilangual contents
940  switch_lang_to($data['language']);
941   
942  load_language('plugin.lang', UAM_PATH);
943
944  switch($typemail)
945  {
946    case 1:
947      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Reminder_with_key_of_%s', $username));
948     
949      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)
950      {
951        // Management of Extension flags ([username], [mygallery], [myurl])
952        $patterns[] = '#\[username\]#i';
953        $replacements[] = $username;
954        $patterns[] = '#\[mygallery\]#i';
955        $replacements[] = $conf['gallery_title'];
956        $patterns[] = '#\[myurl\]#i';
957        $replacements[] = $conf['gallery_url'];
958
959        if (function_exists('get_user_language_desc'))
960        {
961          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[2]))."\n\n";
962        }
963                                else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[2]))."\n\n";
964
965        $infos2 = array
966        (
967          get_l10n_args('UAM_Link: %s', ResetConfirmMail($user_id)),
968          get_l10n_args('', ''),
969        );       
970                        }
971
972// Set reminder true     
973      $query = "
974UPDATE ".USER_CONFIRM_MAIL_TABLE."
975SET reminder = 'true'
976WHERE user_id = '".$user_id."'
977;";
978      pwg_query($query);
979     
980                break;
981     
982    case 2:
983      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Reminder_without_key_of_%s',$username));
984     
985      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)
986      {
987        // Management of Extension flags ([username], [mygallery], [myurl])
988        $patterns[] = '#\[username\]#i';
989        $replacements[] = $username;
990        $patterns[] = '#\[mygallery\]#i';
991        $replacements[] = $conf['gallery_title'];
992        $patterns[] = '#\[myurl\]#i';
993        $replacements[] = $conf['gallery_url'];
994       
995        if (function_exists('get_user_language_desc'))
996        {
997          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[4]))."\n\n";
998        }
999        else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[4]))."\n\n";
1000      }
1001     
1002// Set reminder true     
1003      $query = "
1004UPDATE ".USER_CONFIRM_MAIL_TABLE."
1005SET reminder = 'true'
1006WHERE user_id = '".$user_id."'
1007;";
1008      pwg_query($query);
1009     
1010    break;
1011        }
1012 
1013  pwg_mail($email, array(
1014    'subject' => $subject,
1015    'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1016  ));
1017
1018// **********************
1019// Email sending debugger
1020// This is only to trace
1021// the send of emails for
1022// debugging             
1023// **********************
1024//$content = ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url();
1025//MailLog($email,$subject,$content,$language);
1026// **********************
1027
1028// Switching back to default language
1029switch_lang_back();
1030}
1031
1032/**
1033 * Function called from UAM_admin.php to send a reminder mail for ghost users
1034 *
1035 * @param : User id, username, email address
1036 *
1037 */
1038function ghostreminder($user_id, $username, $email)
1039{
1040  global $conf;
1041
1042  $conf_UAM = unserialize($conf['UserAdvManager']);
1043 
1044        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1045 
1046        $infos1_perso = "";
1047
1048// We have to get the user's language in database
1049  $query ='
1050SELECT user_id, language
1051FROM '.USER_INFOS_TABLE.'
1052WHERE user_id = '.$user_id.'
1053;';
1054  $data = pwg_db_fetch_assoc(pwg_query($query));
1055  $language = $data['language'];
1056
1057// And switch gallery to this language before using personalized and multilangual contents
1058  switch_lang_to($data['language']);
1059   
1060  load_language('plugin.lang', UAM_PATH);
1061 
1062  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Ghost_reminder_of_%s', $username));     
1063
1064  if (isset($conf_UAM[18]) and $conf_UAM[18] <> '' and isset($conf_UAM[16]) and $conf_UAM[16] == 'true')
1065  {
1066    // Management of Extension flags ([username], [mygallery], [myurl])
1067    $patterns[] = '#\[username\]#i';
1068    $replacements[] = $username;
1069    $patterns[] = '#\[mygallery\]#i';
1070    $replacements[] = $conf['gallery_title'];
1071    $patterns[] = '#\[myurl\]#i';
1072    $replacements[] = $conf['gallery_url'];
1073
1074    if (function_exists('get_user_language_desc'))
1075    {
1076      $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[18]))."\n\n";
1077    }
1078    else
1079    {
1080      $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM[18]))."\n\n";
1081    }
1082
1083    resetlastvisit($user_id);
1084  }
1085
1086  pwg_mail($email, array(
1087    'subject' => $subject,
1088    'content' => $infos1.get_absolute_root_url(),
1089  ));
1090
1091// **********************
1092// Email sending debugger
1093// This is only to trace
1094// the send of emails for
1095// debugging             
1096// **********************
1097//$content = $infos1.get_absolute_root_url(); 
1098//MailLog($email,$subject,$content,$language);
1099// **********************
1100
1101// Switching back to default language
1102switch_lang_back();
1103}
1104
1105/**
1106 * Function called from functions.inc.php to send notification email when user have been downgraded
1107 *
1108 * @param : user id, username, email address
1109 *
1110 */
1111function demotion_mail($id, $username, $email)
1112{
1113  global $conf;
1114
1115  $conf_UAM = unserialize($conf['UserAdvManager']);
1116 
1117        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1118 
1119        $custom_txt = "";
1120
1121// We have to get the user's language in database
1122  $query ='
1123SELECT user_id, language
1124FROM '.USER_INFOS_TABLE.'
1125WHERE user_id = '.$id.'
1126;';
1127  $data = pwg_db_fetch_assoc(pwg_query($query));
1128
1129// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1130  if (empty($data))
1131  {
1132// And switch gallery to this language before using personalized and multilangual contents
1133    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1134    switch_lang_to($language);
1135  }
1136  else
1137  {
1138// And switch gallery to this language before using personalized and multilangual contents
1139    $language = $data['language']; // Usefull for debugging
1140    switch_lang_to($data['language']);
1141    load_language('plugin.lang', UAM_PATH);
1142  }
1143
1144  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Demotion of %s', stripslashes($username)));
1145     
1146  if (isset($conf_UAM[25]) and $conf_UAM[25] <> '')
1147  {
1148    // Management of Extension flags ([username], [mygallery], [myurl])
1149    $patterns[] = '#\[username\]#i';
1150    $replacements[] = stripslashes($username);
1151    $patterns[] = '#\[mygallery\]#i';
1152    $replacements[] = $conf['gallery_title'];
1153    $patterns[] = '#\[myurl\]#i';
1154    $replacements[] = $conf['gallery_url'];
1155
1156    if (function_exists('get_user_language_desc'))
1157    {
1158      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[25]))."\n\n";
1159    }
1160    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM[25]))."\n\n"; 
1161  }
1162
1163  $infos1 = array(
1164    get_l10n_args('UAM_User: %s', stripslashes($username)),
1165    get_l10n_args('Email: %s', $email),
1166    get_l10n_args('', ''),
1167  );
1168
1169  $infos2 = array
1170  (
1171    get_l10n_args('UAM_Link: %s', ResetConfirmMail($id)),
1172    get_l10n_args('', ''),
1173  ); 
1174
1175  resetlastvisit($id);
1176
1177// Sending the email with subject and contents
1178  pwg_mail($email, array(
1179    'subject' => $subject,
1180    'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url(),
1181  ));
1182
1183// **********************
1184// Email sending debugger
1185// This is only to trace
1186// the send of emails for
1187// debugging             
1188// **********************
1189//$content = ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url();   
1190//MailLog($email,$subject,$content,$language);
1191// **********************
1192
1193// Switching back to default language
1194switch_lang_back();
1195}
1196
1197/**
1198 * Function called from UAM_admin.php to send notification email when user registration have been manually validated by admin
1199 *
1200 * @param : user id
1201 *
1202 */
1203function validation_mail($id)
1204{
1205  global $conf;
1206
1207  $conf_UAM = unserialize($conf['UserAdvManager']);
1208 
1209        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1210 
1211        $custom_txt = "";
1212
1213// We have to get the user's language in database
1214  $query ='
1215SELECT user_id, language
1216FROM '.USER_INFOS_TABLE.'
1217WHERE user_id = '.$id.'
1218;';
1219  $data = pwg_db_fetch_assoc(pwg_query($query));
1220
1221// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1222  if (empty($data))
1223  {
1224// And switch gallery to this language before using personalized and multilangual contents
1225    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1226    switch_lang_to($language);
1227  }
1228  else
1229  {
1230// And switch gallery to this language before using personalized and multilangual contents
1231    $language = $data['language']; // Usefull for debugging
1232    switch_lang_to($data['language']);
1233    load_language('plugin.lang', UAM_PATH);
1234  }
1235
1236// Retreive users email and user name from id
1237  $query ='
1238SELECT id, username, mail_address
1239FROM '.USERS_TABLE.'
1240WHERE id = '.$id.'
1241;';
1242  $result = pwg_db_fetch_assoc(pwg_query($query));
1243
1244  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Validation of %s', stripslashes($result['username'])));
1245     
1246  if (isset($conf_UAM[28]) and $conf_UAM[28] <> '')
1247  {
1248    // Management of Extension flags ([username], [mygallery], [myurl])
1249    $patterns[] = '#\[username\]#i';
1250    $replacements[] = $result['username'];
1251    $patterns[] = '#\[mygallery\]#i';
1252    $replacements[] = $conf['gallery_title'];
1253    $patterns[] = '#\[myurl\]#i';
1254    $replacements[] = $conf['gallery_url'];
1255
1256    if (function_exists('get_user_language_desc'))
1257    {
1258      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[28]))."\n\n";
1259    }
1260    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM[28]))."\n\n"; 
1261  }
1262
1263  $infos = array(
1264    get_l10n_args('UAM_User: %s', stripslashes($result['username'])),
1265    get_l10n_args('Email: %s', $result['mail_address']),
1266    get_l10n_args('', ''),
1267  );
1268
1269// Sending the email with subject and contents
1270  pwg_mail($result['mail_address'], array(
1271    'subject' => $subject,
1272    'content' => (l10n_args($infos)."\n\n".$custom_txt),
1273  ));
1274
1275// **********************
1276// Email sending debugger
1277// This is only to trace
1278// the send of emails for
1279// debugging             
1280// **********************
1281//$email = $result['mail_address'];
1282//$content = (l10n_args($infos)."\n\n".$custom_txt);   
1283//MailLog($email,$subject,$content,$language);
1284// **********************
1285
1286// Switching back to default language
1287switch_lang_back();
1288}
1289
1290/**
1291 * Function called from functions AddConfirmMail and ResetConfirmMail for validation key generation
1292 *
1293 * @return : validation key
1294 *
1295 */
1296function FindAvailableConfirmMailID()
1297{
1298  while (true)
1299  {
1300    $id = generate_key(16);
1301    $query = "
1302SELECT COUNT(*)
1303  FROM ".USER_CONFIRM_MAIL_TABLE."
1304WHERE id = '".$id."'
1305;";
1306    list($count) = pwg_db_fetch_row(pwg_query($query));
1307
1308    if ($count == 0)
1309      return $id;
1310  }
1311}
1312
1313/**
1314 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
1315 *
1316 * @param : User id, email address
1317 *
1318 * @return : Build validation key in URL
1319 *
1320 */
1321function AddConfirmMail($user_id, $email)
1322{
1323  global $conf;
1324
1325  $conf_UAM = unserialize($conf['UserAdvManager']);
1326  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1327
1328  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1329 
1330  if (isset($Confirm_Mail_ID))
1331  {
1332    $query = "
1333SELECT status
1334  FROM ".USER_INFOS_TABLE."
1335WHERE user_id = '".$user_id."'
1336;";
1337    list($status) = pwg_db_fetch_row(pwg_query($query));
1338   
1339    $query = "
1340INSERT INTO ".USER_CONFIRM_MAIL_TABLE."
1341  (id, user_id, mail_address, status, date_check)
1342VALUES
1343  ('".$Confirm_Mail_ID."', '".$user_id."', '".$email."', '".$status."', null)
1344;";
1345    pwg_query($query);
1346
1347    // Delete user from all groups
1348    $query = "
1349DELETE FROM ".USER_GROUP_TABLE."
1350WHERE user_id = '".$user_id."'
1351  AND (
1352    group_id = '".$conf_UAM[2]."'
1353  OR
1354    group_id = '".$conf_UAM[3]."'
1355  )
1356;";
1357    pwg_query($query);
1358
1359    // Set user unvalidated status
1360    if (!is_admin() and $conf_UAM[8] <> -1)
1361    {
1362      $query = "
1363UPDATE ".USER_INFOS_TABLE."
1364SET status = '".$conf_UAM[8]."'
1365WHERE user_id = '".$user_id."'
1366;";
1367      pwg_query($query);
1368    }
1369
1370    // Set user unvalidated group
1371    if (!is_admin() and $conf_UAM[2] <> -1)
1372    {
1373      $query = "
1374INSERT INTO ".USER_GROUP_TABLE."
1375  (user_id, group_id)
1376VALUES
1377  ('".$user_id."', '".$conf_UAM[2]."')
1378;";
1379      pwg_query($query);
1380    }
1381   
1382    return get_absolute_root_url().UAM_PATH.'ConfirmMail.php?key='.$Confirm_Mail_ID.'&userid='.$user_id;
1383  }
1384}
1385
1386/**
1387 * Function called from main.inc.php to set group to new users if manual validation is set
1388 *
1389 * @param : User id
1390 *
1391 *
1392 */
1393function setgroup($user_id)
1394{
1395  global $conf;
1396 
1397  $conf_UAM = unserialize($conf['UserAdvManager']);
1398
1399  $query = "
1400DELETE FROM ".USER_GROUP_TABLE."
1401WHERE user_id = '".$user_id."'
1402  AND (
1403    group_id = '".$conf_UAM[2]."'
1404  OR
1405    group_id = '".$conf_UAM[3]."'
1406  )
1407;";
1408  pwg_query($query);
1409
1410  if (!is_admin() and $conf_UAM[8] <> -1)
1411  {
1412    $query = "
1413UPDATE ".USER_INFOS_TABLE."
1414SET status = '".$conf_UAM[8]."'
1415WHERE user_id = '".$user_id."'
1416;";
1417    pwg_query($query);
1418  }
1419
1420  if (!is_admin() and $conf_UAM[2] <> -1)
1421  {
1422    $query = "
1423INSERT INTO ".USER_GROUP_TABLE."
1424  (user_id, group_id)
1425VALUES
1426  ('".$user_id."', '".$conf_UAM[2]."')
1427;";
1428    pwg_query($query);
1429  }
1430}
1431
1432/**
1433 * Function called from UAM_admin.php to reset validation key
1434 *
1435 * @param : User id
1436 *
1437 * @return : Build validation key in URL
1438 *
1439 */
1440function ResetConfirmMail($user_id)
1441{
1442  global $conf;
1443 
1444  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1445
1446  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1447 
1448  if (isset($Confirm_Mail_ID))
1449  { 
1450    $query = "
1451UPDATE ".USER_CONFIRM_MAIL_TABLE."
1452SET id = '".$Confirm_Mail_ID."'
1453WHERE user_id = '".$user_id."'
1454;";
1455    pwg_query($query);
1456
1457                $query = "
1458UPDATE ".USER_INFOS_TABLE."
1459SET registration_date = '".$dbnow."'
1460WHERE user_id = '".$user_id."'
1461;";
1462                pwg_query($query);
1463   
1464    return get_absolute_root_url().UAM_PATH.'ConfirmMail.php?key='.$Confirm_Mail_ID.'&userid='.$user_id;
1465  }
1466}
1467
1468/**
1469 * Function called from functions.inc.php to reset last visit date after sending a reminder
1470 *
1471 * @param : User id
1472 *
1473 */
1474function resetlastvisit($user_id)
1475{
1476  global $conf;
1477
1478  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1479
1480  $query = "
1481UPDATE ".USER_LASTVISIT_TABLE."
1482SET lastvisit = '".$dbnow."', reminder = 'true'
1483WHERE user_id = '".$user_id."'
1484;";
1485  pwg_query($query);
1486}
1487
1488
1489/**
1490 * Function called from main.inc.php - Triggered on user deletion
1491 *
1492 */
1493function DeleteConfirmMail($user_id)
1494{
1495  $query = "
1496DELETE FROM ".USER_CONFIRM_MAIL_TABLE."
1497WHERE user_id = '".$user_id."'
1498;";
1499  pwg_query($query);
1500}
1501
1502/**
1503 * Function called from main.inc.php - Triggered on user deletion
1504 *
1505 */
1506function DeleteLastVisit($user_id)
1507{
1508  $query = "
1509DELETE FROM ".USER_LASTVISIT_TABLE."
1510WHERE user_id = '".$user_id."'
1511;";
1512  pwg_query($query);
1513}
1514
1515/**
1516 * Function called from main.inc.php - Triggered on user deletion
1517 *
1518 * @param : User id
1519 *
1520 */
1521function DeleteRedir($user_id)
1522{
1523  $tab = array();
1524
1525  $query = '
1526SELECT value
1527FROM '.CONFIG_TABLE.'
1528WHERE param = "UserAdvManager_Redir"
1529;';
1530
1531  $tab = pwg_db_fetch_row(pwg_query($query));
1532 
1533  $values = explode(',', $tab[0]);
1534
1535  unset($values[array_search($user_id, $values)]);
1536     
1537  $query = "
1538UPDATE ".CONFIG_TABLE."
1539SET value = \"".implode(',', $values)."\"
1540WHERE param = 'UserAdvManager_Redir';";
1541
1542  pwg_query($query);
1543}
1544
1545/**
1546 * Function called from ConfirmMail.php to verify validation key used by user according time limit
1547 * Return true is key validation is OK else return false
1548 *
1549 * @param : User id
1550 *
1551 * @return : Bool
1552 *
1553 */
1554function VerifyConfirmMail($id)
1555{
1556  global $conf;
1557
1558  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1559 
1560  $conf_UAM = unserialize($conf['UserAdvManager']);
1561
1562  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1563
1564  $query = "
1565SELECT COUNT(*)
1566FROM ".USER_CONFIRM_MAIL_TABLE."
1567WHERE id = '".$id."'
1568;";
1569  list($count) = pwg_db_fetch_row(pwg_query($query));
1570
1571  if ($count == 1)
1572  {
1573    $query = "
1574SELECT user_id, status, date_check
1575FROM ".USER_CONFIRM_MAIL_TABLE."
1576WHERE id = '".$id."'
1577;";
1578    $data = pwg_db_fetch_assoc(pwg_query($query));
1579
1580    if (!empty($data) and isset($data['user_id']))
1581    {
1582      $query = "
1583SELECT registration_date
1584FROM ".USER_INFOS_TABLE."
1585WHERE user_id = '".$data['user_id']."'
1586;";
1587      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
1588
1589//              Time limit process             
1590// ******************************************** 
1591      if (!empty($registration_date))
1592      {
1593                                // Verify Confirmmail with time limit ON
1594                                if (isset ($conf_UAM_ConfirmMail[1]))
1595                                {
1596                                        // dates formating and compare
1597                                        $today = date("d-m-Y"); // Get today's date
1598                                        list($day, $month, $year) = explode('-', $today); // explode date of today                                               
1599                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
1600                       
1601                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
1602                                        list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
1603                                        $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
1604                       
1605                                        $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
1606                                        $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
1607
1608                                        // Condition with the value set for time limit
1609                                        if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
1610                                        {
1611                                                list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1612
1613                                                $query = '
1614UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1615SET date_check="'.$dbnow.'", reminder="false"
1616WHERE id = "'.$id.'"
1617;';
1618                                                pwg_query($query);
1619     
1620                                                if ($conf_UAM[2] <> -1) // Delete user from unvalidated users group
1621                                                {
1622                                                        $query = "
1623DELETE FROM ".USER_GROUP_TABLE."
1624WHERE user_id = '".$data['user_id']."'
1625  AND group_id = '".$conf_UAM[2]."'
1626;";
1627                                                        pwg_query($query);
1628                                                }
1629           
1630                                                if ($conf_UAM[3] <> -1) // Add user to validated users group
1631                                                {
1632                                                        $query = "
1633INSERT INTO ".USER_GROUP_TABLE."
1634  (user_id, group_id)
1635VALUES
1636  ('".$data['user_id']."', '".$conf_UAM[3]."')
1637;";
1638                                                        pwg_query($query);
1639                                                }
1640
1641                                                if (($conf_UAM[4] <> -1 or isset($data['status']))) // Change user's status
1642                                                {
1643                                                        $query = "
1644UPDATE ".USER_INFOS_TABLE."
1645SET status = '".(isset($data['status']) ? $data['status'] : $conf_UAM[4])."'
1646WHERE user_id = '".$data['user_id']."'
1647;";
1648                                                        pwg_query($query);
1649                                                }
1650                                                // Refresh user's category cache
1651                                                invalidate_user_cache();
1652 
1653                                                return true;
1654                                        }
1655                                        elseif ($deltadays > $conf_UAM_ConfirmMail[1]) // If timelimit exeeds
1656                                        {
1657                                                return false;
1658                                        }
1659                                }
1660                                // Verify Confirmmail with time limit OFF
1661                                else
1662                                {
1663                                        list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1664
1665                                        $query = '
1666UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1667SET date_check="'.$dbnow.'"
1668WHERE id = "'.$id.'"
1669;';
1670                                        pwg_query($query);
1671     
1672                                        if ($conf_UAM[2] <> -1)
1673                                        {
1674                                                $query = "
1675DELETE FROM ".USER_GROUP_TABLE."
1676WHERE user_id = '".$data['user_id']."'
1677AND group_id = '".$conf_UAM[2]."'
1678;";
1679                                                pwg_query($query);
1680                                        }
1681   
1682                                        if ($conf_UAM[3] <> -1)
1683                                        {
1684                                                $query = "
1685DELETE FROM ".USER_GROUP_TABLE."
1686WHERE user_id = '".$data['user_id']."'
1687AND group_id = '".$conf_UAM[3]."'
1688;";
1689                                                pwg_query($query);
1690
1691                                                $query = "
1692INSERT INTO ".USER_GROUP_TABLE."
1693  (user_id, group_id)
1694VALUES
1695  ('".$data['user_id']."', '".$conf_UAM[3]."')
1696;";
1697                                                pwg_query($query);
1698                                        }
1699
1700                                        if (($conf_UAM[4] <> -1 or isset($data['status'])))
1701                                        {
1702                                                $query = "
1703UPDATE ".USER_INFOS_TABLE."
1704SET status = '".(isset($data['status']) ? $data['status'] : $conf_UAM[4])."'
1705WHERE user_id = '".$data['user_id']."'
1706;";
1707                                                pwg_query($query);
1708                                        }
1709                                        // Refresh user's category cache
1710                                        invalidate_user_cache();
1711 
1712                                        return true;
1713                                }
1714                        }
1715                }
1716        }
1717  else
1718    return false;
1719}
1720
1721/**
1722 * Function called from UAM_admin.php to force users validation by admin
1723 *
1724 * @param : User id
1725 *
1726 */
1727function ForceValidation($id)
1728{
1729  global $conf;
1730
1731  $conf_UAM = unserialize($conf['UserAdvManager']);
1732
1733  if (isset($conf_UAM[1]) and $conf_UAM[1] == 'true')
1734  {
1735    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1736
1737                $query = "
1738UPDATE ".USER_CONFIRM_MAIL_TABLE."
1739SET date_check='".$dbnow."'
1740WHERE user_id = '".$id."'
1741;";
1742    pwg_query($query);
1743             
1744                if ($conf_UAM[2] <> -1)
1745                {
1746                        $query = "
1747DELETE FROM ".USER_GROUP_TABLE."
1748WHERE user_id = '".$id."'
1749  AND group_id = '".$conf_UAM[2]."'
1750;";
1751                        pwg_query($query);
1752                }
1753 
1754                if ($conf_UAM[3] <> -1)
1755                {
1756                        $query = "
1757DELETE FROM ".USER_GROUP_TABLE."
1758WHERE user_id = '".$id."'
1759  AND group_id = '".$conf_UAM[3]."'
1760;";
1761      pwg_query($query);
1762       
1763                        $query = "
1764INSERT INTO ".USER_GROUP_TABLE."
1765  (user_id, group_id)
1766VALUES
1767  ('".$id."', '".$conf_UAM[3]."')
1768;";
1769                        pwg_query($query);
1770    }
1771
1772                if ($conf_UAM[4] <> -1)
1773                {
1774                        $query = "
1775UPDATE ".USER_INFOS_TABLE."
1776SET status = '".$conf_UAM[4]."'
1777WHERE user_id = '".$id."'
1778;";
1779                        pwg_query($query);
1780                }
1781  }
1782  elseif (isset($conf_UAM[1]) and $conf_UAM[1] == 'local')
1783  {
1784    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1785
1786    if ($conf_UAM[2] <> -1)
1787    {
1788                  $query = "
1789DELETE FROM ".USER_GROUP_TABLE."
1790WHERE user_id = '".$id."'
1791  AND group_id = '".$conf_UAM[2]."'
1792;";
1793                  pwg_query($query);
1794    }
1795
1796    if ($conf_UAM[3] <> -1)
1797    {
1798      $query = "
1799DELETE FROM ".USER_GROUP_TABLE."
1800WHERE user_id = '".$id."'
1801  AND group_id = '".$conf_UAM[3]."'
1802;";
1803      pwg_query($query);
1804       
1805                  $query = "
1806INSERT INTO ".USER_GROUP_TABLE."
1807  (user_id, group_id)
1808VALUES
1809  ('".$id."', '".$conf_UAM[3]."')
1810;";
1811                  pwg_query($query);
1812    }
1813
1814    if ($conf_UAM[4] <> -1)
1815    {
1816                  $query = "
1817UPDATE ".USER_INFOS_TABLE."
1818SET status = '".$conf_UAM[4]."'
1819WHERE user_id = '".$id."'
1820;";
1821      pwg_query($query);
1822    }
1823  }
1824}
1825
1826/**
1827 * Function called from main.inc.php - Check if username matches forbidden caracters
1828 *
1829 * @param : User login
1830 *
1831 * @return : Bool
1832 *
1833 */
1834function ValidateUsername($login)
1835{
1836  global $conf;
1837
1838  $conf_UAM = unserialize($conf['UserAdvManager']);
1839
1840  if (isset($login) and isset($conf_UAM[7]) and $conf_UAM[7] <> '')
1841  {
1842    $conf_CharExclusion = preg_split("/,/",$conf_UAM[7]);
1843    for ($i = 0 ; $i < count($conf_CharExclusion) ; $i++)
1844    {
1845      $pattern = '/'.$conf_CharExclusion[$i].'/i';
1846      if (preg_match($pattern, $login))
1847      {
1848        return true;
1849      }
1850    }
1851  }
1852  else
1853  {
1854    return false;
1855  }
1856}
1857
1858/**
1859 * Function called from main.inc.php - Check if user's email is in excluded email providers list
1860 * Doesn't work on call - Must be copied in main.inc.php to work
1861 *
1862 * @param : Email address
1863 *
1864 * @return : Bool
1865 *
1866 */
1867function ValidateEmailProvider($email)
1868{
1869  global $conf;
1870
1871  $conf_UAM = unserialize($conf['UserAdvManager']);
1872 
1873        if (isset($email) and isset($conf_UAM[12]) and $conf_UAM[12] <> '')
1874        {
1875                $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM[12]);
1876                for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
1877                {
1878                        $pattern = '/'.$conf_MailExclusion[$i].'/i';
1879                        if (preg_match($pattern, $email))
1880      {
1881                        return true;
1882      }
1883                }
1884        }
1885  else
1886  {
1887    return false;
1888  }
1889}
1890
1891/**
1892 * Function called from UAM_admin.php - Get unvalidated users according time limit
1893 *
1894 * @return : List of users
1895 *
1896 */
1897function get_unvalid_user_list()
1898{
1899        global $conf, $page;
1900         
1901        // Get ConfirmMail configuration
1902  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1903  // Get UAM configuration
1904  $conf_UAM = unserialize($conf['UserAdvManager']);
1905 
1906  $users = array();
1907
1908        // search users depending expiration date
1909  $query = '
1910SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
1911                u.'.$conf['user_fields']['username'].' AS username,
1912                u.'.$conf['user_fields']['email'].' AS email,
1913                ui.status,
1914                ui.enabled_high,
1915                ui.level,
1916                ui.registration_date
1917FROM '.USERS_TABLE.' AS u
1918  INNER JOIN '.USER_INFOS_TABLE.' AS ui
1919    ON u.'.$conf['user_fields']['id'].' = ui.user_id
1920  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
1921    ON u.'.$conf['user_fields']['id'].' = ug.user_id
1922WHERE u.'.$conf['user_fields']['id'].' >= 3
1923  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'"
1924  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail[1].'")';
1925
1926        if ($conf_UAM[2] <> '-1' and $conf_UAM[8] == '-1')
1927  {
1928    $query.= '
1929  AND ug.group_id = '.$conf_UAM[2];
1930  }
1931  if ($conf_UAM[2] == '-1' and $conf_UAM[8] <> '-1')
1932  {
1933    $query.= '
1934  AND ui.status = \''.$conf_UAM[8]."'";
1935  }
1936  if ($conf_UAM[2] <> '-1' and $conf_UAM[8] <> '-1')
1937  {
1938    $query.= '
1939  AND ug.group_id = \''.$conf_UAM[2]."'";
1940  }
1941  $query.= '
1942ORDER BY ui.registration_date ASC
1943;';
1944
1945        $result = pwg_query($query);
1946     
1947  while ($row = pwg_db_fetch_assoc($result))
1948  {
1949        $user = $row;
1950    $user['groups'] = array();
1951
1952    array_push($users, $user);
1953        }
1954
1955        // add group lists
1956  $user_ids = array();
1957  foreach ($users as $i => $user)
1958  {
1959        $user_ids[$i] = $user['id'];
1960        }
1961       
1962        $user_nums = array_flip($user_ids);
1963
1964  if (count($user_ids) > 0)
1965  {
1966        $query = '
1967SELECT user_id, group_id
1968  FROM '.USER_GROUP_TABLE.'
1969WHERE user_id IN ('.implode(',', $user_ids).')
1970;';
1971       
1972                $result = pwg_query($query);
1973       
1974    while ($row = pwg_db_fetch_assoc($result))
1975    {
1976        array_push(
1977        $users[$user_nums[$row['user_id']]]['groups'],
1978        $row['group_id']
1979                        );
1980                }
1981        }
1982
1983        return $users;
1984}
1985
1986/**
1987 * Function called from functions.inc.php - Get all users who haven't validate their registration in configured time
1988 * to delete or remail them automatically
1989 *
1990 * @return : List of users
1991 *
1992 */
1993function get_unvalid_user_autotasks()
1994{
1995        global $conf, $page;
1996         
1997        // Get ConfirmMail configuration
1998  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1999 
2000  $users = array();
2001
2002        // search users depending expiration date
2003  $query = '
2004SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2005                ui.registration_date
2006FROM '.USERS_TABLE.' AS u
2007  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2008    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2009WHERE u.'.$conf['user_fields']['id'].' >= 3
2010  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'")
2011ORDER BY ui.registration_date ASC;';
2012
2013        $result = pwg_query($query);
2014     
2015  while ($row = pwg_db_fetch_assoc($result))
2016  {
2017    array_push($users, $row);
2018        }
2019
2020        return $users;
2021}
2022
2023/**
2024 * Function called from UAM_admin.php - Get ghost users
2025 *
2026 * @return : List of users
2027 *
2028 */
2029function get_ghost_user_list()
2030{
2031        global $conf, $page;
2032
2033  $conf_UAM = unserialize($conf['UserAdvManager']);
2034 
2035  $users = array();
2036
2037        // search users depending expiration date
2038  $query = '
2039SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2040                u.'.$conf['user_fields']['username'].' AS username,
2041                u.'.$conf['user_fields']['email'].' AS email,
2042                lv.lastvisit,
2043                lv.reminder
2044FROM '.USERS_TABLE.' AS u
2045  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2046    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2047WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[17].'")
2048ORDER BY lv.lastvisit ASC;';
2049
2050        $result = pwg_query($query);
2051     
2052  while ($row = pwg_db_fetch_assoc($result))
2053  {
2054        $user = $row;
2055    $user['groups'] = array();
2056
2057    array_push($users, $user);
2058        }
2059
2060        // add group lists
2061  $user_ids = array();
2062  foreach ($users as $i => $user)
2063  {
2064        $user_ids[$i] = $user['id'];
2065        }
2066
2067        return $users;
2068}
2069
2070
2071/**
2072 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
2073 *
2074 * @return : List of users to delete or downgrade automatically
2075 *
2076 */
2077function get_ghosts_autotasks()
2078{
2079        global $conf, $page;
2080
2081  $conf_UAM = unserialize($conf['UserAdvManager']);
2082 
2083  $users = array();
2084 
2085        // search users depending expiration date and reminder sent
2086  $query = '
2087SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2088                lv.lastvisit
2089FROM '.USERS_TABLE.' AS u
2090  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2091    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2092WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[17].'")
2093ORDER BY lv.lastvisit ASC;';
2094
2095        $result = pwg_query($query);
2096     
2097  while ($row = pwg_db_fetch_assoc($result))
2098  {
2099    array_push($users, $row);
2100        }
2101 
2102        return $users;
2103}
2104
2105
2106/**
2107 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
2108 *
2109 * @return : List of users
2110 *
2111 */
2112function get_user_list()
2113{
2114        global $conf, $page;
2115 
2116  $users = array();
2117
2118        // search users depending expiration date
2119  $query = '
2120SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2121                u.'.$conf['user_fields']['username'].' AS username,
2122                u.'.$conf['user_fields']['email'].' AS email,
2123                ug.lastvisit
2124FROM '.USERS_TABLE.' AS u
2125  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
2126    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2127WHERE u.'.$conf['user_fields']['id'].' >= 3
2128ORDER BY ug.lastvisit DESC
2129;';
2130
2131        $result = pwg_query($query);
2132     
2133  while ($row = pwg_db_fetch_assoc($result))
2134  {
2135        $user = $row;
2136    $user['groups'] = array();
2137
2138    array_push($users, $user);
2139        }
2140
2141        // add group lists
2142  $user_ids = array();
2143  foreach ($users as $i => $user)
2144  {
2145        $user_ids[$i] = $user['id'];
2146        }
2147
2148        return $users;
2149}
2150
2151/**
2152 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
2153 *
2154 * @param : user id
2155 *
2156 * @return : Bool
2157 *
2158 */
2159function expiration($id)
2160{
2161        global $conf, $page;
2162         
2163        // Get ConfirmMail configuration
2164  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2165         
2166        // Get UAM configuration
2167  $conf_UAM = unserialize($conf['UserAdvManager']);
2168       
2169        $query = "
2170SELECT registration_date
2171  FROM ".USER_INFOS_TABLE."
2172WHERE user_id = '".$id."'
2173;";
2174        list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2175
2176//              Time limit process             
2177// ******************************************** 
2178        if (!empty($registration_date))
2179  {
2180                // dates formating and compare
2181                $today = date("d-m-Y"); // Get today's date
2182                list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2183                $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2184               
2185          list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2186                list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2187                $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2188                       
2189                $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
2190                $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2191
2192                // Condition with the value set for time limit
2193                if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
2194                {
2195                        return false;
2196                }
2197                else
2198                {
2199                        return true;
2200                }
2201        }
2202}
2203
2204
2205/**
2206 * Returns a password's score for password complexity check
2207 *
2208 * @param : password filled by user
2209 *
2210 * @return : Score calculation
2211 *
2212 * Thanx to MathieuGut from http://m-gut.developpez.com
2213 */
2214function testpassword($password) // Le mot de passe passé en paramètre - $password given by user
2215{
2216
2217  // Initialisation des variables - Variables initiation
2218  $points = 0;
2219  $point_lowercase = 0;
2220  $point_uppercase = 0;
2221  $point_numbers = 0;
2222  $point_characters = 0;
2223
2224  // On récupère la longueur du mot de passe - Getting password lengh   
2225  $length = strlen($password);
2226 
2227  // On fait une boucle pour lire chaque lettre - Loop to read password characters
2228  for($i = 0; $i < $length; $i++)
2229  {
2230    // On sélectionne une à une chaque lettre - Select each letters
2231    // $i étant à 0 lors du premier passage de la boucle - $i is 0 at first turn
2232    $letters = $password[$i];
2233
2234    if ($letters>='a' && $letters<='z')
2235    {
2236      // On ajoute 1 point pour une minuscule - Adding 1 point to score for a lowercase
2237                  $points = $points + 1;
2238
2239                  // On rajoute le bonus pour une minuscule - Adding bonus points for lowercase
2240                  $point_lowercase = 1;
2241    }
2242    else if ($letters>='A' && $letters <='Z')
2243    {
2244      // On ajoute 2 points pour une majuscule - Adding 2 points to score for uppercase
2245      $points = $points + 2;
2246               
2247      // On rajoute le bonus pour une majuscule - Adding bonus points for uppercase
2248      $point_uppercase = 2;
2249    }
2250    else if ($letters>='0' && $letters<='9')
2251    {
2252      // On ajoute 3 points pour un chiffre - Adding 3 points to score for numbers
2253      $points = $points + 3;
2254               
2255      // On rajoute le bonus pour un chiffre - Adding bonus points for numbers
2256      $point_numbers = 3;
2257    }
2258    else
2259    {
2260      // On ajoute 5 points pour un caractère autre - Adding 5 points to score for special characters
2261      $points = $points + 5;
2262               
2263      // On rajoute le bonus pour un caractère autre - Adding bonus points for special characters
2264      $point_characters = 5;
2265    }
2266  }
2267
2268  // Calcul du coefficient points/longueur - calculating the coefficient points/length
2269  $step1 = $points / $length;
2270
2271  // Calcul du coefficient de la diversité des types de caractères... - Calculation of the diversity of character types...
2272  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
2273
2274  // Multiplication du coefficient de diversité avec celui de la longueur - Multiplying the coefficient of diversity with that of the length
2275  $score = $step1 * $step2;
2276
2277  // Multiplication du resultat par la longueur de la chaine - Multiplying the result by the length of the string
2278  $finalscore = $score * $length;
2279
2280  return $finalscore;
2281}
2282
2283/**
2284 * Function called from maintain.inc.php - to check if database upgrade is needed
2285 *
2286 * @param : table name
2287 *
2288 * @return : boolean
2289 *
2290 */
2291function table_exist($table)
2292{
2293  $query = 'DESC '.$table.';';
2294  return (bool)($res=pwg_query($query));
2295}
2296
2297// Email sending debugger function
2298function MailLog($to, $subject, $content, $language)
2299{
2300   $fo=fopen (UAM_PATH.'admin/maillog.txt','a') ;
2301   fwrite($fo,"======================\n") ;
2302   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
2303   fwrite($fo,$to . "\n" . $subject . "\r\n") ;
2304   fwrite($fo, "\n" . $content . "\r\n") ;
2305   fwrite($fo, 'Langue : '."\n" . $language . "\r\n") ;
2306   fclose($fo) ;
2307   //return mail ($to,$subject) ;
2308}
2309
2310/**
2311 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
2312 *
2313 * @param : plugin directory
2314 *
2315 * @return : plugin's version and name
2316 *
2317 */
2318function PluginInfos($dir)
2319{
2320  $path = $dir;
2321
2322  $plg_data = implode( '', file($path.'main.inc.php') );
2323  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
2324  {
2325    $plugin['name'] = trim( $val[1] );
2326  }
2327  if (preg_match("|Version: (.*)|", $plg_data, $val))
2328  {
2329    $plugin['version'] = trim($val[1]);
2330  }
2331  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
2332  {
2333    $plugin['uri'] = trim($val[1]);
2334  }
2335  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
2336  {
2337    $plugin['description'] = trim($desc);
2338  }
2339  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
2340  {
2341    $plugin['description'] = trim($val[1]);
2342  }
2343  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
2344  {
2345    $plugin['author'] = trim($val[1]);
2346  }
2347  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
2348  {
2349    $plugin['author uri'] = trim($val[1]);
2350  }
2351  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
2352  {
2353    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
2354    if (is_numeric($extension)) $plugin['extension'] = $extension;
2355  }
2356// IMPORTANT SECURITY !
2357  $plugin = array_map('htmlspecialchars', $plugin);
2358
2359  return $plugin ;
2360}
2361
2362
2363function clean_obsolete_files()
2364{
2365  if (file_exists(UAM_PATH.'obsolete.list')
2366    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
2367    and !empty($old_files))
2368  {
2369    array_push($old_files, 'obsolete.list');
2370    foreach($old_files as $old_file)
2371    {
2372      $path = UAM_PATH.$old_file;
2373      if (is_file($path))
2374      {
2375        @unlink($path);
2376      }
2377    }
2378  }
2379}
2380
2381/**
2382 * UAM_check_profile - Thx to LucMorizur
2383 * checks if a user id is registered as having already
2384 * visited his profile.php page.
2385 *
2386 * @uid        : the user id
2387 *
2388 * @user_idsOK : (returned) array of all users ids having already visited
2389 *               their profile.php pages
2390 *
2391 * @returns    : true or false whether the users has already visited his
2392 *               profile.php page or not
2393 *
2394 */
2395function UAM_check_profile($uid, &$user_idsOK)
2396{
2397  $t = array();
2398  $v = false;
2399 
2400  $query = "
2401SELECT value
2402FROM ".CONFIG_TABLE."
2403WHERE param = 'UserAdvManager_Redir'
2404;";
2405 
2406  if ($v = (($t = pwg_db_fetch_row(pwg_query($query))) !== false))
2407  {
2408    $user_idsOK = explode(',', $t[0]);
2409    $v = (in_array($uid, $user_idsOK));
2410  }
2411  return $v;
2412}
2413?>
Note: See TracBrowser for help on using the repository browser.