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

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

bug 2265 fixed : Add of a new option to display or not user's password in information email
Improving UAM version check for db upgrade
Version 2.20.4 hard coded

  • Property svn:eol-style set to LF
File size: 65.8 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    if (isset($conf_UAM[35]) and $conf_UAM[35] == 'false') // Allow display of clear password in email
861    {
862      $infos1 = array(
863        get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
864        get_l10n_args('UAM_User: %s', stripslashes($username)),
865        get_l10n_args('UAM_Password: %s', $password),
866        get_l10n_args('Email: %s', $email),
867        get_l10n_args('', ''),
868      );
869    }
870    else // Do not allow display of clear password in email
871    {
872      $infos1 = array(
873        get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
874        get_l10n_args('UAM_User: %s', stripslashes($username)),
875        get_l10n_args('Email: %s', $email),
876        get_l10n_args('', ''),
877      );
878    }
879  }
880
881  if ( isset($conf_UAM[1]) and $conf_UAM[1] == 'true' and $confirm)
882  {
883    $infos2 = array
884    (
885      get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
886      get_l10n_args('', ''),
887    );
888
889    if (isset($conf_UAM[10]) and $conf_UAM[10] <> '')
890    {
891      // Management of Extension flags ([username], [mygallery], [myurl])
892      $patterns[] = '#\[username\]#i';
893      $replacements[] = $username;
894      $patterns[] = '#\[mygallery\]#i';
895      $replacements[] = $conf['gallery_title'];
896      $patterns[] = '#\[myurl\]#i';
897      $replacements[] = $conf['gallery_url'];
898     
899      if (function_exists('get_user_language_desc'))
900      {
901        $infos2_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[10]))."\n\n";
902      }
903      else $infos2_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM[10]))."\n\n";
904    }
905  }
906
907// ********************************************************
908// **** Pending code since to find how to make it work ****
909// ********************************************************
910// Testing if FCK Editor is used. Then decoding htmlchars to avoid problems with pwg_mail()
911/*$areas = array();
912array_push( $areas,'UAM_MailInfo_Text','UAM_ConfirmMail_Text');
913
914if (function_exists('set_fckeditor_instance'))
915{
916  $fcke_config = unserialize($conf['FCKEditor']);
917  foreach($areas as $area)
918  {
919    if (isset($fcke_config['UAM_MailInfo_Text']) and $fcke_config['UAM_MailInfo_Text'] = true)
920    {
921      $infos1_perso = html_entity_decode($infos1_perso,ENT_QUOTES,UTF-8);
922    }
923   
924    if (isset($fcke_config['UAM_ConfirmMail_Text']) and $fcke_config['UAM_ConfirmMail_Text'] = true)
925    {
926      $infos2_perso = html_entity_decode($infos2_perso,ENT_QUOTES,UTF-8);
927    }
928  }
929}*/
930
931
932// Sending the email with subject and contents
933  pwg_mail($email, array(
934    'subject' => $subject,
935    'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
936  ));
937
938// Switching back to default language
939switch_lang_back();
940}
941
942
943/**
944 * Function called from UAM_admin.php to resend validation email with or without new validation key
945 *
946 * @param : Type of email, user id, username, email address, confirmation (optional)
947 *
948 */
949function ResendMail2User($typemail, $user_id, $username, $email, $confirm)
950{
951  global $conf;
952
953  $conf_UAM = unserialize($conf['UserAdvManager']);
954
955  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
956 
957        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
958 
959// We have to get the user's language in database
960  $query ='
961SELECT user_id, language
962FROM '.USER_INFOS_TABLE.'
963WHERE user_id = '.$user_id.'
964;';
965  $data = pwg_db_fetch_assoc(pwg_query($query));
966  $language = $data['language'];
967 
968// And switch gallery to this language before using personalized and multilangual contents
969  switch_lang_to($data['language']);
970   
971  load_language('plugin.lang', UAM_PATH);
972
973  switch($typemail)
974  {
975    case 1:
976      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Reminder_with_key_of_%s', $username));
977     
978      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)
979      {
980        // Management of Extension flags ([username], [mygallery], [myurl])
981        $patterns[] = '#\[username\]#i';
982        $replacements[] = $username;
983        $patterns[] = '#\[mygallery\]#i';
984        $replacements[] = $conf['gallery_title'];
985        $patterns[] = '#\[myurl\]#i';
986        $replacements[] = $conf['gallery_url'];
987
988        if (function_exists('get_user_language_desc'))
989        {
990          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[2]))."\n\n";
991        }
992                                else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[2]))."\n\n";
993
994        $infos2 = array
995        (
996          get_l10n_args('UAM_Link: %s', ResetConfirmMail($user_id)),
997          get_l10n_args('', ''),
998        );       
999                        }
1000
1001// Set reminder true     
1002      $query = "
1003UPDATE ".USER_CONFIRM_MAIL_TABLE."
1004SET reminder = 'true'
1005WHERE user_id = '".$user_id."'
1006;";
1007      pwg_query($query);
1008     
1009                break;
1010     
1011    case 2:
1012      $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Reminder_without_key_of_%s',$username));
1013     
1014      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)
1015      {
1016        // Management of Extension flags ([username], [mygallery], [myurl])
1017        $patterns[] = '#\[username\]#i';
1018        $replacements[] = $username;
1019        $patterns[] = '#\[mygallery\]#i';
1020        $replacements[] = $conf['gallery_title'];
1021        $patterns[] = '#\[myurl\]#i';
1022        $replacements[] = $conf['gallery_url'];
1023       
1024        if (function_exists('get_user_language_desc'))
1025        {
1026          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[4]))."\n\n";
1027        }
1028        else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[4]))."\n\n";
1029      }
1030     
1031// Set reminder true     
1032      $query = "
1033UPDATE ".USER_CONFIRM_MAIL_TABLE."
1034SET reminder = 'true'
1035WHERE user_id = '".$user_id."'
1036;";
1037      pwg_query($query);
1038     
1039    break;
1040        }
1041 
1042  pwg_mail($email, array(
1043    'subject' => $subject,
1044    'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1045  ));
1046
1047// Switching back to default language
1048switch_lang_back();
1049}
1050
1051
1052/**
1053 * Function called from UAM_admin.php to send a reminder mail for ghost users
1054 *
1055 * @param : User id, username, email address
1056 *
1057 */
1058function ghostreminder($user_id, $username, $email)
1059{
1060  global $conf;
1061
1062  $conf_UAM = unserialize($conf['UserAdvManager']);
1063 
1064        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1065 
1066        $infos1_perso = "";
1067
1068// We have to get the user's language in database
1069  $query ='
1070SELECT user_id, language
1071FROM '.USER_INFOS_TABLE.'
1072WHERE user_id = '.$user_id.'
1073;';
1074  $data = pwg_db_fetch_assoc(pwg_query($query));
1075  $language = $data['language'];
1076
1077// And switch gallery to this language before using personalized and multilangual contents
1078  switch_lang_to($data['language']);
1079   
1080  load_language('plugin.lang', UAM_PATH);
1081 
1082  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Ghost_reminder_of_%s', $username));     
1083
1084  if (isset($conf_UAM[18]) and $conf_UAM[18] <> '' and isset($conf_UAM[16]) and $conf_UAM[16] == 'true')
1085  {
1086    // Management of Extension flags ([username], [mygallery], [myurl])
1087    $patterns[] = '#\[username\]#i';
1088    $replacements[] = $username;
1089    $patterns[] = '#\[mygallery\]#i';
1090    $replacements[] = $conf['gallery_title'];
1091    $patterns[] = '#\[myurl\]#i';
1092    $replacements[] = $conf['gallery_url'];
1093
1094    if (function_exists('get_user_language_desc'))
1095    {
1096      $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[18]))."\n\n";
1097    }
1098    else
1099    {
1100      $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM[18]))."\n\n";
1101    }
1102
1103    resetlastvisit($user_id);
1104  }
1105
1106  pwg_mail($email, array(
1107    'subject' => $subject,
1108    'content' => $infos1.get_absolute_root_url(),
1109  ));
1110
1111// Switching back to default language
1112switch_lang_back();
1113}
1114
1115
1116/**
1117 * Function called from functions.inc.php to send notification email when user have been downgraded
1118 *
1119 * @param : user id, username, email address
1120 *
1121 */
1122function demotion_mail($id, $username, $email)
1123{
1124  global $conf;
1125
1126  $conf_UAM = unserialize($conf['UserAdvManager']);
1127 
1128        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1129 
1130        $custom_txt = "";
1131
1132// We have to get the user's language in database
1133  $query ='
1134SELECT user_id, language
1135FROM '.USER_INFOS_TABLE.'
1136WHERE user_id = '.$id.'
1137;';
1138  $data = pwg_db_fetch_assoc(pwg_query($query));
1139
1140// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1141  if (empty($data))
1142  {
1143// And switch gallery to this language before using personalized and multilangual contents
1144    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1145    switch_lang_to($language);
1146  }
1147  else
1148  {
1149// And switch gallery to this language before using personalized and multilangual contents
1150    $language = $data['language']; // Usefull for debugging
1151    switch_lang_to($data['language']);
1152    load_language('plugin.lang', UAM_PATH);
1153  }
1154
1155  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Demotion of %s', stripslashes($username)));
1156     
1157  if (isset($conf_UAM[25]) and $conf_UAM[25] <> '')
1158  {
1159    // Management of Extension flags ([username], [mygallery], [myurl])
1160    $patterns[] = '#\[username\]#i';
1161    $replacements[] = stripslashes($username);
1162    $patterns[] = '#\[mygallery\]#i';
1163    $replacements[] = $conf['gallery_title'];
1164    $patterns[] = '#\[myurl\]#i';
1165    $replacements[] = $conf['gallery_url'];
1166
1167    if (function_exists('get_user_language_desc'))
1168    {
1169      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[25]))."\n\n";
1170    }
1171    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM[25]))."\n\n"; 
1172  }
1173
1174  $infos1 = array(
1175    get_l10n_args('UAM_User: %s', stripslashes($username)),
1176    get_l10n_args('Email: %s', $email),
1177    get_l10n_args('', ''),
1178  );
1179
1180  $infos2 = array
1181  (
1182    get_l10n_args('UAM_Link: %s', ResetConfirmMail($id)),
1183    get_l10n_args('', ''),
1184  ); 
1185
1186  resetlastvisit($id);
1187
1188// Sending the email with subject and contents
1189  pwg_mail($email, array(
1190    'subject' => $subject,
1191    'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url(),
1192  ));
1193
1194// Switching back to default language
1195switch_lang_back();
1196}
1197
1198
1199/**
1200 * Function called from UAM_admin.php to send notification email when user registration have been manually validated by admin
1201 *
1202 * @param : user id
1203 *
1204 */
1205function validation_mail($id)
1206{
1207  global $conf;
1208
1209  $conf_UAM = unserialize($conf['UserAdvManager']);
1210 
1211        include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1212 
1213        $custom_txt = "";
1214
1215// We have to get the user's language in database
1216  $query ='
1217SELECT user_id, language
1218FROM '.USER_INFOS_TABLE.'
1219WHERE user_id = '.$id.'
1220;';
1221  $data = pwg_db_fetch_assoc(pwg_query($query));
1222
1223// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1224  if (empty($data))
1225  {
1226// And switch gallery to this language before using personalized and multilangual contents
1227    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1228    switch_lang_to($language);
1229  }
1230  else
1231  {
1232// And switch gallery to this language before using personalized and multilangual contents
1233    $language = $data['language']; // Usefull for debugging
1234    switch_lang_to($data['language']);
1235    load_language('plugin.lang', UAM_PATH);
1236  }
1237
1238// Retreive users email and user name from id
1239  $query ='
1240SELECT id, username, mail_address
1241FROM '.USERS_TABLE.'
1242WHERE id = '.$id.'
1243;';
1244  $result = pwg_db_fetch_assoc(pwg_query($query));
1245
1246  $subject = '['.$conf['gallery_title'].'] '.l10n_args(get_l10n_args('UAM_Validation of %s', stripslashes($result['username'])));
1247     
1248  if (isset($conf_UAM[28]) and $conf_UAM[28] <> '')
1249  {
1250    // Management of Extension flags ([username], [mygallery], [myurl])
1251    $patterns[] = '#\[username\]#i';
1252    $replacements[] = $result['username'];
1253    $patterns[] = '#\[mygallery\]#i';
1254    $replacements[] = $conf['gallery_title'];
1255    $patterns[] = '#\[myurl\]#i';
1256    $replacements[] = $conf['gallery_url'];
1257
1258    if (function_exists('get_user_language_desc'))
1259    {
1260      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[28]))."\n\n";
1261    }
1262    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM[28]))."\n\n"; 
1263  }
1264
1265  $infos = array(
1266    get_l10n_args('UAM_User: %s', stripslashes($result['username'])),
1267    get_l10n_args('Email: %s', $result['mail_address']),
1268    get_l10n_args('', ''),
1269  );
1270
1271// Sending the email with subject and contents
1272  pwg_mail($result['mail_address'], array(
1273    'subject' => $subject,
1274    'content' => (l10n_args($infos)."\n\n".$custom_txt),
1275  ));
1276
1277// Switching back to default language
1278switch_lang_back();
1279}
1280
1281
1282/**
1283 * Function called from functions AddConfirmMail and ResetConfirmMail for validation key generation
1284 *
1285 * @return : validation key
1286 *
1287 */
1288function FindAvailableConfirmMailID()
1289{
1290  while (true)
1291  {
1292    $id = generate_key(16);
1293    $query = "
1294SELECT COUNT(*)
1295  FROM ".USER_CONFIRM_MAIL_TABLE."
1296WHERE id = '".$id."'
1297;";
1298    list($count) = pwg_db_fetch_row(pwg_query($query));
1299
1300    if ($count == 0)
1301      return $id;
1302  }
1303}
1304
1305
1306/**
1307 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
1308 *
1309 * @param : User id, email address
1310 *
1311 * @return : Build validation key in URL
1312 *
1313 */
1314function AddConfirmMail($user_id, $email)
1315{
1316  global $conf;
1317
1318  $conf_UAM = unserialize($conf['UserAdvManager']);
1319  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1320
1321  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1322 
1323  if (isset($Confirm_Mail_ID))
1324  {
1325    $query = "
1326SELECT status
1327  FROM ".USER_INFOS_TABLE."
1328WHERE user_id = '".$user_id."'
1329;";
1330    list($status) = pwg_db_fetch_row(pwg_query($query));
1331   
1332    $query = "
1333INSERT INTO ".USER_CONFIRM_MAIL_TABLE."
1334  (id, user_id, mail_address, status, date_check)
1335VALUES
1336  ('".$Confirm_Mail_ID."', '".$user_id."', '".$email."', '".$status."', null)
1337;";
1338    pwg_query($query);
1339
1340    // Delete user from all groups
1341    $query = "
1342DELETE FROM ".USER_GROUP_TABLE."
1343WHERE user_id = '".$user_id."'
1344  AND (
1345    group_id = '".$conf_UAM[2]."'
1346  OR
1347    group_id = '".$conf_UAM[3]."'
1348  )
1349;";
1350    pwg_query($query);
1351
1352    // Set user unvalidated status
1353    if (!is_admin() and $conf_UAM[8] <> -1)
1354    {
1355      $query = "
1356UPDATE ".USER_INFOS_TABLE."
1357SET status = '".$conf_UAM[8]."'
1358WHERE user_id = '".$user_id."'
1359;";
1360      pwg_query($query);
1361    }
1362
1363    // Set user unvalidated group
1364    if (!is_admin() and $conf_UAM[2] <> -1)
1365    {
1366      $query = "
1367INSERT INTO ".USER_GROUP_TABLE."
1368  (user_id, group_id)
1369VALUES
1370  ('".$user_id."', '".$conf_UAM[2]."')
1371;";
1372      pwg_query($query);
1373    }
1374   
1375    return get_absolute_root_url().UAM_PATH.'ConfirmMail.php?key='.$Confirm_Mail_ID.'&userid='.$user_id;
1376  }
1377}
1378
1379
1380/**
1381 * Function called from main.inc.php to set group to new users if manual validation is set
1382 *
1383 * @param : User id
1384 *
1385 *
1386 */
1387function setgroup($user_id)
1388{
1389  global $conf;
1390 
1391  $conf_UAM = unserialize($conf['UserAdvManager']);
1392
1393  $query = "
1394DELETE FROM ".USER_GROUP_TABLE."
1395WHERE user_id = '".$user_id."'
1396  AND (
1397    group_id = '".$conf_UAM[2]."'
1398  OR
1399    group_id = '".$conf_UAM[3]."'
1400  )
1401;";
1402  pwg_query($query);
1403
1404  if (!is_admin() and $conf_UAM[8] <> -1)
1405  {
1406    $query = "
1407UPDATE ".USER_INFOS_TABLE."
1408SET status = '".$conf_UAM[8]."'
1409WHERE user_id = '".$user_id."'
1410;";
1411    pwg_query($query);
1412  }
1413
1414  if (!is_admin() and $conf_UAM[2] <> -1)
1415  {
1416    $query = "
1417INSERT INTO ".USER_GROUP_TABLE."
1418  (user_id, group_id)
1419VALUES
1420  ('".$user_id."', '".$conf_UAM[2]."')
1421;";
1422    pwg_query($query);
1423  }
1424}
1425
1426
1427/**
1428 * Function called from UAM_admin.php to reset validation key
1429 *
1430 * @param : User id
1431 *
1432 * @return : Build validation key in URL
1433 *
1434 */
1435function ResetConfirmMail($user_id)
1436{
1437  global $conf;
1438 
1439  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1440
1441  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1442 
1443  if (isset($Confirm_Mail_ID))
1444  { 
1445    $query = "
1446UPDATE ".USER_CONFIRM_MAIL_TABLE."
1447SET id = '".$Confirm_Mail_ID."'
1448WHERE user_id = '".$user_id."'
1449;";
1450    pwg_query($query);
1451
1452                $query = "
1453UPDATE ".USER_INFOS_TABLE."
1454SET registration_date = '".$dbnow."'
1455WHERE user_id = '".$user_id."'
1456;";
1457                pwg_query($query);
1458   
1459    return get_absolute_root_url().UAM_PATH.'ConfirmMail.php?key='.$Confirm_Mail_ID.'&userid='.$user_id;
1460  }
1461}
1462
1463
1464/**
1465 * Function called from functions.inc.php to reset last visit date after sending a reminder
1466 *
1467 * @param : User id
1468 *
1469 */
1470function resetlastvisit($user_id)
1471{
1472  global $conf;
1473
1474  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1475
1476  $query = "
1477UPDATE ".USER_LASTVISIT_TABLE."
1478SET lastvisit = '".$dbnow."', reminder = 'true'
1479WHERE user_id = '".$user_id."'
1480;";
1481  pwg_query($query);
1482}
1483
1484
1485/**
1486 * Function called from main.inc.php - Triggered on user deletion
1487 *
1488 */
1489function DeleteConfirmMail($user_id)
1490{
1491  $query = "
1492DELETE FROM ".USER_CONFIRM_MAIL_TABLE."
1493WHERE user_id = '".$user_id."'
1494;";
1495  pwg_query($query);
1496}
1497
1498/**
1499 * Function called from main.inc.php - Triggered on user deletion
1500 *
1501 */
1502function DeleteLastVisit($user_id)
1503{
1504  $query = "
1505DELETE FROM ".USER_LASTVISIT_TABLE."
1506WHERE user_id = '".$user_id."'
1507;";
1508  pwg_query($query);
1509}
1510
1511
1512/**
1513 * Function called from main.inc.php - Triggered on user deletion
1514 *
1515 * @param : User id
1516 *
1517 */
1518function DeleteRedir($user_id)
1519{
1520  $tab = array();
1521
1522  $query = '
1523SELECT value
1524FROM '.CONFIG_TABLE.'
1525WHERE param = "UserAdvManager_Redir"
1526;';
1527
1528  $tab = pwg_db_fetch_row(pwg_query($query));
1529 
1530  $values = explode(',', $tab[0]);
1531
1532  unset($values[array_search($user_id, $values)]);
1533     
1534  $query = "
1535UPDATE ".CONFIG_TABLE."
1536SET value = \"".implode(',', $values)."\"
1537WHERE param = 'UserAdvManager_Redir';";
1538
1539  pwg_query($query);
1540}
1541
1542
1543/**
1544 * Function called from ConfirmMail.php to verify validation key used by user according time limit
1545 * Return true is key validation is OK else return false
1546 *
1547 * @param : User id
1548 *
1549 * @return : Bool
1550 *
1551 */
1552function VerifyConfirmMail($id)
1553{
1554  global $conf;
1555
1556  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
1557 
1558  $conf_UAM = unserialize($conf['UserAdvManager']);
1559
1560  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1561
1562  $query = "
1563SELECT COUNT(*)
1564FROM ".USER_CONFIRM_MAIL_TABLE."
1565WHERE id = '".$id."'
1566;";
1567  list($count) = pwg_db_fetch_row(pwg_query($query));
1568
1569  if ($count == 1)
1570  {
1571    $query = "
1572SELECT user_id, status, date_check
1573FROM ".USER_CONFIRM_MAIL_TABLE."
1574WHERE id = '".$id."'
1575;";
1576    $data = pwg_db_fetch_assoc(pwg_query($query));
1577
1578    if (!empty($data) and isset($data['user_id']))
1579    {
1580      $query = "
1581SELECT registration_date
1582FROM ".USER_INFOS_TABLE."
1583WHERE user_id = '".$data['user_id']."'
1584;";
1585      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
1586
1587//              Time limit process             
1588// ******************************************** 
1589      if (!empty($registration_date))
1590      {
1591                                // Verify Confirmmail with time limit ON
1592                                if (isset ($conf_UAM_ConfirmMail[1]))
1593                                {
1594                                        // dates formating and compare
1595                                        $today = date("d-m-Y"); // Get today's date
1596                                        list($day, $month, $year) = explode('-', $today); // explode date of today                                               
1597                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
1598                       
1599                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
1600                                        list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
1601                                        $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
1602                       
1603                                        $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
1604                                        $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
1605
1606                                        // Condition with the value set for time limit
1607                                        if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
1608                                        {
1609                                                list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1610
1611                                                $query = '
1612UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1613SET date_check="'.$dbnow.'", reminder="false"
1614WHERE id = "'.$id.'"
1615;';
1616                                                pwg_query($query);
1617     
1618                                                if ($conf_UAM[2] <> -1) // Delete user from unvalidated users group
1619                                                {
1620                                                        $query = "
1621DELETE FROM ".USER_GROUP_TABLE."
1622WHERE user_id = '".$data['user_id']."'
1623  AND group_id = '".$conf_UAM[2]."'
1624;";
1625                                                        pwg_query($query);
1626                                                }
1627           
1628                                                if ($conf_UAM[3] <> -1) // Add user to validated users group
1629                                                {
1630                                                        $query = "
1631INSERT INTO ".USER_GROUP_TABLE."
1632  (user_id, group_id)
1633VALUES
1634  ('".$data['user_id']."', '".$conf_UAM[3]."')
1635;";
1636                                                        pwg_query($query);
1637                                                }
1638
1639                                                if (($conf_UAM[4] <> -1 or isset($data['status']))) // Change user's status
1640                                                {
1641                                                        $query = "
1642UPDATE ".USER_INFOS_TABLE."
1643SET status = '".(isset($data['status']) ? $data['status'] : $conf_UAM[4])."'
1644WHERE user_id = '".$data['user_id']."'
1645;";
1646                                                        pwg_query($query);
1647                                                }
1648                                                // Refresh user's category cache
1649                                                invalidate_user_cache();
1650 
1651                                                return true;
1652                                        }
1653                                        elseif ($deltadays > $conf_UAM_ConfirmMail[1]) // If timelimit exeeds
1654                                        {
1655                                                return false;
1656                                        }
1657                                }
1658                                // Verify Confirmmail with time limit OFF
1659                                else
1660                                {
1661                                        list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1662
1663                                        $query = '
1664UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1665SET date_check="'.$dbnow.'"
1666WHERE id = "'.$id.'"
1667;';
1668                                        pwg_query($query);
1669     
1670                                        if ($conf_UAM[2] <> -1)
1671                                        {
1672                                                $query = "
1673DELETE FROM ".USER_GROUP_TABLE."
1674WHERE user_id = '".$data['user_id']."'
1675AND group_id = '".$conf_UAM[2]."'
1676;";
1677                                                pwg_query($query);
1678                                        }
1679   
1680                                        if ($conf_UAM[3] <> -1)
1681                                        {
1682                                                $query = "
1683DELETE FROM ".USER_GROUP_TABLE."
1684WHERE user_id = '".$data['user_id']."'
1685AND group_id = '".$conf_UAM[3]."'
1686;";
1687                                                pwg_query($query);
1688
1689                                                $query = "
1690INSERT INTO ".USER_GROUP_TABLE."
1691  (user_id, group_id)
1692VALUES
1693  ('".$data['user_id']."', '".$conf_UAM[3]."')
1694;";
1695                                                pwg_query($query);
1696                                        }
1697
1698                                        if (($conf_UAM[4] <> -1 or isset($data['status'])))
1699                                        {
1700                                                $query = "
1701UPDATE ".USER_INFOS_TABLE."
1702SET status = '".(isset($data['status']) ? $data['status'] : $conf_UAM[4])."'
1703WHERE user_id = '".$data['user_id']."'
1704;";
1705                                                pwg_query($query);
1706                                        }
1707                                        // Refresh user's category cache
1708                                        invalidate_user_cache();
1709 
1710                                        return true;
1711                                }
1712                        }
1713                }
1714        }
1715  else
1716    return false;
1717}
1718
1719
1720/**
1721 * Function called from UAM_admin.php to force users validation by admin
1722 *
1723 * @param : User id
1724 *
1725 */
1726function ForceValidation($id)
1727{
1728  global $conf;
1729
1730  $conf_UAM = unserialize($conf['UserAdvManager']);
1731
1732  if (isset($conf_UAM[1]) and $conf_UAM[1] == 'true')
1733  {
1734    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1735
1736                $query = "
1737UPDATE ".USER_CONFIRM_MAIL_TABLE."
1738SET date_check='".$dbnow."'
1739WHERE user_id = '".$id."'
1740;";
1741    pwg_query($query);
1742             
1743                if ($conf_UAM[2] <> -1)
1744                {
1745                        $query = "
1746DELETE FROM ".USER_GROUP_TABLE."
1747WHERE user_id = '".$id."'
1748  AND group_id = '".$conf_UAM[2]."'
1749;";
1750                        pwg_query($query);
1751                }
1752 
1753                if ($conf_UAM[3] <> -1)
1754                {
1755                        $query = "
1756DELETE FROM ".USER_GROUP_TABLE."
1757WHERE user_id = '".$id."'
1758  AND group_id = '".$conf_UAM[3]."'
1759;";
1760      pwg_query($query);
1761       
1762                        $query = "
1763INSERT INTO ".USER_GROUP_TABLE."
1764  (user_id, group_id)
1765VALUES
1766  ('".$id."', '".$conf_UAM[3]."')
1767;";
1768                        pwg_query($query);
1769    }
1770
1771                if ($conf_UAM[4] <> -1)
1772                {
1773                        $query = "
1774UPDATE ".USER_INFOS_TABLE."
1775SET status = '".$conf_UAM[4]."'
1776WHERE user_id = '".$id."'
1777;";
1778                        pwg_query($query);
1779                }
1780  }
1781  elseif (isset($conf_UAM[1]) and $conf_UAM[1] == 'local')
1782  {
1783    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1784
1785    if ($conf_UAM[2] <> -1)
1786    {
1787                  $query = "
1788DELETE FROM ".USER_GROUP_TABLE."
1789WHERE user_id = '".$id."'
1790  AND group_id = '".$conf_UAM[2]."'
1791;";
1792                  pwg_query($query);
1793    }
1794
1795    if ($conf_UAM[3] <> -1)
1796    {
1797      $query = "
1798DELETE FROM ".USER_GROUP_TABLE."
1799WHERE user_id = '".$id."'
1800  AND group_id = '".$conf_UAM[3]."'
1801;";
1802      pwg_query($query);
1803       
1804                  $query = "
1805INSERT INTO ".USER_GROUP_TABLE."
1806  (user_id, group_id)
1807VALUES
1808  ('".$id."', '".$conf_UAM[3]."')
1809;";
1810                  pwg_query($query);
1811    }
1812
1813    if ($conf_UAM[4] <> -1)
1814    {
1815                  $query = "
1816UPDATE ".USER_INFOS_TABLE."
1817SET status = '".$conf_UAM[4]."'
1818WHERE user_id = '".$id."'
1819;";
1820      pwg_query($query);
1821    }
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/**
1860 * Function called from main.inc.php - Check if user's email is in excluded email providers list
1861 * Doesn't work on call - Must be copied in main.inc.php to work
1862 *
1863 * @param : Email address
1864 *
1865 * @return : Bool
1866 *
1867 */
1868function ValidateEmailProvider($email)
1869{
1870  global $conf;
1871
1872  $conf_UAM = unserialize($conf['UserAdvManager']);
1873 
1874        if (isset($email) and isset($conf_UAM[12]) and $conf_UAM[12] <> '')
1875        {
1876                $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM[12]);
1877                for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
1878                {
1879                        $pattern = '/'.$conf_MailExclusion[$i].'/i';
1880                        if (preg_match($pattern, $email))
1881      {
1882                        return true;
1883      }
1884                }
1885        }
1886  else
1887  {
1888    return false;
1889  }
1890}
1891
1892
1893/**
1894 * Function called from UAM_admin.php - Get unvalidated users according time limit
1895 *
1896 * @return : List of users
1897 *
1898 */
1899function get_unvalid_user_list()
1900{
1901        global $conf, $page;
1902         
1903        // Get ConfirmMail configuration
1904  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1905  // Get UAM configuration
1906  $conf_UAM = unserialize($conf['UserAdvManager']);
1907 
1908  $users = array();
1909
1910        // search users depending expiration date
1911  $query = '
1912SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
1913                u.'.$conf['user_fields']['username'].' AS username,
1914                u.'.$conf['user_fields']['email'].' AS email,
1915                ui.status,
1916                ui.enabled_high,
1917                ui.level,
1918                ui.registration_date
1919FROM '.USERS_TABLE.' AS u
1920  INNER JOIN '.USER_INFOS_TABLE.' AS ui
1921    ON u.'.$conf['user_fields']['id'].' = ui.user_id
1922  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
1923    ON u.'.$conf['user_fields']['id'].' = ug.user_id
1924WHERE u.'.$conf['user_fields']['id'].' >= 3
1925  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'"
1926  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail[1].'")';
1927
1928        if ($conf_UAM[2] <> '-1' and $conf_UAM[8] == '-1')
1929  {
1930    $query.= '
1931  AND ug.group_id = '.$conf_UAM[2];
1932  }
1933  if ($conf_UAM[2] == '-1' and $conf_UAM[8] <> '-1')
1934  {
1935    $query.= '
1936  AND ui.status = \''.$conf_UAM[8]."'";
1937  }
1938  if ($conf_UAM[2] <> '-1' and $conf_UAM[8] <> '-1')
1939  {
1940    $query.= '
1941  AND ug.group_id = \''.$conf_UAM[2]."'";
1942  }
1943  $query.= '
1944ORDER BY ui.registration_date ASC
1945;';
1946
1947        $result = pwg_query($query);
1948     
1949  while ($row = pwg_db_fetch_assoc($result))
1950  {
1951        $user = $row;
1952    $user['groups'] = array();
1953
1954    array_push($users, $user);
1955        }
1956
1957        // add group lists
1958  $user_ids = array();
1959  foreach ($users as $i => $user)
1960  {
1961        $user_ids[$i] = $user['id'];
1962        }
1963       
1964        $user_nums = array_flip($user_ids);
1965
1966  if (count($user_ids) > 0)
1967  {
1968        $query = '
1969SELECT user_id, group_id
1970  FROM '.USER_GROUP_TABLE.'
1971WHERE user_id IN ('.implode(',', $user_ids).')
1972;';
1973       
1974                $result = pwg_query($query);
1975       
1976    while ($row = pwg_db_fetch_assoc($result))
1977    {
1978        array_push(
1979        $users[$user_nums[$row['user_id']]]['groups'],
1980        $row['group_id']
1981                        );
1982                }
1983        }
1984
1985        return $users;
1986}
1987
1988
1989/**
1990 * Function called from functions.inc.php - Get all users who haven't validate their registration in configured time
1991 * to delete or remail them automatically
1992 *
1993 * @return : List of users
1994 *
1995 */
1996function get_unvalid_user_autotasks()
1997{
1998        global $conf, $page;
1999         
2000        // Get ConfirmMail configuration
2001  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2002 
2003  $users = array();
2004
2005        // search users depending expiration date
2006  $query = '
2007SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2008                ui.registration_date
2009FROM '.USERS_TABLE.' AS u
2010  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2011    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2012WHERE u.'.$conf['user_fields']['id'].' >= 3
2013  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'")
2014ORDER BY ui.registration_date ASC;';
2015
2016        $result = pwg_query($query);
2017     
2018  while ($row = pwg_db_fetch_assoc($result))
2019  {
2020    array_push($users, $row);
2021        }
2022
2023        return $users;
2024}
2025
2026
2027/**
2028 * Function called from UAM_admin.php - Get ghost users
2029 *
2030 * @return : List of users
2031 *
2032 */
2033function get_ghost_user_list()
2034{
2035        global $conf, $page;
2036
2037  $conf_UAM = unserialize($conf['UserAdvManager']);
2038 
2039  $users = array();
2040
2041        // search users depending expiration date
2042  $query = '
2043SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2044                u.'.$conf['user_fields']['username'].' AS username,
2045                u.'.$conf['user_fields']['email'].' AS email,
2046                lv.lastvisit,
2047                lv.reminder
2048FROM '.USERS_TABLE.' AS u
2049  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2050    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2051WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[17].'")
2052ORDER BY lv.lastvisit ASC;';
2053
2054        $result = pwg_query($query);
2055     
2056  while ($row = pwg_db_fetch_assoc($result))
2057  {
2058        $user = $row;
2059    $user['groups'] = array();
2060
2061    array_push($users, $user);
2062        }
2063
2064        // add group lists
2065  $user_ids = array();
2066  foreach ($users as $i => $user)
2067  {
2068        $user_ids[$i] = $user['id'];
2069        }
2070
2071        return $users;
2072}
2073
2074
2075/**
2076 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
2077 *
2078 * @return : List of users to delete or downgrade automatically
2079 *
2080 */
2081function get_ghosts_autotasks()
2082{
2083        global $conf, $page;
2084
2085  $conf_UAM = unserialize($conf['UserAdvManager']);
2086 
2087  $users = array();
2088 
2089        // search users depending expiration date and reminder sent
2090  $query = '
2091SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2092                lv.lastvisit
2093FROM '.USERS_TABLE.' AS u
2094  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2095    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2096WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[17].'")
2097ORDER BY lv.lastvisit ASC;';
2098
2099        $result = pwg_query($query);
2100     
2101  while ($row = pwg_db_fetch_assoc($result))
2102  {
2103    array_push($users, $row);
2104        }
2105 
2106        return $users;
2107}
2108
2109
2110/**
2111 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
2112 *
2113 * @return : List of users
2114 *
2115 */
2116function get_user_list()
2117{
2118        global $conf, $page;
2119 
2120  $users = array();
2121
2122        // search users depending expiration date
2123  $query = '
2124SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2125                u.'.$conf['user_fields']['username'].' AS username,
2126                u.'.$conf['user_fields']['email'].' AS email,
2127                ug.lastvisit
2128FROM '.USERS_TABLE.' AS u
2129  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
2130    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2131WHERE u.'.$conf['user_fields']['id'].' >= 3
2132ORDER BY ug.lastvisit DESC
2133;';
2134
2135        $result = pwg_query($query);
2136     
2137  while ($row = pwg_db_fetch_assoc($result))
2138  {
2139        $user = $row;
2140    $user['groups'] = array();
2141
2142    array_push($users, $user);
2143        }
2144
2145        // add group lists
2146  $user_ids = array();
2147  foreach ($users as $i => $user)
2148  {
2149        $user_ids[$i] = $user['id'];
2150        }
2151
2152        return $users;
2153}
2154
2155
2156/**
2157 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
2158 *
2159 * @param : user id
2160 *
2161 * @return : Bool
2162 *
2163 */
2164function expiration($id)
2165{
2166        global $conf, $page;
2167         
2168        // Get ConfirmMail configuration
2169  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2170         
2171        // Get UAM configuration
2172  $conf_UAM = unserialize($conf['UserAdvManager']);
2173       
2174        $query = "
2175SELECT registration_date
2176  FROM ".USER_INFOS_TABLE."
2177WHERE user_id = '".$id."'
2178;";
2179        list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2180
2181//              Time limit process             
2182// ******************************************** 
2183        if (!empty($registration_date))
2184  {
2185                // dates formating and compare
2186                $today = date("d-m-Y"); // Get today's date
2187                list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2188                $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2189               
2190          list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2191                list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2192                $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2193                       
2194                $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
2195                $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2196
2197                // Condition with the value set for time limit
2198                if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
2199                {
2200                        return false;
2201                }
2202                else
2203                {
2204                        return true;
2205                }
2206        }
2207}
2208
2209
2210/**
2211 * Returns a password's score for password complexity check
2212 *
2213 * @param : password filled by user
2214 *
2215 * @return : Score calculation
2216 *
2217 * Thanx to MathieuGut from http://m-gut.developpez.com
2218 */
2219function testpassword($password) // Le mot de passe passé en paramètre - $password given by user
2220{
2221
2222  // Initialisation des variables - Variables initiation
2223  $points = 0;
2224  $point_lowercase = 0;
2225  $point_uppercase = 0;
2226  $point_numbers = 0;
2227  $point_characters = 0;
2228
2229  // On récupère la longueur du mot de passe - Getting password lengh   
2230  $length = strlen($password);
2231 
2232  // On fait une boucle pour lire chaque lettre - Loop to read password characters
2233  for($i = 0; $i < $length; $i++)
2234  {
2235    // On sélectionne une à une chaque lettre - Select each letters
2236    // $i étant à 0 lors du premier passage de la boucle - $i is 0 at first turn
2237    $letters = $password[$i];
2238
2239    if ($letters>='a' && $letters<='z')
2240    {
2241      // On ajoute 1 point pour une minuscule - Adding 1 point to score for a lowercase
2242                  $points = $points + 1;
2243
2244                  // On rajoute le bonus pour une minuscule - Adding bonus points for lowercase
2245                  $point_lowercase = 1;
2246    }
2247    else if ($letters>='A' && $letters <='Z')
2248    {
2249      // On ajoute 2 points pour une majuscule - Adding 2 points to score for uppercase
2250      $points = $points + 2;
2251               
2252      // On rajoute le bonus pour une majuscule - Adding bonus points for uppercase
2253      $point_uppercase = 2;
2254    }
2255    else if ($letters>='0' && $letters<='9')
2256    {
2257      // On ajoute 3 points pour un chiffre - Adding 3 points to score for numbers
2258      $points = $points + 3;
2259               
2260      // On rajoute le bonus pour un chiffre - Adding bonus points for numbers
2261      $point_numbers = 3;
2262    }
2263    else
2264    {
2265      // On ajoute 5 points pour un caractère autre - Adding 5 points to score for special characters
2266      $points = $points + 5;
2267               
2268      // On rajoute le bonus pour un caractère autre - Adding bonus points for special characters
2269      $point_characters = 5;
2270    }
2271  }
2272
2273  // Calcul du coefficient points/longueur - calculating the coefficient points/length
2274  $step1 = $points / $length;
2275
2276  // Calcul du coefficient de la diversité des types de caractères... - Calculation of the diversity of character types...
2277  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
2278
2279  // Multiplication du coefficient de diversité avec celui de la longueur - Multiplying the coefficient of diversity with that of the length
2280  $score = $step1 * $step2;
2281
2282  // Multiplication du resultat par la longueur de la chaine - Multiplying the result by the length of the string
2283  $finalscore = $score * $length;
2284
2285  return $finalscore;
2286}
2287
2288
2289/**
2290 * Function called from maintain.inc.php - to check if database upgrade is needed
2291 *
2292 * @param : table name
2293 *
2294 * @return : boolean
2295 *
2296 */
2297function table_exist($table)
2298{
2299  $query = 'DESC '.$table.';';
2300  return (bool)($res=pwg_query($query));
2301}
2302
2303
2304/**
2305 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
2306 *
2307 * @param : plugin directory
2308 *
2309 * @return : plugin's version and name
2310 *
2311 */
2312function PluginInfos($dir)
2313{
2314  $path = $dir;
2315
2316  $plg_data = implode( '', file($path.'main.inc.php') );
2317  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
2318  {
2319    $plugin['name'] = trim( $val[1] );
2320  }
2321  if (preg_match("|Version: (.*)|", $plg_data, $val))
2322  {
2323    $plugin['version'] = trim($val[1]);
2324  }
2325  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
2326  {
2327    $plugin['uri'] = trim($val[1]);
2328  }
2329  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
2330  {
2331    $plugin['description'] = trim($desc);
2332  }
2333  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
2334  {
2335    $plugin['description'] = trim($val[1]);
2336  }
2337  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
2338  {
2339    $plugin['author'] = trim($val[1]);
2340  }
2341  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
2342  {
2343    $plugin['author uri'] = trim($val[1]);
2344  }
2345  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
2346  {
2347    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
2348    if (is_numeric($extension)) $plugin['extension'] = $extension;
2349  }
2350// IMPORTANT SECURITY !
2351  $plugin = array_map('htmlspecialchars', $plugin);
2352
2353  return $plugin ;
2354}
2355
2356
2357/**
2358 * Delete obsolete files on plugin upgrade
2359 * Obsolete files are listed in file obsolete.list
2360 *
2361 */
2362function clean_obsolete_files()
2363{
2364  if (file_exists(UAM_PATH.'obsolete.list')
2365    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
2366    and !empty($old_files))
2367  {
2368    array_push($old_files, 'obsolete.list');
2369    foreach($old_files as $old_file)
2370    {
2371      $path = UAM_PATH.$old_file;
2372      if (is_file($path))
2373      {
2374        @unlink($path);
2375      }
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
2414
2415/**
2416 * UAM specific database dump (only for MySql !)
2417 * Creates an SQL dump of UAM specific tables and configuration settings
2418 *
2419 * @returns  : Boolean to manage appropriate message display
2420 *
2421 */
2422function uam_dump($download)
2423{
2424  global $conf;
2425 
2426  // Initial backup folder creation and file initialisation
2427  if (!is_dir(UAM_PATH.'/include/backup'))
2428    mkdir(UAM_PATH.'/include/backup');
2429
2430  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
2431
2432  $fp = fopen($Backup_File, 'w');
2433
2434
2435  // Saving UAM specific tables
2436  $ListTables = array(USER_CONFIRM_MAIL_TABLE, USER_LASTVISIT_TABLE);
2437  $j=0;
2438 
2439  while($j < count($ListTables))
2440  {
2441    $sql = 'SHOW CREATE TABLE '.$ListTables[$j];
2442    $res = pwg_query($sql);
2443
2444    if ($res)
2445    {
2446      $insertions = "-- -------------------------------------------------------\n";
2447      $insertions .= "-- Create ".$ListTables[$j]." table\n";
2448      $insertions .= "-- ------------------------------------------------------\n\n";
2449
2450      $insertions .= "DROP TABLE IF EXISTS ".$ListTables[$j].";\n\n";
2451
2452      $array = mysql_fetch_array($res);
2453      $array[1] .= ";\n\n";
2454      $insertions .= $array[1];
2455
2456      $req_table = pwg_query('SELECT * FROM '.$ListTables[$j]) or die(mysql_error());
2457      $nb_fields = mysql_num_fields($req_table);
2458      while ($line = mysql_fetch_array($req_table))
2459      {
2460        $insertions .= 'INSERT INTO '.$ListTables[$j].' VALUES (';
2461        for ($i=0; $i<$nb_fields; $i++)
2462        {
2463          $insertions .= '\'' . mysql_real_escape_string($line[$i]) . '\', ';
2464        }
2465        $insertions = substr($insertions, 0, -2);
2466        $insertions .= ");\n";
2467      }
2468      $insertions .= "\n\n";
2469    }
2470
2471    fwrite($fp, $insertions);   
2472    $j++;
2473  }
2474 
2475  // Saving UAM configuration
2476  $insertions = "-- -------------------------------------------------------\n";
2477  $insertions .= "-- Insert UAM configuration in ".CONFIG_TABLE."\n";
2478  $insertions .= "-- ------------------------------------------------------\n\n";
2479
2480  fwrite($fp, $insertions);
2481
2482  $pattern = "UserAdvManager%";
2483  $req_table = pwg_query('SELECT * FROM '.CONFIG_TABLE.' WHERE param LIKE "'.$pattern.'";') or die(mysql_error());
2484  $nb_fields = mysql_num_fields($req_table);
2485
2486  while ($line = mysql_fetch_array($req_table))
2487  {
2488    $insertions = 'INSERT INTO '.CONFIG_TABLE.' VALUES (';
2489    for ($i=0; $i<$nb_fields; $i++)
2490    {
2491      $insertions .= '\'' . mysql_real_escape_string($line[$i]) . '\', ';
2492    }
2493    $insertions = substr($insertions, 0, -2);
2494    $insertions .= ");\n";
2495
2496    fwrite($fp, $insertions);
2497  }
2498
2499  fclose($fp);
2500
2501  // Download generated dump file
2502  if ($download == 'true')
2503  {
2504    if (@filesize($Backup_File))
2505    {
2506      $http_headers = array(
2507        'Content-Length: '.@filesize($Backup_File),
2508        'Content-Type: text/x-sql',
2509        'Content-Disposition: attachment; filename="UAM_dbbackup.sql";',
2510        'Content-Transfer-Encoding: binary',
2511        );
2512
2513      foreach ($http_headers as $header)
2514      {
2515        header($header);
2516      }
2517
2518      @readfile($Backup_File);
2519      exit();
2520    }
2521  }
2522
2523  return true;
2524}
2525
2526
2527/**
2528 * Useful for debugging - 4 vars can be set
2529 * Output result to log.txt file
2530 *
2531 */
2532function UAMLog($var1, $var2, $var3, $var4)
2533{
2534   $fo=fopen (UAM_PATH.'log.txt','a') ;
2535   fwrite($fo,"======================\n") ;
2536   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
2537   fwrite($fo,$var1 ."\r\n") ;
2538   fwrite($fo,$var2 ."\r\n") ;
2539   fwrite($fo,$var3 ."\r\n") ;
2540   fwrite($fo,$var4 ."\r\n") ;
2541   fclose($fo) ;
2542}
2543?>
Note: See TracBrowser for help on using the repository browser.