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

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