source: extensions/UserAdvManager/branches/2.20/include/functions.inc.php @ 10145

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

r10144 merged from trunk to branch 2.20

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