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

Last change on this file since 25062 was 25062, checked in by Eric, 11 years ago

Bug 2979 fixed - Users manually added by an admin with "Confirmation of registration for admins" disabled and "Automatic management of unconfirmed users" enabled will no longer receive a reminder email to confirm the registration

  • Property svn:eol-style set to LF
File size: 106.0 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_admin_page
32 *
33 * Check options compatibility
34 */
35function UAM_check_compat()
36{
37  global $conf, $page;
38 
39  $conf_UAM = unserialize($conf['UserAdvManager']);
40 
41  // Check mandatory email address for email exclusion
42  if (!$conf['obligatory_user_mail_address'] and $conf_UAM['MAILEXCLUSION'] == 'true')
43  {
44    array_push($page['warnings'], l10n('UAM_mail_exclusion_error'));
45  }
46}
47
48
49/**
50 * Triggered on loc_begin_index
51 *
52 * Initiating GhostTracker - Perform user logout after registration if not validated
53 */
54function UAM_Init()
55{
56  global $conf, $user;
57
58  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
59
60  $conf_UAM = unserialize($conf['UserAdvManager']);
61
62  // Admins, Guests and Adult_Content users are not tracked for Ghost Tracker or Users Tracker
63  // -----------------------------------------------------------------------------------------
64  if (!is_admin() and !is_a_guest() and $user['username'] != "16" and $user['username'] != "18")
65  {
66    if ((isset($conf_UAM['GHOSTRACKER']) and $conf_UAM['GHOSTRACKER'] == 'true') or (isset($conf_UAM['ADDLASTVISIT']) and $conf_UAM['ADDLASTVISIT'] == 'true'))
67    {
68      $userid = get_userid($user['username']);
69         
70      // Looking for existing entry in last visit table
71      // ----------------------------------------------
72      $query = '
73SELECT *
74FROM '.USER_LASTVISIT_TABLE.'
75WHERE user_id = '.$userid.'
76;';
77
78      $count = pwg_db_num_rows(pwg_query($query));
79
80      if ($count == 0)
81      {
82        // If not, data are inserted in table
83        // ----------------------------------
84        $query = '
85INSERT INTO '.USER_LASTVISIT_TABLE.' (user_id, lastvisit, reminder)
86VALUES ('.$userid.', now(), "false")
87;';
88        pwg_query($query);
89      }
90      else if ($count > 0)
91      {
92        // If yes, data are updated in table
93        // ---------------------------------
94        $query = '
95UPDATE '.USER_LASTVISIT_TABLE.'
96SET lastvisit = now(), reminder = "false"
97WHERE user_id = '.$userid.'
98LIMIT 1
99;';
100        pwg_query($query);
101      }
102    }
103
104    // Perform user logout after registration if not validated
105    if ((isset($conf_UAM['CONFIRM_MAIL']) and ($conf_UAM['CONFIRM_MAIL']=='true' or $conf_UAM['CONFIRM_MAIL']=='local'))
106          and (isset($conf_UAM['REJECTCONNECT']) and $conf_UAM['REJECTCONNECT'] == 'true')
107          and !UAM_UsrReg_Verif($user['id'])
108          and !is_admin()
109          and !is_webmaster())
110    {
111      invalidate_user_cache();
112      logout_user();
113      if ( $conf['guest_access'] )
114      {
115        redirect( make_index_url().'?UAM_msg=rejected', 0);
116      }
117      else
118      {
119        redirect( get_root_url().'identification.php?UAM_msg=rejected' , 0);
120      }
121    }
122  }
123}
124
125
126/**
127 * Triggered on register_user
128 *
129 * Additional controls on user registration
130 */
131function UAM_Adduser($register_user)
132{
133  global $conf;
134
135  $conf_UAM = unserialize($conf['UserAdvManager']);
136
137  // Exclusion of Adult_Content users
138  // --------------------------------
139  if ($register_user['username'] != "16" and $register_user['username'] != "18")
140  {
141    $passwd = (isset($_POST['password'])) ? $_POST['password'] : '';
142
143    // --------------------------------------------------------------------------------------------------------------------
144    // Workflow when admins have to validate registrations (CONFIRM_MAIL = local)
145    // No validation needed when admins add users if ADMINCONFMAIL is set to OFF - users are considered as valid by default
146    // Else a notification email with validation link is send to admins
147    // Finally when a user registers himself, a notification email with validation link is send to admins
148    // --------------------------------------------------------------------------------------------------------------------
149    if (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'local')
150    {
151      if (is_admin() and isset($conf_UAM['ADMINCONFMAIL']) and $conf_UAM['ADMINCONFMAIL'] == 'true')
152      {
153        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], true); 
154      }
155      elseif (is_admin() and isset($conf_UAM['ADMINCONFMAIL']) and $conf_UAM['ADMINCONFMAIL'] == 'false')
156      {
157        SetValidated($register_user['id']);
158        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], false);
159      }
160      elseif (!is_admin())
161      {
162        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], true);
163      }
164    }
165    // --------------------------------------------------------------------------------------------------------------------
166    // Workflow when users have to validate their registration (CONFIRM_MAIL = true)
167    // No validation needed when admins add users if ADMINCONFMAIL is set to OFF - users are considered as valid by default
168    // Else an email with validation link is send to user
169    // Finally when a user registers himself, an email with validation link is send to him
170    // --------------------------------------------------------------------------------------------------------------------
171    elseif (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true')
172    {
173      if (is_admin() and isset($conf_UAM['ADMINCONFMAIL']) and $conf_UAM['ADMINCONFMAIL'] == 'true')
174      {
175        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], true); 
176      }
177      elseif (is_admin() and isset($conf_UAM['ADMINCONFMAIL']) and $conf_UAM['ADMINCONFMAIL'] == 'false')
178      {
179        SetValidated($register_user['id']);
180        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], false);
181      }
182      elseif (!is_admin())
183      {
184        SendMail2User(1, $register_user['id'], $register_user['username'], $passwd, $register_user['email'], true);
185      }
186    }
187  }
188}
189
190
191/**
192 * Triggered on delete_user
193 *
194 * Database cleanup on user deletion
195 */
196function UAM_Deluser($user_id)
197{
198  // Cleanup for ConfirmMail table
199  // -----------------------------
200  DeleteConfirmMail($user_id);
201  // Cleanup for LastVisit table
202  // ---------------------------
203  DeleteLastVisit($user_id);
204  // Cleanup Redirection settings
205  // ----------------------------
206  DeleteRedir($user_id);
207}
208
209
210/**
211 * Triggered on register_user_check
212 *
213 * Additional controls on user registration check
214 */
215function UAM_RegistrationCheck($errors, $user)
216{
217  global $conf;
218
219  // Exclusion of Adult_Content users
220  // --------------------------------
221  if ($user['username'] != "16" and $user['username'] != "18")
222  {
223    load_language('plugin.lang', UAM_PATH);
224
225    $PasswordCheck = 0;
226
227    $conf_UAM = unserialize($conf['UserAdvManager']);
228
229    // Password enforcement control
230    // ----------------------------
231    if (isset($conf_UAM['PASSWORDENF']) and $conf_UAM['PASSWORDENF'] == 'true' and !empty($conf_UAM['PASSWORD_SCORE']))
232    {
233      if (!empty($user['password']) and !is_admin())
234      {
235        $PasswordCheck = testpassword($user['password']);
236 
237        if ($PasswordCheck < $conf_UAM['PASSWORD_SCORE'])
238        {
239          $message = get_l10n_args('UAM_reg_err_login4_%s', $PasswordCheck);
240          $lang['reg_err_pass'] = l10n_args($message).$conf_UAM['PASSWORD_SCORE'];
241          array_push($errors, $lang['reg_err_pass']);
242        }
243      }
244      else if (!empty($user['password']) and is_admin() and isset($conf_UAM['ADMINPASSWENF']) and $conf_UAM['ADMINPASSWENF'] == 'true')
245      {
246        $PasswordCheck = testpassword($user['password']);
247 
248        if ($PasswordCheck < $conf_UAM['PASSWORD_SCORE'])
249        {
250          $message = get_l10n_args('UAM_reg_err_login4_%s', $PasswordCheck);
251          $lang['reg_err_pass'] = l10n_args($message).$conf_UAM['PASSWORD_SCORE'];
252          array_push($errors, $lang['reg_err_pass']);
253        }
254      }
255    }
256
257    // Username without forbidden keys
258    // -------------------------------
259    if (isset($conf_UAM['USERNAME_CHAR']) and $conf_UAM['USERNAME_CHAR'] == 'true' and !empty($user['username']) and ValidateUsername($user['username']) and !is_admin())
260    {
261      $lang['reg_err_login1'] = l10n('UAM_reg_err_login2')."'".$conf_UAM['USERNAME_CHAR_LIST']."'";
262      array_push($errors, $lang['reg_err_login1']);
263    }
264
265    // Email without forbidden domains
266    // -------------------------------
267    if (isset($conf_UAM['MAILEXCLUSION']) and $conf_UAM['MAILEXCLUSION'] == 'true' and !empty($user['email']) and ValidateEmailProvider($user['email']) and !is_admin())
268    {
269      $lang['reg_err_login1'] = l10n('UAM_reg_err_login5')."'".$conf_UAM['MAILEXCLUSION_LIST']."'";
270      array_push($errors, $lang['reg_err_login1']);
271    }
272    return $errors;
273  }
274}
275
276
277/**
278 * Triggered on loc_begin_profile
279 */
280function UAM_Profile_Init()
281{
282  global $conf, $user, $template;
283
284  $conf_UAM = unserialize($conf['UserAdvManager']);
285
286  // Update first redirection parameter
287  // ----------------------------------
288  if ((isset($conf_UAM['REDIRTOPROFILE']) and $conf_UAM['REDIRTOPROFILE'] == 'true'))
289  {
290    $user_idsOK = array();
291    if (!UAM_check_profile($user['id'], $user_idsOK))
292    {
293      $user_idsOK[] = $user['id'];
294
295      $query = '
296UPDATE '.CONFIG_TABLE.'
297SET value = "'.implode(',', $user_idsOK).'"
298WHERE param = "UserAdvManager_Redir";';
299         
300      pwg_query($query);
301    }
302  }
303
304  // Special message display for password reset
305  // ------------------------------------------
306  if ((isset($conf_UAM['PWDRESET']) and $conf_UAM['PWDRESET'] == 'true'))
307  {
308    if (UAM_check_pwgreset($user['id']))
309    {
310      $template->append('errors', l10n('UAM_Password_Reset_Msg'));
311    }
312  }
313
314  // Controls on profile page submission
315  // -----------------------------------
316  if (isset($_POST['validate']) and !is_admin())
317  {
318    // Email without forbidden domains
319    // -------------------------------
320    if (isset($conf_UAM['MAILEXCLUSION']) and $conf_UAM['MAILEXCLUSION'] == 'true' and !empty($_POST['mail_address']))
321    {
322      if (ValidateEmailProvider($_POST['mail_address']))
323      {
324        $template->append('errors', l10n('UAM_reg_err_login5')."'".$conf_UAM['MAILEXCLUSION_LIST']."'");
325        unset($_POST['validate']);
326      }
327    }
328
329    // Password reset control
330    // ----------------------
331    if (isset($conf_UAM['PWDRESET']) and $conf_UAM['PWDRESET'] == 'true' and UAM_check_pwgreset($user['id']))
332    {
333      // if password not changed then pwdreset field = true else pwdreset field = false
334      // ------------------------------------------------------------------------------
335      if (!empty($_POST['use_new_pwd']))
336      {
337        $query = '
338UPDATE '.USERS_TABLE.'
339SET UAM_pwdreset = "false"
340WHERE id = '.$user['id'].'
341LIMIT 1
342;';
343        pwg_query($query);
344      }
345    }
346
347    $typemail = 3; // Only information email send to user on user profile update if checked
348
349    if (!empty($_POST['use_new_pwd']))
350    {
351      $typemail = 2; // Confirmation email on user profile update - With information email
352
353      // Password enforcement control
354      // ----------------------------
355      if (isset($conf_UAM['PASSWORDENF']) and $conf_UAM['PASSWORDENF'] == 'true' and !empty($conf_UAM['PASSWORD_SCORE']))
356      {
357        $PasswordCheck = testpassword($_POST['use_new_pwd']);
358
359        if ($PasswordCheck < $conf_UAM['PASSWORD_SCORE'])
360        {
361          $message = get_l10n_args('UAM_reg_err_login4_%s', $PasswordCheck);
362          $template->append('errors', l10n_args($message).$conf_UAM['PASSWORD_SCORE']);
363          unset($_POST['use_new_pwd']);
364          unset($_POST['validate']);
365        }
366      }
367    }
368
369    // Sending registration confirmation by email
370    // ------------------------------------------
371    if ((isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true') or (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'local'))
372    {
373      $confirm_mail_need = false;
374
375      if (!empty($_POST['mail_address']))
376      {
377        $query = '
378SELECT '.$conf['user_fields']['email'].' AS email
379FROM '.USERS_TABLE.'
380WHERE '.$conf['user_fields']['id'].' = \''.$user['id'].'\'
381;';
382
383        list($current_email) = pwg_db_fetch_row(pwg_query($query));
384
385        // This is to send a new validation key
386        // ------------------------------------
387        if ($_POST['mail_address'] != $current_email and (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true'))
388        {
389          SetPermission($user['id']);// Set to "waiting" group or status until user validation
390          SetUnvalidated($user['id']); // Set UAM_validated field to false in #_users table
391          $confirm_mail_need = true;
392        }
393
394        // This is to set the user to "waiting" group or status until admin validation
395        // ---------------------------------------------------------------------------
396        elseif ($_POST['mail_address'] != $current_email and (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'local'))
397        {
398          SetPermission($user['id']);// Set to "waiting" group or status until admin validation
399          SetUnvalidated($user['id']); // Set UAM_validated field to false in #_users table
400          $confirm_mail_need = false;
401        }       
402      }
403
404      if (((!empty($_POST['use_new_pwd']) and (isset($conf_UAM['MAIL_INFO']) and $conf_UAM['MAIL_INFO'] == 'true')) or $confirm_mail_need))
405      {
406        $query = '
407SELECT '.$conf['user_fields']['username'].'
408FROM '.USERS_TABLE.'
409WHERE '.$conf['user_fields']['id'].' = \''.$user['id'].'\'
410;';
411
412        list($username) = pwg_db_fetch_row(pwg_query($query));
413        SendMail2User($typemail, $user['id'], $username, $_POST['use_new_pwd'], $_POST['mail_address'], $confirm_mail_need);
414      }
415    }
416  }
417}
418
419
420/**
421 * Triggered on login_success
422 *
423 * Triggers scheduled tasks at login
424 * Redirects a visitor (except for admins, webmasters and generic statuses) to his profile.php page (Thx to LucMorizur)
425 *
426 */
427function UAM_LoginTasks()
428{
429  global $conf, $user;
430
431  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
432
433  $conf_UAM = unserialize($conf['UserAdvManager']);
434
435  // Performing GhostTracker scheduled tasks
436  // ---------------------------------------
437  if ((isset($conf_UAM['GTAUTO']) and $conf_UAM['GTAUTO'] == 'true'))
438  {
439    UAM_GT_ScheduledTasks();
440  }
441
442  // Performing User validation scheduled tasks
443  // ------------------------------------------
444  if ((isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL']=='true')
445        and (isset($conf_UAM['USRAUTO']) and $conf_UAM['USRAUTO'] == 'true'))
446  {
447    UAM_USR_ScheduledTasks();
448  }
449
450  // Avoid login into private galleries until registration confirmation is done
451  if ((isset($conf_UAM['REJECTCONNECT']) and $conf_UAM['REJECTCONNECT'] == 'false')
452        or ((isset($conf_UAM['REJECTCONNECT']) and $conf_UAM['REJECTCONNECT'] == 'true') and UAM_UsrReg_Verif($user['id']))
453        or (!is_admin() and !is_webmaster()))
454  {
455    // Performing redirection to profile page on first login
456    // -----------------------------------------------------
457    if ((isset($conf_UAM['REDIRTOPROFILE']) and $conf_UAM['REDIRTOPROFILE'] == 'true'))
458    {
459      $query ='
460SELECT user_id, status
461FROM '.USER_INFOS_TABLE.'
462WHERE user_id = '.$user['id'].'
463;';
464      $data = pwg_db_fetch_assoc(pwg_query($query));
465
466      if ($data['status'] <> "admin" and $data['status'] <> "webmaster" and $data['status'] <> "generic") // Exclusion of specific accounts
467      {
468        $user_idsOK = array();
469        if (!UAM_check_profile($user['id'], $user_idsOK))
470          redirect(PHPWG_ROOT_PATH.'profile.php');
471      }
472    }
473
474    // Performing redirection to profile page for password reset
475    // ---------------------------------------------------------
476    if ((isset($conf_UAM['PWDRESET']) and $conf_UAM['PWDRESET'] == 'true'))
477    {
478      $query ='
479SELECT user_id, status
480FROM '.USER_INFOS_TABLE.'
481WHERE user_id = '.$user['id'].'
482;';
483      $data = pwg_db_fetch_assoc(pwg_query($query));
484
485      if ($data['status'] <> "webmaster" and $data['status'] <> "generic") // Exclusion of specific accounts
486      {
487        if (UAM_check_pwgreset($user['id']))
488        {
489          redirect(PHPWG_ROOT_PATH.'profile.php');
490        }
491      }
492    }
493  }
494  elseif ((isset($conf_UAM['REJECTCONNECT']) and $conf_UAM['REJECTCONNECT'] == 'true') and !UAM_UsrReg_Verif($user['id']) and !is_admin() and !is_webmaster())
495  {
496    // Logged-in user cleanup, session destruction and redirected to custom page
497    // -------------------------------------------------------------------------
498    invalidate_user_cache();
499    logout_user();
500    if ( $conf['guest_access'] )
501    {
502      redirect( make_index_url().'?UAM_msg=rejected', 0);
503    }
504    else
505    {
506      redirect( get_root_url().'identification.php?UAM_msg=rejected' , 0);
507    }
508  }
509}
510
511
512/**
513 * Adds a new module settable in PWG_Stuffs - Triggered on get_stuffs_modules in main.inc.php
514 * Useful to inform unvalidated user for their status
515 *
516 */
517function register_UAM_stuffs_module($modules)
518{
519  array_push($modules, array(
520    'path' => UAM_PATH.'/stuffs_module',
521    'name' => l10n('UAM_Stuffs_Title'),
522    'description' => l10n('UAM_Stuffs_Desc'),
523    )
524  );
525  return $modules;
526}
527
528
529/**
530 * Triggered on UAM_LoginTasks()
531 *
532 * Executes optional post-login tasks for Ghost users
533 *
534 */
535function UAM_GT_ScheduledTasks()
536{
537  global $conf, $user, $page;
538
539  if (!defined('PHPWG_ROOT_PATH'))
540  {
541    die('Hacking attempt!');
542  }
543
544  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
545
546  $conf_UAM = unserialize($conf['UserAdvManager']);
547
548  $collection = array();
549  $reminder = false;
550
551  $page['filtered_users'] = get_ghosts_autotasks();
552
553  foreach($page['filtered_users'] as $listed_user)
554  {
555    array_push($collection, $listed_user['id']);
556  }
557
558  // Auto group, status or privacy level downgrade and autodeletion if user already reminded
559  // ---------------------------------------------------------------------------------------
560  if ((isset($conf_UAM['GTAUTO']) and $conf_UAM['GTAUTO'] == 'true') and ((isset($conf_UAM['DOWNGRADE_GROUP']) and $conf_UAM['DOWNGRADE_GROUP'] <> -1) or (isset($conf_UAM['DOWNGRADE_STATUS']) and $conf_UAM['DOWNGRADE_STATUS'] <> -1) or (isset($conf_UAM['DOWNGRADE_LEVEL']) and $conf_UAM['DOWNGRADE_LEVEL'] <> -1)))
561  {
562    if (count($collection) > 0)
563    {
564      // Process if a non-admin nor webmaster user is logged
565      // ---------------------------------------------------
566      if (in_array($user['id'], $collection))
567                        {
568        // Check lastvisit reminder state
569        // ------------------------------
570        $query = '
571SELECT reminder
572FROM '.USER_LASTVISIT_TABLE.'
573WHERE user_id = '.$user['id'].';';
574
575        $result = pwg_db_fetch_assoc(pwg_query($query));
576
577        if (isset($result['reminder']) and $result['reminder'] == 'true')
578        {
579          $reminder = true;
580        }
581        else
582        {
583          $reminder = false;
584        }
585
586        // If user already reminded for ghost account
587        // ------------------------------------------
588        if ($reminder)
589        {
590          // Delete account
591          // --------------
592          delete_user($user['id']);
593
594          // Logged-in user cleanup, session destruction and redirected to custom page
595          // -------------------------------------------------------------------------
596          invalidate_user_cache();
597          logout_user();
598          redirect(make_index_url().'?UAM_msg=deleted', 0);
599        }
600      }
601      else // Process if an admin or webmaster user is logged
602      {
603        foreach ($collection as $user_id)
604        {
605          // Check lastvisit reminder state
606          // ------------------------------
607          $query = '
608SELECT reminder
609FROM '.USER_LASTVISIT_TABLE.'
610WHERE user_id = '.$user_id.';';
611
612          $result = pwg_db_fetch_assoc(pwg_query($query));
613
614          if (isset($result['reminder']) and $result['reminder'] == 'true')
615          {
616            $reminder = true;
617          }
618          else
619          {
620            $reminder = false;
621          }
622
623          // If never reminded before
624          // ------------------------
625          if (!$reminder)
626          {
627            // Reset of lastvisit date
628            // -----------------------
629            $dbnow = date("Y-m-d H:i:s");
630
631                        $query = '
632UPDATE '.USER_LASTVISIT_TABLE.'
633SET lastvisit="'.$dbnow.'"
634WHERE user_id = '.$user_id.'
635;';
636            pwg_query($query);
637
638          // Auto change group and / or status
639          // ---------------------------------
640            // Delete user from all groups
641            // ---------------------------
642            if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1 and $conf_UAM['VALIDATED_GROUP'] <> -1)
643            {
644                        $query = '
645DELETE FROM '.USER_GROUP_TABLE.'
646WHERE user_id = '.$user_id.'
647  AND (
648    group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
649  OR
650    group_id = '.$conf_UAM['VALIDATED_GROUP'].'
651  )
652;';
653                        pwg_query($query);
654            }
655
656            // Change user status
657            // ------------------
658            if ($conf_UAM['DOWNGRADE_STATUS'] <> -1)
659            {
660              $query = '
661UPDATE '.USER_INFOS_TABLE.'
662SET status = "'.$conf_UAM['DOWNGRADE_STATUS'].'"
663WHERE user_id = '.$user_id.'
664;';
665              pwg_query($query);
666            }
667
668            // Change user group
669            // -----------------
670            if ($conf_UAM['DOWNGRADE_GROUP'] <> -1)
671            {
672              $query = '
673INSERT INTO '.USER_GROUP_TABLE.'
674  (user_id, group_id)
675VALUES
676  ('.$user_id.', "'.$conf_UAM['DOWNGRADE_GROUP'].'")
677;';
678              pwg_query($query);
679            }
680
681            // Change user privacy level
682            // -------------------------
683            if ($conf_UAM['DOWNGRADE_LEVEL'] <> -1)
684            {
685              $query = '
686UPDATE '.USER_INFOS_TABLE.'
687SET level = "'.$conf_UAM['DOWNGRADE_LEVEL'].'"
688WHERE user_id = '.$user_id.'
689;';
690              pwg_query($query);
691            }
692
693            // Auto send email notification on group / status downgrade
694            // --------------------------------------------------------
695            if (isset($conf_UAM['GTAUTOMAIL']) and $conf_UAM['GTAUTOMAIL'] == 'true')
696            {
697              // Set reminder true
698              // -----------------
699              $query = '
700UPDATE '.USER_LASTVISIT_TABLE.'
701SET reminder = "true"
702WHERE user_id = '.$user_id.'
703;';
704              pwg_query($query);
705           
706              // Reset confirmed user status to unvalidated
707              // ------------------------------------------
708              $query = '
709UPDATE '.USER_CONFIRM_MAIL_TABLE.'
710SET date_check = NULL
711WHERE user_id = '.$user_id.'
712;';
713              pwg_query($query);
714
715              // Get users information for email notification
716              // --------------------------------------------
717              $query = '
718SELECT id, username, mail_address
719FROM '.USERS_TABLE.'
720WHERE id = '.$user_id.'
721;';
722              $data = pwg_db_fetch_assoc(pwg_query($query));
723
724              SetUnvalidated($user_id);
725              demotion_mail($user_id, $data['username'], $data['mail_address']);
726            }
727          }
728          elseif ($reminder) // If user already reminded for ghost account
729          {
730            // Delete account
731            // --------------
732            delete_user($user_id);
733          }
734        }
735      }
736    }
737  }
738}
739
740
741/**
742 * Triggered on UAM_LoginTasks()
743 *
744 * Executes optional post-login tasks for unvalidated users
745 *
746 */
747function UAM_USR_ScheduledTasks()
748{
749  global $conf, $user, $page;
750
751  if (!defined('PHPWG_ROOT_PATH'))
752  {
753    die('Hacking attempt!');
754  }
755
756  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
757
758  $conf_UAM = unserialize($conf['UserAdvManager']);
759
760  $collection = array();
761  $reminder = false;
762
763  $page['filtered_users'] = get_unvalid_user_autotasks();
764
765  foreach($page['filtered_users'] as $listed_user)
766  {
767    array_push($collection, $listed_user['id']);
768  }
769
770  // Unvalidated accounts auto email sending and autodeletion if user already reminded
771  // ---------------------------------------------------------------------------------
772  if ((isset($conf_UAM['USRAUTO']) and $conf_UAM['USRAUTO'] == 'true'))
773  {
774    if (count($collection) > 0)
775                {
776      // Process if a non-admin nor webmaster user is logged
777      // ---------------------------------------------------
778      if (in_array($user['id'], $collection))
779      {
780        // Check ConfirmMail reminder state
781        // --------------------------------
782        $query = '
783SELECT reminder
784FROM '.USER_CONFIRM_MAIL_TABLE.'
785WHERE user_id = '.$user['id'].';';
786
787        $result = pwg_db_fetch_assoc(pwg_query($query));
788
789        if (isset($result['reminder']) and $result['reminder'] == 'true')
790        {
791          $reminder = true;
792        }
793        else
794        {
795          $reminder = false;
796        }
797
798        // If never reminded before, send reminder and set reminder True
799        // -------------------------------------------------------------
800        if (!$reminder and isset($conf_UAM['USRAUTOMAIL']) and $conf_UAM['USRAUTOMAIL'] == 'true')
801        {
802          $typemail = 1;
803
804          // Get current user information
805          // ----------------------------
806          $query = '
807SELECT id, username, mail_address
808FROM '.USERS_TABLE.'
809WHERE id = '.$user['id'].'
810;';
811          $data = pwg_db_fetch_assoc(pwg_query($query));
812
813          ResendMail2User($typemail,$user['id'],stripslashes($data['username']),$data['mail_address'],true);
814        }
815
816        // If already reminded before, delete user
817        // ---------------------------------------
818        if ($reminder)
819        {
820          // delete account
821          delete_user($user['id']);
822
823          // Logged-in user cleanup, session destruction and redirected to custom page
824          // -------------------------------------------------------------------------
825          invalidate_user_cache();
826          logout_user();
827          redirect(make_index_url().'?UAM_msg=deleted', 0);
828        }
829      }
830      else // Process if an admin or webmaster user is logged
831      {
832        foreach ($collection as $user_id)
833        {
834          // Check reminder state
835          // --------------------
836          $query = '
837SELECT reminder
838FROM '.USER_CONFIRM_MAIL_TABLE.'
839WHERE user_id = '.$user_id.';';
840
841          $result = pwg_db_fetch_assoc(pwg_query($query));
842
843          if (isset($result['reminder']) and $result['reminder'] == 'true')
844          {
845            $reminder = true;
846          }
847          else
848          {
849            $reminder = false;
850          }
851
852          // If never reminded before, send reminder and set reminder True
853          // -------------------------------------------------------------
854          if (!$reminder and isset($conf_UAM['USRAUTOMAIL']) and $conf_UAM['USRAUTOMAIL'] == 'true')
855          {
856            $typemail = 1;
857         
858            // Get current user information
859            // ----------------------------
860            $query = '
861SELECT id, username, mail_address
862FROM '.USERS_TABLE.'
863WHERE id = '.$user_id.'
864;';
865            $data = pwg_db_fetch_assoc(pwg_query($query));
866
867            ResendMail2User($typemail,$user_id,stripslashes($data['username']),$data['mail_address'],true);
868          }
869          elseif ($reminder) // If user already reminded for account validation
870          {
871            // Delete account
872            // --------------
873            delete_user($user_id);
874          }
875        }
876      }
877    }
878  }
879}
880
881
882/**
883 * Triggered on init
884 *
885 * Check for forbidden email domains in admin's users management panel
886 */
887function UAM_InitPage()
888{
889  load_language('plugin.lang', UAM_PATH);
890  global $conf, $template, $page, $lang, $errors;
891
892  $conf_UAM = unserialize($conf['UserAdvManager']);
893
894// Admin user management
895// ---------------------
896  if (script_basename() == 'admin' and isset($_GET['page']) and $_GET['page'] == 'user_list')
897  {
898    if (isset($_POST['submit_add']))
899    {
900      // Email without forbidden domains
901      // -------------------------------
902      if (isset($conf_UAM['MAILEXCLUSION']) and $conf_UAM['MAILEXCLUSION'] == 'true' and !empty($_POST['email']) and ValidateEmailProvider($_POST['email']))
903      {
904        $template->append('errors', l10n('UAM_reg_err_login5')."'".$conf_UAM['MAILEXCLUSION_LIST']."'");
905        unset($_POST['submit_add']);
906      }
907    }
908  }
909  if( isset($_GET['UAM_msg']))
910  {
911    UAM_DisplayMsg();
912  }
913  elseif (isset($_GET['key']) and isset($_GET['userid']))
914  {
915    UAM_ConfirmMail();
916  }
917}
918
919
920/**
921 * Triggered on init
922 *
923 * Display a message according to $_GET['UAM_msg']
924 */
925function UAM_DisplayMsg()
926{
927  if( isset($_GET['UAM_msg']))
928  {
929    global $user, $lang, $conf, $page;
930    $conf_UAM = unserialize($conf['UserAdvManager']);
931
932    // Connexion rejected until validation
933    if (isset($conf_UAM['REJECTCONNECT_TEXT']) and !empty($conf_UAM['REJECTCONNECT_TEXT']) and $_GET['UAM_msg']=="rejected")
934    {
935      // Management of Extension flags ([mygallery], [myurl])
936      // ---------------------------------------------------
937      $patterns[] = '#\[mygallery\]#i';
938      $replacements[] = $conf['gallery_title'];
939      $patterns[] = '#\[myurl\]#i';
940      $replacements[] = get_gallery_home_url();
941
942      if (function_exists('get_user_language_desc'))
943      {
944        $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['REJECTCONNECT_TEXT']));
945      }
946      else $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM['REJECTCONNECT_TEXT']));
947
948      $page["errors"][]=$custom_text;
949    }
950
951    // User account deleted after validation deadline - Triggered by any other user
952    elseif (isset($conf_UAM['GTAUTODEL']) and !empty($conf_UAM['GTAUTODEL']) and $_GET['UAM_msg']=="deleted")
953    {
954      // Management of Extension flags ([mygallery], [myurl]) - [username] flag can't be used here
955      // -----------------------------------------------------------------------------------------
956      $patterns[] = '#\[mygallery\]#i';
957      $replacements[] = $conf['gallery_title'];
958      $patterns[] = '#\[myurl\]#i';
959      $replacements[] = get_gallery_home_url();
960
961      if (function_exists('get_user_language_desc'))
962      {
963        $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTAUTODEL']));
964      }
965      else $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTAUTODEL']));
966
967      $page["errors"][]=$custom_text;
968    }
969
970    // User account deleted after validation deadline - Triggered by user himself
971    elseif (isset($conf_UAM['USRAUTODEL']) and !empty($conf_UAM['USRAUTODEL']) and $_GET['UAM_msg']=="deleted")
972    {
973      // Management of Extension flags ([mygallery], [myurl]) - [username] flag can't be used here
974      // -----------------------------------------------------------------------------------------
975      $patterns[] = '#\[mygallery\]#i';
976      $replacements[] = $conf['gallery_title'];
977      $patterns[] = '#\[myurl\]#i';
978      $replacements[] = get_gallery_home_url();
979
980      if (function_exists('get_user_language_desc'))
981      {
982        $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['USRAUTODEL']));
983      }
984      else $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM['USRAUTODEL']));
985
986      $page["errors"][]=$custom_text;
987    }
988  }
989}
990
991
992/**
993 * Triggered on init
994 *
995 * Check the key and display a message
996 */
997function UAM_ConfirmMail()
998{
999  global $conf;
1000  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1001
1002  if (isset($_GET['key']) and isset($_GET['userid']))
1003  {
1004    global $user, $lang, $conf, $page;
1005
1006    $key = $_GET['key'];
1007    $userid = $_GET['userid'];
1008   
1009    $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1010    $conf_UAM = unserialize($conf['UserAdvManager']);
1011
1012    $query = '
1013SELECT '.USERS_TABLE.'.username
1014FROM '.USERS_TABLE.'
1015WHERE ('.USERS_TABLE.'.id ='.$userid.')
1016;';
1017    $result = pwg_db_fetch_assoc(pwg_query($query));
1018
1019    if (VerifyConfirmMail($key))
1020    {
1021      if (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'local')
1022      {
1023        validation_mail($userid);
1024      }
1025  // We have to get the user's language in database
1026  // ----------------------------------------------
1027      $query = '
1028SELECT language
1029FROM '.USER_INFOS_TABLE.'
1030WHERE '.USER_INFOS_TABLE.'.user_id ='.$userid.'
1031;';
1032      $data = pwg_db_fetch_assoc(pwg_query($query));
1033
1034  // Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1035  // -------------------------------------------------------------------------------------------------------------------------------
1036      if (empty($data))
1037      {
1038  // And switch gallery to this language before using personalized and multilangual contents
1039  // ---------------------------------------------------------------------------------------
1040        $language = pwg_get_session_var('lang_switch', $user['language']);
1041        switch_lang_to($language);
1042      }
1043      else
1044      {
1045  // And switch gallery to this language before using personalized and multilangual contents
1046  // ---------------------------------------------------------------------------------------
1047        switch_lang_to($data['language']);
1048        load_language('plugin.lang', UAM_PATH);
1049      }
1050
1051      if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT1']) and !empty($conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT1']))
1052      {
1053        // Management of Extension flags ([username], [mygallery], [myurl])
1054        // ----------------------------------------------------------------
1055        $patterns[] = '#\[username\]#i';
1056        $replacements[] = $result['username'];
1057        $patterns[] = '#\[mygallery\]#i';
1058        $replacements[] = $conf['gallery_title'];
1059        $patterns[] = '#\[myurl\]#i';
1060        $replacements[] = get_gallery_home_url();
1061
1062        if (function_exists('get_user_language_desc'))
1063        {
1064          $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT1']));
1065        }
1066        else
1067        {
1068          $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT1']));
1069        }
1070        $page['infos'][]=$custom_text;
1071      }
1072    } 
1073    else
1074    {
1075      if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT2']) and !empty($conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT2']))
1076      {
1077        // Management of Extension flags ([username], [mygallery], [myurl])
1078        // ----------------------------------------------------------------
1079        $patterns[] = '#\[username\]#i';
1080        $replacements[] = $result['username'];
1081        $patterns[] = '#\[mygallery\]#i';
1082        $replacements[] = $conf['gallery_title'];
1083        $patterns[] = '#\[myurl\]#i';
1084        $replacements[] = get_gallery_home_url();
1085
1086        if (function_exists('get_user_language_desc'))
1087        {
1088          $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT2']));
1089        }
1090        else
1091        {
1092          $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_CUSTOM_TXT2']));
1093        }
1094
1095        $page['errors'][]=$custom_text;
1096      }
1097    }
1098  }
1099}
1100
1101
1102/**
1103 * Triggered on render_lost_password_mail_content
1104 *
1105 * Adds a customized text in lost password email content
1106 * Added text is inserted before users login name and new password
1107 *
1108 * @param : Standard Piwigo email content
1109 *
1110 * @return : Customized content added to standard content
1111 *
1112 */
1113function UAM_lost_password_mail_content($infos)
1114{
1115  global $conf;
1116
1117  load_language('plugin.lang', UAM_PATH);
1118
1119  $conf_UAM = unserialize($conf['UserAdvManager']);
1120
1121  if (isset($conf_UAM['CUSTOMPASSWRETR']) and $conf_UAM['CUSTOMPASSWRETR'] == 'true')
1122  {
1123    // Management of Extension flags ([mygallery], [myurl])
1124    $patterns[] = '#\[mygallery\]#i';
1125    $replacements[] = $conf['gallery_title'];
1126    $patterns[] = '#\[myurl\]#i';
1127    $replacements[] = get_gallery_home_url();
1128
1129    $infos = preg_replace($patterns, $replacements, $conf_UAM['CUSTOMPASSWRETR_TEXT'])."\n"."\n".$infos;
1130  }
1131  return $infos;
1132}
1133
1134
1135/**
1136 * Function called from main.inc.php to send validation email
1137 *
1138 * @param : Type of email, user id, username, email address, confirmation (optional)
1139 *
1140 */
1141function SendMail2User($typemail, $id, $username, $password, $email, $confirm)
1142{
1143  global $conf;
1144
1145  $conf_UAM = unserialize($conf['UserAdvManager']);
1146  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1147
1148  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1149
1150        $infos1_perso = "";
1151  $infos2_perso = "";
1152  $subject = "";
1153
1154// We have to get the user's language in database
1155// ----------------------------------------------
1156  $query ='
1157SELECT user_id, language
1158FROM '.USER_INFOS_TABLE.'
1159WHERE user_id = '.$id.'
1160;';
1161  $data = pwg_db_fetch_assoc(pwg_query($query));
1162
1163// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1164// -------------------------------------------------------------------------------------------------------------------------------
1165  if (empty($data))
1166  {
1167// And switch gallery to this language before using personalized and multilangual contents
1168// ---------------------------------------------------------------------------------------
1169    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1170    switch_lang_to($language);
1171  }
1172  else
1173  {
1174// And switch gallery to this language before using personalized and multilangual contents
1175// ---------------------------------------------------------------------------------------
1176    //$language = $data['language']; // Usefull for debugging
1177    switch_lang_to($data['language']);
1178    load_language('plugin.lang', UAM_PATH);
1179  }
1180
1181  switch($typemail)
1182  {
1183    case 1: // Confirmation email on user registration - Without information email (already managed by Piwigo)
1184      if (isset($conf_UAM['CONFIRMMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_SUBJECT']))
1185      {
1186        // Management of Extension flags ([username], [mygallery])
1187        // -------------------------------------------------------
1188        $patterns[] = '#\[username\]#i';
1189        $replacements[] = $username;
1190        $patterns[] = '#\[mygallery\]#i';
1191        $replacements[] = $conf['gallery_title'];
1192
1193        if (function_exists('get_user_language_desc'))
1194        {
1195          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n";
1196        }
1197        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n"; 
1198      }
1199
1200      break;
1201
1202    case 2: // Confirmation email on user profile update - With information email if modification done in user profile
1203      if (isset($conf_UAM['CONFIRMMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_SUBJECT']))
1204      {
1205        // Management of Extension flags ([username], [mygallery])
1206        // -------------------------------------------------------
1207        $patterns[] = '#\[username\]#i';
1208        $replacements[] = $username;
1209        $patterns[] = '#\[mygallery\]#i';
1210        $replacements[] = $conf['gallery_title'];
1211
1212        if (function_exists('get_user_language_desc'))
1213        {
1214          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n";
1215        }
1216        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n"; 
1217      }
1218
1219      $password = !empty($password) ? $password : l10n('UAM_empty_pwd');
1220
1221      if (isset($conf_UAM['MAILINFO_TEXT']) and !empty($conf_UAM['MAILINFO_TEXT']))
1222      {
1223        // Management of Extension flags ([username], [mygallery], [myurl])
1224        // ----------------------------------------------------------------
1225        $patterns[] = '#\[username\]#i';
1226        $replacements[] = $username;
1227        $patterns[] = '#\[mygallery\]#i';
1228        $replacements[] = $conf['gallery_title'];
1229        $patterns[] = '#\[myurl\]#i';
1230        $replacements[] = get_gallery_home_url();
1231
1232        if (function_exists('get_user_language_desc'))
1233        {
1234          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n";
1235        }
1236        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n"; 
1237      }
1238
1239      if (isset($conf_UAM['MAIL_INFO']) and $conf_UAM['MAIL_INFO'] == 'true')
1240      {
1241        if (isset($conf_UAM['HIDEPASSW']) and $conf_UAM['HIDEPASSW'] == 'true') // Allow display of clear password in email
1242        {
1243          $infos1 = array(
1244            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1245            get_l10n_args('UAM_User: %s', stripslashes($username)),
1246            get_l10n_args('UAM_Password: %s', $password),
1247            get_l10n_args('Email: %s', $email),
1248            get_l10n_args('', ''),
1249          );
1250        }
1251        else // Do not allow display of clear password in email
1252        {
1253          $infos1 = array(
1254            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1255            get_l10n_args('UAM_User: %s', stripslashes($username)),
1256            get_l10n_args('Email: %s', $email),
1257            get_l10n_args('', ''),
1258          );
1259        }
1260      }
1261
1262      break;
1263
1264    case 3: // Only information email send to user if checked
1265      if (isset($conf_UAM['INFOMAIL_SUBJECT']) and !empty($conf_UAM['INFOMAIL_SUBJECT']))
1266      {
1267        // Management of Extension flags ([username], [mygallery])
1268        // -------------------------------------------------------
1269        $patterns[] = '#\[username\]#i';
1270        $replacements[] = $username;
1271        $patterns[] = '#\[mygallery\]#i';
1272        $replacements[] = $conf['gallery_title'];
1273
1274        if (function_exists('get_user_language_desc'))
1275        {
1276          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['INFOMAIL_SUBJECT']))."\n\n";
1277        }
1278        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['INFOMAIL_SUBJECT']))."\n\n"; 
1279      }
1280
1281      $password = !empty($password) ? $password : l10n('UAM_no_update_pwd');
1282
1283      if (isset($conf_UAM['MAILINFO_TEXT']) and !empty($conf_UAM['MAILINFO_TEXT']))
1284      {
1285        // Management of Extension flags ([username], [mygallery], [myurl])
1286        // ----------------------------------------------------------------
1287        $patterns[] = '#\[username\]#i';
1288        $replacements[] = $username;
1289        $patterns[] = '#\[mygallery\]#i';
1290        $replacements[] = $conf['gallery_title'];
1291        $patterns[] = '#\[myurl\]#i';
1292        $replacements[] = get_gallery_home_url();
1293
1294        if (function_exists('get_user_language_desc'))
1295        {
1296          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n";
1297        }
1298        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n"; 
1299      }
1300
1301      if (isset($conf_UAM['MAIL_INFO']) and $conf_UAM['MAIL_INFO'] == 'true')
1302      {
1303        if (isset($conf_UAM['HIDEPASSW']) and $conf_UAM['HIDEPASSW'] == 'true') // Allow display of clear password in email
1304        {
1305          $infos1 = array(
1306            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1307            get_l10n_args('UAM_User: %s', stripslashes($username)),
1308            get_l10n_args('UAM_Password: %s', $password),
1309            get_l10n_args('Email: %s', $email),
1310            get_l10n_args('', ''),
1311          );
1312        }
1313        else // Do not allow display of clear password in email
1314        {
1315          $infos1 = array(
1316            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1317            get_l10n_args('UAM_User: %s', stripslashes($username)),
1318            get_l10n_args('Email: %s', $email),
1319            get_l10n_args('', ''),
1320          );
1321        }
1322      }
1323
1324      break;
1325  }
1326
1327  if ((isset($conf_UAM['CONFIRM_MAIL']) and ($conf_UAM['CONFIRM_MAIL'] == 'true')) and $confirm) // Add confirmation link ?
1328  {
1329    $infos2 = array(
1330      get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
1331      get_l10n_args('', ''),
1332    );
1333
1334    if (isset($conf_UAM['CONFIRMMAIL_TEXT']) and !empty($conf_UAM['CONFIRMMAIL_TEXT'])) // Add personal text in confirmation email ?
1335    {
1336      // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1337      // -------------------------------------------------------------------------
1338      $patterns[] = '#\[username\]#i';
1339      $replacements[] = $username;
1340      $patterns[] = '#\[mygallery\]#i';
1341      $replacements[] = $conf['gallery_title'];
1342      $patterns[] = '#\[myurl\]#i';
1343      $replacements[] = get_gallery_home_url();
1344
1345      if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT'] == 'true') // [Kdays] replacement only if related option is active
1346      {
1347        $patterns[] = '#\[Kdays\]#i';
1348        $replacements[] = $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'];
1349      }
1350
1351      if (function_exists('get_user_language_desc'))
1352      {
1353        $infos2_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_TEXT']))."\n\n";
1354      }
1355      else $infos2_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_TEXT']))."\n\n";
1356    }
1357  }
1358
1359// Sending the email with subject and contents
1360// -------------------------------------------
1361  if ((isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'local') and $confirm)
1362        {
1363    switch_lang_to(get_default_language());
1364
1365        load_language('plugin.lang', UAM_PATH);
1366        $subject = get_l10n_args('UAM_Subject admin validation for %s',$username);
1367
1368                $content = array(
1369         get_l10n_args('UAM_Manual_validation_needed_for %s', stripslashes($username)),
1370     get_l10n_args('', ''),
1371     get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
1372    );
1373
1374    UAM_mail_notification_admins($subject, $content);
1375  }
1376        elseif ((isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true') and $confirm)
1377        {
1378          // Adding gallery URL at the end of the email
1379    if (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'true')
1380    {
1381      pwg_mail($email, array(
1382        'subject' => $subject,
1383         'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1384      ));
1385    }
1386    // Do not add gallery URL at the end of the email
1387    elseif (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'false')
1388    {
1389      pwg_mail($email, array(
1390        'subject' => $subject,
1391         'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : ""),
1392      ));
1393    }
1394    // By default do not add gallery URL at the end of the email
1395    else
1396    {
1397      pwg_mail($email, array(
1398        'subject' => $subject,
1399         'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : ""),
1400      ));
1401    }
1402        }
1403// Switching back to default language
1404// ----------------------------------
1405switch_lang_back();
1406}
1407
1408
1409/**
1410 * Function called from SendMail2User in functions.inc.php to notify admins on user registration validation with validation key
1411 *
1412 * @param:
1413 *   - keyargs_subject: mail subject on l10n_args format
1414 *   - keyargs_content: mail content on l10n_args format
1415 *
1416 * @return boolean (Ok or not)
1417 */
1418function UAM_mail_notification_admins($keyargs_subject, $keyargs_content)
1419{
1420  global $conf, $user;
1421
1422  // Check arguments
1423  if (empty($keyargs_subject) or empty($keyargs_content))
1424  {
1425    return false;
1426  }
1427
1428  $return = true;
1429
1430  $admins = array();
1431
1432  $query = '
1433SELECT
1434    u.username AS username,
1435    u.mail_address AS mail_address
1436  FROM '.USERS_TABLE.' AS u
1437    JOIN '.USER_INFOS_TABLE.' AS i ON i.user_id = id
1438  WHERE i.status in (\'webmaster\',  \'admin\')
1439    AND mail_address IS NOT NULL
1440    AND i.user_id = id
1441  ORDER BY username
1442;';
1443
1444  $datas = pwg_query($query);
1445  if (!empty($datas))
1446  {
1447    while ($admin = pwg_db_fetch_assoc($datas))
1448    {
1449      if (!empty($admin['mail_address']))
1450      {
1451        array_push($admins, format_email($admin['username'], $admin['mail_address']));
1452      }
1453    }
1454  }
1455
1456  if (count($admins) > 0)
1457  {
1458    $content = l10n_args($keyargs_content)."\n";
1459
1460    $return = pwg_mail(
1461      implode(', ', $admins),
1462      array(
1463        'subject' => '['.$conf['gallery_title'].'] '.l10n_args($keyargs_subject),
1464        'content' => $content,
1465        'content_format' => 'text/plain',
1466        'email_format' => 'text/plain',
1467        )
1468      );
1469  }
1470
1471  return $return;
1472}
1473
1474
1475/**
1476 * Function called from UAM_admin.php to resend validation email with or without new validation key
1477 *
1478 * @param : Type of email, user id, username, email address, confirmation (optional)
1479 *
1480 */
1481function ResendMail2User($typemail, $user_id, $username, $email, $confirm)
1482{
1483  global $conf;
1484 
1485  $subject = "";
1486
1487  $conf_UAM = unserialize($conf['UserAdvManager']);
1488
1489  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1490 
1491  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1492 
1493// We have to get the user's language in database
1494// ----------------------------------------------
1495  $query ='
1496SELECT user_id, language
1497FROM '.USER_INFOS_TABLE.'
1498WHERE user_id = '.$user_id.'
1499;';
1500  $data = pwg_db_fetch_assoc(pwg_query($query));
1501  $language = $data['language'];
1502
1503// And switch gallery to this language before using personalized and multilangual contents
1504// ---------------------------------------------------------------------------------------
1505  switch_lang_to($data['language']);
1506
1507  load_language('plugin.lang', UAM_PATH);
1508
1509  switch($typemail)
1510  {
1511    case 1: //Generating email content for remind with a new key
1512      if (isset($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))
1513      {
1514        // Management of Extension flags ([username], [mygallery])
1515        // -------------------------------------------------------
1516        $patterns[] = '#\[username\]#i';
1517        $replacements[] = $username;
1518        $patterns[] = '#\[mygallery\]#i';
1519        $replacements[] = $conf['gallery_title'];
1520
1521        if (function_exists('get_user_language_desc'))
1522        {
1523          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n";
1524        }
1525        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n"; 
1526      }
1527
1528      if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT1']) and !empty($conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT1']) and isset($conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL'] == 'true' and $confirm)
1529      {
1530                // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1531        // -------------------------------------------------------------------------
1532        $patterns[] = '#\[username\]#i';
1533        $replacements[] = $username;
1534        $patterns[] = '#\[mygallery\]#i';
1535        $replacements[] = $conf['gallery_title'];
1536        $patterns[] = '#\[myurl\]#i';
1537        $replacements[] = get_gallery_home_url();
1538
1539        if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT'] == 'true') // [Kdays] replacement only if related option is active
1540        {
1541          $patterns[] = '#\[Kdays\]#i';
1542          $replacements[] = $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'];
1543        }
1544
1545        if (function_exists('get_user_language_desc'))
1546        {
1547          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT1']))."\n\n";
1548        }
1549                                else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT1']))."\n\n";
1550
1551        $infos2 = array
1552        (
1553          get_l10n_args('UAM_Link: %s', ResetConfirmMail($user_id)),
1554          get_l10n_args('', ''),
1555        );
1556      }
1557
1558// Set reminder true
1559// -----------------     
1560      $query = '
1561UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1562SET reminder = "true"
1563WHERE user_id = '.$user_id.'
1564;';
1565      pwg_query($query);
1566
1567      break;
1568
1569    case 2: //Generating email content for remind without a new key
1570      if (isset($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))
1571      {
1572        // Management of Extension flags ([username], [mygallery])
1573        // -------------------------------------------------------
1574        $patterns[] = '#\[username\]#i';
1575        $replacements[] = $username;
1576        $patterns[] = '#\[mygallery\]#i';
1577        $replacements[] = $conf['gallery_title'];
1578   
1579        if (function_exists('get_user_language_desc'))
1580        {
1581          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n";
1582        }
1583        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n"; 
1584      }
1585
1586      if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT2']) and !empty($conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT2']) and isset($conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL'] == 'true' and !$confirm)
1587      {
1588        // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1589        // -------------------------------------------------------------------------
1590        $patterns[] = '#\[username\]#i';
1591        $replacements[] = $username;
1592        $patterns[] = '#\[mygallery\]#i';
1593        $replacements[] = $conf['gallery_title'];
1594        $patterns[] = '#\[myurl\]#i';
1595        $replacements[] = get_gallery_home_url();
1596
1597        if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT'] == 'true') // [Kdays] replacement only if related option is active
1598        {
1599          $patterns[] = '#\[Kdays\]#i';
1600          $replacements[] = $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'];
1601        }
1602
1603        if (function_exists('get_user_language_desc'))
1604        {
1605          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT2']))."\n\n";
1606        }
1607        else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT2']))."\n\n";
1608      }
1609
1610// Set reminder true
1611// -----------------
1612      $query = '
1613UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1614SET reminder = "true"
1615WHERE user_id = '.$user_id.'
1616;';
1617      pwg_query($query);
1618     
1619    break;
1620        }
1621
1622  // Adding gallery URL at the end of the email
1623  if (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'true')
1624  {
1625    pwg_mail($email, array(
1626      'subject' => $subject,
1627      'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1628    ));
1629  }
1630  // Do not add gallery URL at the end of the email
1631  elseif (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'false')
1632  {
1633    pwg_mail($email, array(
1634      'subject' => $subject,
1635      'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : ""),
1636    ));
1637  }
1638  // By default do not add gallery URL at the end of the email
1639  else
1640  {
1641    pwg_mail($email, array(
1642      'subject' => $subject,
1643      'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : ""),
1644    ));
1645  }
1646
1647  // Switching back to default language
1648        // ----------------------------------
1649        switch_lang_back();
1650}
1651
1652
1653/**
1654 * Function called from UAM_admin.php to send a reminder mail for ghost users
1655 *
1656 * @param : User id, username, email address
1657 *
1658 */
1659function ghostreminder($user_id, $username, $email)
1660{
1661  global $conf;
1662
1663  $conf_UAM = unserialize($conf['UserAdvManager']);
1664  $subject = "";
1665
1666  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1667
1668// We have to get the user's language in database
1669// ----------------------------------------------
1670  $query ='
1671SELECT user_id, language
1672FROM '.USER_INFOS_TABLE.'
1673WHERE user_id = '.$user_id.'
1674;';
1675  $data = pwg_db_fetch_assoc(pwg_query($query));
1676  $language = $data['language'];
1677
1678// And switch gallery to this language before using personalized and multilangual contents
1679// ---------------------------------------------------------------------------------------
1680  switch_lang_to($data['language']);
1681
1682  load_language('plugin.lang', UAM_PATH);
1683
1684  if (isset($conf_UAM['GTREMINDER_SUBJECT']) and !empty($conf_UAM['GTREMINDER_SUBJECT']))
1685  {
1686    // Management of Extension flags ([username], [mygallery])
1687    // -------------------------------------------------------
1688    $patterns[] = '#\[username\]#i';
1689    $replacements[] = $username;
1690    $patterns[] = '#\[mygallery\]#i';
1691    $replacements[] = $conf['gallery_title'];
1692
1693    if (function_exists('get_user_language_desc'))
1694    {
1695      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTREMINDER_SUBJECT']))."\n\n";
1696    }
1697    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTREMINDER_SUBJECT']))."\n\n"; 
1698  }
1699
1700  if (isset($conf_UAM['GHOSTRACKER_REMINDERTEXT']) and !empty($conf_UAM['GHOSTRACKER_REMINDERTEXT']) and isset($conf_UAM['GHOSTRACKER']) and $conf_UAM['GHOSTRACKER'] == 'true')
1701  {
1702    // Management of Extension flags ([username], [mygallery], [myurl], [days])
1703    // ------------------------------------------------------------------------
1704    $patterns[] = '#\[username\]#i';
1705    $replacements[] = $username;
1706    $patterns[] = '#\[mygallery\]#i';
1707    $replacements[] = $conf['gallery_title'];
1708    $patterns[] = '#\[myurl\]#i';
1709    $replacements[] = get_gallery_home_url();
1710    $patterns[] = '#\[days\]#i';
1711    $replacements[] = $conf_UAM['GHOSTRACKER_DAYLIMIT'];
1712
1713    if (function_exists('get_user_language_desc'))
1714    {
1715      $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GHOSTRACKER_REMINDERTEXT']))."\n\n";
1716    }
1717    else
1718    {
1719      $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM['GHOSTRACKER_REMINDERTEXT']))."\n\n";
1720    }
1721
1722    resetlastvisit($user_id);
1723  }
1724
1725  // Adding gallery URL at the end of the email
1726  if (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'true')
1727  {
1728    pwg_mail($email, array(
1729      'subject' => $subject,
1730      'content' => $infos1.get_absolute_root_url(),
1731    ));
1732  }
1733  // Do not add gallery URL at the end of the email
1734  elseif (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'false')
1735  {
1736    pwg_mail($email, array(
1737      'subject' => $subject,
1738      'content' => $infos1,
1739    ));
1740  }
1741  // By default do not add gallery URL at the end of the email
1742  else
1743  {
1744    pwg_mail($email, array(
1745      'subject' => $subject,
1746      'content' => $infos1,
1747    ));
1748  }
1749
1750  // Switching back to default language
1751        // ----------------------------------
1752        switch_lang_back();
1753}
1754
1755
1756/**
1757 * Function called from functions.inc.php to send notification email when user have been downgraded
1758 *
1759 * @param : user id, username, email address
1760 *
1761 */
1762function demotion_mail($id, $username, $email)
1763{
1764  global $conf;
1765
1766  $conf_UAM = unserialize($conf['UserAdvManager']);
1767
1768  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1769 
1770        $custom_txt = "";
1771        $subject = "";
1772
1773// We have to get the user's language in database
1774// ----------------------------------------------
1775  $query = '
1776SELECT user_id, language
1777FROM '.USER_INFOS_TABLE.'
1778WHERE user_id = '.$id.'
1779;';
1780
1781  $data = pwg_db_fetch_assoc(pwg_query($query));
1782
1783// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1784// -------------------------------------------------------------------------------------------------------------------------------
1785  if (empty($data))
1786  {
1787// And switch gallery to this language before using personalized and multilangual contents
1788// ---------------------------------------------------------------------------------------
1789    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1790    switch_lang_to($language);
1791  }
1792  else
1793  {
1794// And switch gallery to this language before using personalized and multilangual contents
1795// ---------------------------------------------------------------------------------------
1796    $language = $data['language']; // Usefull for debugging
1797    switch_lang_to($data['language']);
1798    load_language('plugin.lang', UAM_PATH);
1799  }
1800
1801  if (isset($conf_UAM['GTAUTOMAIL_SUBJECT']) and !empty($conf_UAM['GTAUTOMAIL_SUBJECT']))
1802  {
1803    // Management of Extension flags ([username], [mygallery])
1804    // -------------------------------------------------------
1805    $patterns[] = '#\[username\]#i';
1806    $replacements[] = $username;
1807    $patterns[] = '#\[mygallery\]#i';
1808    $replacements[] = $conf['gallery_title'];
1809
1810    if (function_exists('get_user_language_desc'))
1811    {
1812      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAIL_SUBJECT']))."\n\n";
1813    }
1814    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAIL_SUBJECT']))."\n\n"; 
1815  }
1816
1817  if (isset($conf_UAM['GTAUTOMAILTEXT']) and !empty($conf_UAM['GTAUTOMAILTEXT']))
1818  {
1819    // Management of Extension flags ([username], [mygallery], [myurl])
1820    // ----------------------------------------------------------------
1821    $patterns[] = '#\[username\]#i';
1822    $replacements[] = stripslashes($username);
1823    $patterns[] = '#\[mygallery\]#i';
1824    $replacements[] = $conf['gallery_title'];
1825    $patterns[] = '#\[myurl\]#i';
1826    $replacements[] = get_gallery_home_url();
1827
1828    if (function_exists('get_user_language_desc'))
1829    {
1830      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAILTEXT']))."\n\n";
1831    }
1832    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAILTEXT']))."\n\n"; 
1833  }
1834
1835  $infos1 = array(
1836    get_l10n_args('UAM_User: %s', stripslashes($username)),
1837    get_l10n_args('Email: %s', $email),
1838    get_l10n_args('', ''),
1839  );
1840
1841  $infos2 = array
1842  (
1843    get_l10n_args('UAM_Link: %s', ResetConfirmMail($id)),
1844    get_l10n_args('', ''),
1845  ); 
1846
1847  resetlastvisit($id);
1848
1849// Sending the email with subject and contents
1850// -------------------------------------------
1851  // Adding gallery URL at the end of the email
1852  if (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'true')
1853  {
1854    pwg_mail($email, array(
1855      'subject' => $subject,
1856      'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url(),
1857    ));
1858  }
1859  // Do not add gallery URL at the end of the email
1860  elseif (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'false')
1861  {
1862    pwg_mail($email, array(
1863      'subject' => $subject,
1864      'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n"),
1865    ));
1866  }
1867  // By default do not add gallery URL at the end of the email
1868  else
1869  {
1870    pwg_mail($email, array(
1871      'subject' => $subject,
1872      'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n"),
1873    ));
1874  }
1875
1876                // Switching back to default language
1877                // ----------------------------------
1878                switch_lang_back();
1879}
1880
1881
1882/**
1883 * Function called from UAM_admin.php to send notification email when user registration have been manually validated by admin
1884 *
1885 * @param : user id
1886 *
1887 */
1888function validation_mail($id)
1889{
1890  global $conf;
1891
1892  $conf_UAM = unserialize($conf['UserAdvManager']);
1893
1894  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1895
1896        $custom_txt = "";
1897  $subject = "";
1898
1899// We have to get the user's language in database
1900// ----------------------------------------------
1901  $query ='
1902SELECT user_id, language
1903FROM '.USER_INFOS_TABLE.'
1904WHERE user_id = '.$id.'
1905;';
1906
1907  $data = pwg_db_fetch_assoc(pwg_query($query));
1908
1909// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1910// -------------------------------------------------------------------------------------------------------------------------------
1911  if (empty($data))
1912  {
1913// And switch gallery to this language before using personalized and multilangual contents
1914// ---------------------------------------------------------------------------------------
1915    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1916    switch_lang_to($language);
1917  }
1918  else
1919  {
1920// And switch gallery to this language before using personalized and multilangual contents
1921// ---------------------------------------------------------------------------------------
1922    $language = $data['language']; // Usefull for debugging
1923    switch_lang_to($data['language']);
1924    load_language('plugin.lang', UAM_PATH);
1925  }
1926
1927// Retreive users email and user name from id
1928// ------------------------------------------
1929  $query ='
1930SELECT id, username, mail_address
1931FROM '.USERS_TABLE.'
1932WHERE id = '.$id.'
1933;';
1934
1935  $result = pwg_db_fetch_assoc(pwg_query($query));
1936
1937  if (isset($conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']) and !empty($conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']))
1938  {
1939    // Management of Extension flags ([username], [mygallery])
1940    // -------------------------------------------------------
1941    $patterns[] = '#\[username\]#i';
1942    $replacements[] = $result['username'];
1943    $patterns[] = '#\[mygallery\]#i';
1944    $replacements[] = $conf['gallery_title'];
1945
1946    if (function_exists('get_user_language_desc'))
1947    {
1948      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']))."\n\n";
1949    }
1950    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']))."\n\n";
1951  }
1952
1953  if (isset($conf_UAM['ADMINVALIDATIONMAIL']) and !empty($conf_UAM['ADMINVALIDATIONMAIL']))
1954  {
1955    // Management of Extension flags ([username], [mygallery], [myurl])
1956    // ----------------------------------------------------------------
1957    $patterns[] = '#\[username\]#i';
1958    $replacements[] = $result['username'];
1959    $patterns[] = '#\[mygallery\]#i';
1960    $replacements[] = $conf['gallery_title'];
1961    $patterns[] = '#\[myurl\]#i';
1962    $replacements[] = get_gallery_home_url();
1963    if (function_exists('get_user_language_desc'))
1964    {
1965      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL']))."\n\n";
1966    }
1967    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL']))."\n\n";
1968  }
1969
1970  $infos = array(
1971    get_l10n_args('UAM_User: %s', stripslashes($result['username'])),
1972    get_l10n_args('Email: %s', $result['mail_address']),
1973    get_l10n_args('', ''),
1974  );
1975
1976// Sending the email with subject and contents
1977// -------------------------------------------
1978  // Adding gallery URL at the end of the email
1979  if (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'true')
1980  {
1981    pwg_mail($result['mail_address'], array(
1982      'subject' => $subject,
1983      'content' => (l10n_args($infos)."\n\n".$custom_txt).get_absolute_root_url(),
1984    ));
1985  }
1986  // Do not add gallery URL at the end of the email
1987  elseif (isset($conf_UAM['ADD_GALLERY_URL_TO_EMAILS']) and $conf_UAM['ADD_GALLERY_URL_TO_EMAILS'] == 'false')
1988  {
1989    pwg_mail($result['mail_address'], array(
1990      'subject' => $subject,
1991      'content' => (l10n_args($infos)."\n\n".$custom_txt),
1992    ));
1993  }
1994  // By defaukt do not add gallery URL at the end of the email
1995  else
1996  {
1997    pwg_mail($result['mail_address'], array(
1998      'subject' => $subject,
1999      'content' => (l10n_args($infos)."\n\n".$custom_txt),
2000    ));
2001  }
2002
2003  // Switching back to default language
2004        // ----------------------------------
2005        switch_lang_back();
2006}
2007
2008
2009/**
2010 * Function called from functions AddConfirmMail and ResetConfirmMail for validation key generation
2011 *
2012 * @return : validation key
2013 *
2014 */
2015function FindAvailableConfirmMailID()
2016{
2017  while (true)
2018  {
2019    $id = generate_key(16);
2020
2021    $query = '
2022SELECT COUNT(*)
2023FROM '.USER_CONFIRM_MAIL_TABLE.'
2024WHERE id = "'.$id.'"
2025;';
2026    list($count) = pwg_db_fetch_row(pwg_query($query));
2027
2028    if ($count == 0)
2029      return $id;
2030  }
2031}
2032
2033
2034/**
2035 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
2036 *
2037 * @param : User id, email address
2038 *
2039 * @return : Build validation key in URL
2040 *
2041 */
2042function AddConfirmMail($user_id, $email)
2043{
2044  global $conf;
2045
2046  $conf_UAM = unserialize($conf['UserAdvManager']);
2047  $Confirm_Mail_ID = FindAvailableConfirmMailID();
2048
2049  $dbnow = date("Y-m-d H:i:s");
2050
2051  if (isset($Confirm_Mail_ID))
2052  {
2053    $query = "
2054SELECT status
2055  FROM ".USER_INFOS_TABLE."
2056WHERE user_id = '".$user_id."'
2057;";
2058    list($status) = pwg_db_fetch_row(pwg_query($query));
2059
2060    // Insert $Confirm_Mail_ID in USER_CONFIRM_MAIL_TABLE
2061    $query = "
2062INSERT INTO ".USER_CONFIRM_MAIL_TABLE."
2063  (id, user_id, mail_address, status, date_check, reminder)
2064VALUES
2065  ('".$Confirm_Mail_ID."', '".$user_id."', '".$email."', '".$status."', null, 'false')
2066;";
2067    pwg_query($query);
2068
2069    // Set user permissions
2070    // --------------------
2071    SetPermission($user_id);
2072
2073    // Set UAM_validated field to false in #_users table
2074    // -------------------------------------------------
2075    SetUnvalidated($user_id);
2076
2077    if ($conf['guest_access'])
2078    {
2079      return(get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2080    }
2081    else
2082    {
2083      return(get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2084    }
2085  }
2086}
2087
2088
2089/**
2090 * Function called from UAM_Adduser() to set group/status/level to new users if manual validation is set
2091 *
2092 * @param : User id
2093 *
2094 *
2095 */
2096function SetPermission($user_id)
2097{
2098  global $conf;
2099
2100  $conf_UAM = unserialize($conf['UserAdvManager']);
2101
2102// Groups cleanup
2103// --------------
2104  $query = '
2105DELETE FROM '.USER_GROUP_TABLE.'
2106WHERE user_id = '.$user_id.'
2107  AND (
2108    group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2109  OR
2110    group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2111  )
2112;';
2113
2114  pwg_query($query);
2115
2116  if ($conf_UAM['NO_CONFIRM_STATUS'] <> -1) // Set status
2117  {
2118    $query = '
2119UPDATE '.USER_INFOS_TABLE.'
2120SET status = "'.$conf_UAM['NO_CONFIRM_STATUS'].'"
2121WHERE user_id = '.$user_id.'
2122;';
2123
2124    pwg_query($query);
2125  }
2126
2127  if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Set group
2128  {
2129    $query = '
2130INSERT INTO '.USER_GROUP_TABLE.'
2131  (user_id, group_id)
2132VALUES
2133  ('.$user_id.', '.$conf_UAM['NO_CONFIRM_GROUP'].')
2134;';
2135
2136    pwg_query($query);
2137  }
2138
2139  if ($conf_UAM['NO_VALID_LEVEL'] <> -1) // Set privacy level
2140  {
2141    $query = '
2142INSERT INTO '.USER_INFOS_TABLE.'
2143  (user_id, level)
2144VALUES
2145  ('.$user_id.', "'.$conf_UAM['NO_VALID_LEVEL'].'")
2146;';
2147
2148    pwg_query($query);
2149  }
2150}
2151
2152
2153/**
2154 * Function called from UAM_admin.php to reset validation key
2155 *
2156 * @param : User id
2157 *
2158 * @return : Build validation key in URL
2159 *
2160 */
2161function ResetConfirmMail($user_id)
2162{
2163  global $conf;
2164
2165  $Confirm_Mail_ID = FindAvailableConfirmMailID();
2166
2167  $dbnow = date("Y-m-d H:i:s");
2168
2169  if (isset($Confirm_Mail_ID))
2170  { 
2171    $query = '
2172UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2173SET id = "'.$Confirm_Mail_ID.'"
2174WHERE user_id = '.$user_id.'
2175;';
2176
2177    pwg_query($query);
2178
2179    $query = '
2180UPDATE '.USER_INFOS_TABLE.'
2181SET registration_date = "'.$dbnow.'"
2182WHERE user_id = '.$user_id.'
2183;';
2184
2185    pwg_query($query);
2186
2187    if ( $conf['guest_access'] )
2188    {
2189      return(get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2190    }
2191    else
2192    {
2193      return(get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2194    }
2195  }
2196}
2197
2198
2199/**
2200 * Function called from functions.inc.php to reset last visit date after sending a reminder
2201 *
2202 * @param : User id
2203 *
2204 */
2205function resetlastvisit($user_id)
2206{
2207  global $conf;
2208
2209  $dbnow = date("Y-m-d H:i:s");
2210
2211  $query = '
2212UPDATE '.USER_LASTVISIT_TABLE.'
2213SET lastvisit = "'.$dbnow.'", reminder = "true"
2214WHERE user_id = '.$user_id.'
2215;';
2216
2217  pwg_query($query);
2218}
2219
2220
2221/**
2222 * Function called from main.inc.php - Triggered on user deletion
2223 *
2224 */
2225function DeleteConfirmMail($user_id)
2226{
2227  $query = '
2228DELETE FROM '.USER_CONFIRM_MAIL_TABLE.'
2229WHERE user_id = '.$user_id.'
2230;';
2231
2232  pwg_query($query);
2233}
2234
2235
2236/**
2237 * Function called from main.inc.php - Triggered on user deletion
2238 *
2239 */
2240function DeleteLastVisit($user_id)
2241{
2242  $query = '
2243DELETE FROM '.USER_LASTVISIT_TABLE.'
2244WHERE user_id = '.$user_id.'
2245;';
2246
2247  pwg_query($query);
2248}
2249
2250
2251/**
2252 * Function called from main.inc.php - Triggered on user deletion
2253 *
2254 * @param : User id
2255 *
2256 */
2257function DeleteRedir($user_id)
2258{
2259  $tab = array();
2260
2261  $query = '
2262SELECT value
2263FROM '.CONFIG_TABLE.'
2264WHERE param = "UserAdvManager_Redir"
2265;';
2266
2267  $tab = pwg_db_fetch_row(pwg_query($query));
2268
2269  $values = explode(',', $tab[0]);
2270
2271  unset($values[array_search($user_id, $values)]);
2272
2273  $query = '
2274UPDATE '.CONFIG_TABLE.'
2275SET value = "'.implode(',', $values).'"
2276WHERE param = "UserAdvManager_Redir";';
2277
2278  pwg_query($query);
2279}
2280
2281
2282/**
2283 * Function called from ConfirmMail.php to verify validation key used by user according time limit
2284 * Return true is key validation is OK else return false
2285 *
2286 * @param : User id
2287 *
2288 * @return : Bool
2289 *
2290 */
2291function VerifyConfirmMail($id)
2292{
2293  global $conf;
2294
2295  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2296
2297  $conf_UAM = unserialize($conf['UserAdvManager']);
2298
2299  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2300
2301  $query = '
2302SELECT COUNT(*)
2303FROM '.USER_CONFIRM_MAIL_TABLE.'
2304WHERE id = "'.$id.'"
2305;';
2306
2307  list($count) = pwg_db_fetch_row(pwg_query($query));
2308
2309  if ($count == 1)
2310  {
2311    $query = '
2312SELECT user_id, status, date_check
2313FROM '.USER_CONFIRM_MAIL_TABLE.'
2314WHERE id = "'.$id.'"
2315;';
2316    $data = pwg_db_fetch_assoc(pwg_query($query));
2317
2318    if (!empty($data) and isset($data['user_id']) and is_null($data['date_check']))
2319    {
2320      $query = '
2321SELECT registration_date
2322FROM '.USER_INFOS_TABLE.'
2323WHERE user_id = '.$data['user_id'].'
2324;';
2325
2326      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2327
2328//              Time limit process             
2329// ******************************************** 
2330      if (!empty($registration_date))
2331      {
2332        // Verify Confirmmail with time limit ON
2333                // -------------------------------------
2334                                if (isset ($conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']))
2335        {
2336                                  // Dates formating and compare
2337                        // ---------------------------
2338                                        $today = date("d-m-Y"); // Get today's date
2339                                        list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2340                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2341
2342                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2343                                        list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2344                                        $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2345
2346          $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps   
2347                                        $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2348
2349                                        // Condition with the value set for time limit
2350                        // -------------------------------------------
2351                                        if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If Nb of days is less than the limit set
2352          {
2353            $dbnow = date("Y-m-d H:i:s");
2354
2355                        // Update ConfirmMail table
2356                        // ------------------------
2357                                                $query = '
2358UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2359SET date_check="'.$dbnow.'", reminder="false"
2360WHERE id = "'.$id.'"
2361;';
2362                                                pwg_query($query);
2363
2364                        // Update LastVisit table - Force reminder field to false
2365                        // Usefull when a user has been automatically downgraded and revalidate its registration
2366                        // -------------------------------------------------------------------------------------
2367                                                $query = '
2368UPDATE '.USER_LASTVISIT_TABLE.'
2369SET reminder="false"
2370WHERE user_id = "'.$data['user_id'].'"
2371;';
2372                                                pwg_query($query);
2373     
2374                                                if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from unvalidated users group
2375                                                {
2376              $query = '
2377DELETE FROM '.USER_GROUP_TABLE.'
2378WHERE user_id = '.$data['user_id'].'
2379  AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2380;';
2381                                                        pwg_query($query);
2382            }
2383
2384                                                if ($conf_UAM['VALIDATED_GROUP'] <> -1) // Add user to validated users group
2385                                                {
2386              $query = '
2387INSERT INTO '.USER_GROUP_TABLE.'
2388  (user_id, group_id)
2389VALUES
2390  ('.$data['user_id'].', '.$conf_UAM['VALIDATED_GROUP'].')
2391;';
2392                                                        pwg_query($query);
2393            }
2394
2395                                                if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Change user's status
2396                                                {
2397              $query = '
2398UPDATE '.USER_INFOS_TABLE.'
2399SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2400WHERE user_id = '.$data['user_id'].'
2401;';
2402                                                        pwg_query($query);
2403            }
2404
2405                                                if ($conf_UAM['VALID_LEVEL'] <> -1) // Change user's privacy level
2406                                                {
2407              $query = '
2408UPDATE '.USER_INFOS_TABLE.'
2409SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2410WHERE user_id = '.$data['user_id'].'
2411;';
2412                                                        pwg_query($query);
2413            }
2414
2415                                                // Set UAM_validated field to True in #_users table
2416            SetValidated($data['user_id']);
2417
2418                                                // Refresh user's category cache
2419            // -----------------------------
2420                                                invalidate_user_cache();
2421
2422                                                return true;
2423          }
2424          elseif ($deltadays > $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If timelimit exeeds
2425          {
2426            return false;
2427          }
2428        }
2429        // Verify Confirmmail with time limit OFF
2430        // --------------------------------------
2431        else
2432        {
2433          $dbnow = date("Y-m-d H:i:s");
2434
2435          // Update ConfirmMail table
2436          // ------------------------
2437                                        $query = '
2438UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2439SET date_check="'.$dbnow.'"
2440WHERE id = "'.$id.'"
2441;';
2442                                        pwg_query($query);
2443
2444          // Update LastVisit table - Force reminder field to false
2445          // Usefull when a user has been automatically downgraded and revalidate its registration
2446          // -------------------------------------------------------------------------------------
2447          $query = '
2448UPDATE '.USER_LASTVISIT_TABLE.'
2449SET reminder="false"
2450WHERE user_id = "'.$data['user_id'].'"
2451;';
2452          pwg_query($query);
2453
2454          if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from unvalidated users group
2455          {
2456            $query = '
2457DELETE FROM '.USER_GROUP_TABLE.'
2458WHERE user_id = '.$data['user_id'].'
2459AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2460;';
2461            pwg_query($query);
2462          }
2463
2464          if ($conf_UAM['VALIDATED_GROUP'] <> -1)
2465          {
2466            $query = '
2467DELETE FROM '.USER_GROUP_TABLE.'
2468WHERE user_id = '.$data['user_id'].'
2469AND group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2470;';
2471            pwg_query($query);
2472
2473            $query = '
2474INSERT INTO '.USER_GROUP_TABLE.'
2475  (user_id, group_id)
2476VALUES
2477  ('.$data['user_id'].', '.$conf_UAM['VALIDATED_GROUP'].')
2478;';
2479            pwg_query($query);
2480          }
2481
2482          if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Change user's status
2483          {
2484            $query = '
2485UPDATE '.USER_INFOS_TABLE.'
2486SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2487WHERE user_id = '.$data['user_id'].'
2488;';
2489            pwg_query($query);
2490          }
2491
2492          if ($conf_UAM['VALID_LEVEL'] <> -1) // Change user's privacy level
2493          {
2494            $query = '
2495UPDATE '.USER_INFOS_TABLE.'
2496SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2497WHERE user_id = '.$data['user_id'].'
2498;';
2499            pwg_query($query);
2500          }
2501
2502          // Set UAM_validated field to True in #_users table
2503          SetValidated($data['user_id']);
2504
2505          // Refresh user's category cache
2506          // -----------------------------
2507          invalidate_user_cache();
2508
2509          return true;
2510        }
2511      }
2512    }
2513    else if (!empty($data) and !is_null($data['date_check']))
2514    {
2515      return false;
2516    }
2517  }
2518  else
2519    return false;
2520}
2521
2522
2523/**
2524 * Function called from UAM_admin.php for manual validation by admin
2525 *
2526 * @param : User id
2527 *
2528 */
2529function ManualValidation($id)
2530{
2531                global $conf;
2532
2533                $conf_UAM = unserialize($conf['UserAdvManager']);
2534
2535                if (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true') // Set date of validation
2536                {
2537      $dbnow = date("Y-m-d H:i:s");
2538
2539                        $query = '
2540UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2541SET date_check="'.$dbnow.'"
2542WHERE user_id = '.$id.'
2543;';
2544                        pwg_query($query);
2545                }
2546
2547                if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from waiting group
2548                {
2549                                $query = '
2550DELETE FROM '.USER_GROUP_TABLE.'
2551WHERE user_id = '.$id.'
2552                AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2553;';
2554                                pwg_query($query);
2555                }
2556
2557                if ($conf_UAM['VALIDATED_GROUP'] <> -1) // Set user's valid group
2558                {
2559      $query = '
2560DELETE FROM '.USER_GROUP_TABLE.'
2561WHERE user_id = '.$id.'
2562                AND group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2563;';
2564      pwg_query($query);
2565
2566      $query = '
2567INSERT INTO '.USER_GROUP_TABLE.'
2568                (user_id, group_id)
2569VALUES
2570                ('.$id.', '.$conf_UAM['VALIDATED_GROUP'].')
2571;';
2572      pwg_query($query);
2573                }
2574
2575                if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Set user's valid status
2576                {
2577      $query = '
2578UPDATE '.USER_INFOS_TABLE.'
2579SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2580WHERE user_id = '.$id.'
2581;';
2582      pwg_query($query);
2583                }
2584
2585                if ($conf_UAM['VALID_LEVEL'] <> -1) // Set user's valid privacy level
2586                {
2587      $query = '
2588UPDATE '.USER_INFOS_TABLE.'
2589SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2590WHERE user_id = '.$id.'
2591;';
2592      pwg_query($query);
2593                }
2594
2595                // Set UAM_validated field to True in #_users table
2596                SetValidated($id);
2597}
2598
2599
2600/**
2601 * Function called from functions.inc.php - Check if username matches forbidden characters
2602 *
2603 * @param : User login
2604 *
2605 * @return : Bool
2606 *
2607 */
2608function ValidateUsername($login)
2609{
2610  global $conf;
2611
2612  $conf_UAM = unserialize($conf['UserAdvManager']);
2613
2614  if (isset($login) and isset($conf_UAM['USERNAME_CHAR_LIST']) and !empty($conf_UAM['USERNAME_CHAR_LIST']))
2615  {
2616    $conf_CharExclusion = preg_split("/,/",$conf_UAM['USERNAME_CHAR_LIST']);
2617    for ($i = 0 ; $i < count($conf_CharExclusion) ; $i++)
2618    {
2619      //Detect meta-characters (# ! ^ $ ( ) [ ] { } ? + * . \ -) for special pattern
2620      if ($conf_CharExclusion[$i] == "#"
2621       or $conf_CharExclusion[$i] == "$"
2622       or $conf_CharExclusion[$i] == "!"
2623       or $conf_CharExclusion[$i] == "^"
2624       or $conf_CharExclusion[$i] == "*"
2625       or $conf_CharExclusion[$i] == "?"
2626       or $conf_CharExclusion[$i] == "+"
2627       or $conf_CharExclusion[$i] == "."
2628       or $conf_CharExclusion[$i] == "\\"
2629       or $conf_CharExclusion[$i] == "|"
2630       or $conf_CharExclusion[$i] == "["
2631       or $conf_CharExclusion[$i] == "]"
2632       or $conf_CharExclusion[$i] == "("
2633       or $conf_CharExclusion[$i] == ")"
2634       or $conf_CharExclusion[$i] == "{"
2635       or $conf_CharExclusion[$i] == "}"
2636       or $conf_CharExclusion[$i] == "-")
2637      {
2638        $pattern = '/[][^$.\*+?(){}#|-]/i';
2639      }
2640      else
2641      {
2642        $pattern = '/'.$conf_CharExclusion[$i].'/i';
2643      }
2644
2645      if (preg_match($pattern, $login))
2646      {
2647        return true;
2648      }
2649    }
2650  }
2651  else
2652  {
2653    return false;
2654  }
2655}
2656
2657
2658/**
2659 * Function called from main.inc.php - Check if user's email is in excluded email providers list
2660 * Doesn't work on call - Must be copied in main.inc.php to work
2661 *
2662 * @param : Email address
2663 *
2664 * @return : Bool
2665 *
2666 */
2667function ValidateEmailProvider($email)
2668{
2669  global $conf;
2670
2671  $conf_UAM = unserialize($conf['UserAdvManager']);
2672
2673                if (isset($email) and isset($conf_UAM['MAILEXCLUSION_LIST']) and !empty($conf_UAM['MAILEXCLUSION_LIST']))
2674                {
2675      $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM['MAILEXCLUSION_LIST']);
2676      for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
2677      {
2678        $pattern = '/'.$conf_MailExclusion[$i].'/i';
2679        if (preg_match($pattern, $email))
2680        {
2681          return true;
2682        }
2683      }
2684    }
2685    else
2686    {
2687      return false;
2688    }
2689}
2690
2691
2692/**
2693 * Function called from UAM_admin.php - Get unvalidated users according time limit
2694 *
2695 * @return : List of users
2696 *
2697 */
2698function get_unvalid_user_list()
2699{
2700  global $conf, $page;
2701
2702  // Get ConfirmMail configuration
2703  // -----------------------------
2704  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2705  // Get UAM configuration
2706  // ---------------------
2707  $conf_UAM = unserialize($conf['UserAdvManager']);
2708
2709  $users = array();
2710
2711  // Search users depending expiration date
2712  // --------------------------------------
2713  $query = '
2714SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2715                u.'.$conf['user_fields']['username'].' AS username,
2716                u.'.$conf['user_fields']['email'].' AS email,
2717                ui.status,
2718                ui.enabled_high,
2719                ui.level,
2720                ui.registration_date
2721FROM '.USERS_TABLE.' AS u
2722  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2723    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2724  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
2725    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2726WHERE u.'.$conf['user_fields']['id'].' >= 3
2727  AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2728  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'"
2729  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'")
2730                AND u.UAM_validated = "false"
2731ORDER BY ui.registration_date ASC
2732;';
2733
2734  $result = pwg_query($query);
2735
2736  while ($row = pwg_db_fetch_assoc($result))
2737  {
2738    $user = $row;
2739    $user['groups'] = array();
2740
2741    array_push($users, $user);
2742  }
2743
2744  // Add groups list
2745  // ---------------
2746  $user_ids = array();
2747  foreach ($users as $i => $user)
2748  {
2749    $user_ids[$i] = $user['id'];
2750  }
2751
2752                $user_nums = array_flip($user_ids);
2753
2754  if (count($user_ids) > 0)
2755  {
2756    $query = '
2757SELECT user_id, group_id
2758  FROM '.USER_GROUP_TABLE.'
2759WHERE user_id IN ('.implode(',', $user_ids).')
2760;';
2761       
2762    $result = pwg_query($query);
2763       
2764    while ($row = pwg_db_fetch_assoc($result))
2765    {
2766      array_push(
2767        $users[$user_nums[$row['user_id']]]['groups'],
2768        $row['group_id']
2769      );
2770    }
2771  }
2772
2773  return $users;
2774}
2775
2776
2777/**
2778 * Function called from functions.inc.php - Get all users who haven't validate their registration in configured time
2779 * to delete or remail them automatically
2780 *
2781 * @return : List of users
2782 *
2783 */
2784function get_unvalid_user_autotasks()
2785{
2786  global $conf, $page;
2787
2788  // Get ConfirmMail configuration
2789  // -----------------------------
2790  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2791
2792  $users = array();
2793
2794  // search users depending expiration date
2795  // --------------------------------------
2796  $query = '
2797SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2798                u.UAM_validated,
2799                ui.registration_date
2800FROM '.USERS_TABLE.' AS u
2801  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2802    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2803WHERE u.'.$conf['user_fields']['id'].' >= 3
2804  AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2805  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'")
2806  AND u.UAM_validated <> "true"
2807ORDER BY ui.registration_date ASC;';
2808
2809  $result = pwg_query($query);
2810
2811  while ($row = pwg_db_fetch_assoc($result))
2812  {
2813    array_push($users, $row);
2814  }
2815
2816  return $users;
2817}
2818
2819
2820/**
2821 * Function called from UAM_admin.php - Get ghost users
2822 *
2823 * @return : List of users
2824 *
2825 */
2826function get_ghost_user_list()
2827{
2828  global $conf, $page;
2829
2830  $conf_UAM = unserialize($conf['UserAdvManager']);
2831
2832  $users = array();
2833
2834  // Search users depending expiration date
2835  // --------------------------------------
2836  $query = '
2837SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2838                u.'.$conf['user_fields']['username'].' AS username,
2839                u.'.$conf['user_fields']['email'].' AS email,
2840                lv.lastvisit,
2841                lv.reminder
2842FROM '.USERS_TABLE.' AS u
2843  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2844    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2845WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM['GHOSTRACKER_DAYLIMIT'].'")
2846AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2847ORDER BY lv.lastvisit ASC;';
2848
2849  $result = pwg_query($query);
2850     
2851  while ($row = pwg_db_fetch_assoc($result))
2852  {
2853    $user = $row;
2854    $user['groups'] = array();
2855
2856    array_push($users, $user);
2857  }
2858
2859  // Add groups list
2860  // ---------------
2861  $user_ids = array();
2862  foreach ($users as $i => $user)
2863  {
2864        $user_ids[$i] = $user['id'];
2865  }
2866
2867  return $users;
2868}
2869
2870
2871/**
2872 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
2873 *
2874 * @return : List of users to delete or downgrade automatically
2875 *
2876 */
2877function get_ghosts_autotasks()
2878{
2879  global $conf, $page;
2880
2881  $conf_UAM = unserialize($conf['UserAdvManager']);
2882
2883  $users = array();
2884 
2885  // Search users depending expiration date and reminder sent
2886  // --------------------------------------------------------
2887  $query = '
2888SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2889                lv.lastvisit
2890FROM '.USERS_TABLE.' AS u
2891  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2892    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2893WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM['GHOSTRACKER_DAYLIMIT'].'")
2894AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2895ORDER BY lv.lastvisit ASC;';
2896
2897  $result = pwg_query($query);
2898     
2899  while ($row = pwg_db_fetch_assoc($result))
2900  {
2901    array_push($users, $row);
2902  }
2903
2904  return $users;
2905}
2906
2907
2908/**
2909 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
2910 *
2911 * @return : List of users
2912 *
2913 */
2914function get_user_list()
2915{
2916  global $conf, $page;
2917
2918  $users = array();
2919
2920  // Search users depending expiration date with exclusion of Adult_Content generic users
2921  // ------------------------------------------------------------------------------------
2922  $query = '
2923SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2924                u.'.$conf['user_fields']['username'].' AS username,
2925                u.'.$conf['user_fields']['email'].' AS email,
2926                ug.lastvisit
2927FROM '.USERS_TABLE.' AS u
2928  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
2929    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2930WHERE u.'.$conf['user_fields']['id'].' >= 3
2931  AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2932  AND u.username NOT LIKE "16"
2933  AND u.username NOT LIKE "18"
2934ORDER BY ug.lastvisit DESC
2935;';
2936
2937  $result = pwg_query($query);
2938     
2939  while ($row = pwg_db_fetch_assoc($result))
2940  {
2941    $user = $row;
2942    $user['groups'] = array();
2943
2944    array_push($users, $user);
2945  }
2946
2947  // Add groups list
2948  // ---------------
2949  $user_ids = array();
2950  foreach ($users as $i => $user)
2951  {
2952    $user_ids[$i] = $user['id'];
2953  }
2954
2955  return $users;
2956}
2957
2958
2959/**
2960 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
2961 *
2962 * @param : user id
2963 *
2964 * @return : Bool
2965 *
2966 */
2967function expiration($id)
2968{
2969        global $conf, $page;
2970
2971  // Get ConfirmMail configuration
2972  // -----------------------------
2973  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2974         
2975  // Get UAM configuration
2976  // ---------------------
2977  $conf_UAM = unserialize($conf['UserAdvManager']);
2978
2979  $query = '
2980SELECT registration_date
2981  FROM '.USER_INFOS_TABLE.'
2982WHERE user_id = '.$id.'
2983;';
2984  list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2985
2986//              Time limit process             
2987// ******************************************** 
2988  if (!empty($registration_date))
2989  {
2990    // Dates formating and compare
2991    // ---------------------------
2992    $today = date("d-m-Y"); // Get today's date
2993    list($day, $month, $year) = explode('-', $today); // explode date of today                                           
2994    $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2995
2996    list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2997    list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2998    $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2999
3000    $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps
3001    $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
3002
3003    // Condition with the value set for time limit
3004    // -------------------------------------------
3005    if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If Nb of days is less than the limit set
3006    {
3007      return false;
3008    }
3009    else
3010    {
3011      return true;
3012    }
3013  }
3014}
3015
3016
3017/**
3018 * Returns a password's score for password complexity check
3019 *
3020 * @param : password filled by user
3021 *
3022 * @return : Score calculation
3023 *
3024 * Thanx to MathieuGut from http://m-gut.developpez.com
3025 */
3026function testpassword($password) // $password given by user
3027{
3028
3029  // Variables initiation
3030  // --------------------
3031  $points = 0;
3032  $point_lowercase = 0;
3033  $point_uppercase = 0;
3034  $point_numbers = 0;
3035  $point_characters = 0;
3036
3037  // Getting password lengh
3038  // ----------------------
3039  $length = strlen($password);
3040
3041  // Loop to read password characters
3042  for($i = 0; $i < $length; $i++)
3043  {
3044    // Select each letters
3045    // $i is 0 at first turn
3046    // ---------------------
3047    $letters = $password[$i];
3048
3049    if ($letters>='a' && $letters<='z')
3050    {
3051      // Adding 1 point to score for a lowercase
3052      // ---------------------------------------
3053                                $points = $points + 1;
3054
3055      // Adding bonus points for lowercase
3056      // ---------------------------------
3057                  $point_lowercase = 1;
3058    }
3059    else if ($letters>='A' && $letters <='Z')
3060    {
3061      // Adding 2 points to score for uppercase
3062      // --------------------------------------
3063      $points = $points + 2;
3064
3065      // Adding bonus points for uppercase
3066      // ---------------------------------
3067      $point_uppercase = 2;
3068    }
3069    else if ($letters>='0' && $letters<='9')
3070    {
3071      // Adding 3 points to score for numbers
3072      // ------------------------------------
3073      $points = $points + 3;
3074
3075      // Adding bonus points for numbers
3076      // -------------------------------
3077      $point_numbers = 3;
3078    }
3079    else
3080    {
3081      // Adding 5 points to score for special characters
3082      // -----------------------------------------------
3083      $points = $points + 5;
3084               
3085      // Adding bonus points for special characters
3086      // ------------------------------------------
3087      $point_characters = 5;
3088    }
3089  }
3090
3091  // Calculating the coefficient points/length
3092  // -----------------------------------------
3093  $step1 = $points / $length;
3094
3095  // Calculation of the diversity of character types...
3096  // --------------------------------------------------
3097  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
3098
3099  // Multiplying the coefficient of diversity with that of the length
3100  // ----------------------------------------------------------------
3101  $score = $step1 * $step2;
3102
3103  // Multiplying the result by the length of the string
3104  // --------------------------------------------------
3105  $finalscore = $score * $length;
3106
3107  return $finalscore;
3108}
3109
3110
3111/**
3112 * UAM_check_profile - Thx to LucMorizur
3113 * checks if a user id is registered as having already
3114 * visited his profile page.
3115 *
3116 * @uid        : the user id
3117 *
3118 * @user_idsOK : (returned) array of all users ids having already visited
3119 *               their profile.php pages
3120 *
3121 * @returns    : true or false whether the users has already visited his
3122 *               profile.php page or not
3123 *
3124 */
3125function UAM_check_profile($uid, &$user_idsOK)
3126{
3127  $t = array();
3128  $v = false;
3129
3130  $query = '
3131SELECT value
3132FROM '.CONFIG_TABLE.'
3133WHERE param = "UserAdvManager_Redir"
3134;';
3135
3136  if ($v = (($t = pwg_db_fetch_row(pwg_query($query))) !== false))
3137  {
3138    $user_idsOK = explode(',', $t[0]);
3139    $v = (in_array($uid, $user_idsOK));
3140  }
3141  return $v;
3142}
3143
3144
3145/**
3146 * UAM_check_pwdreset
3147 * checks if a user id is registered as having already
3148 * changed his password.
3149 *
3150 * @uid        : the user id
3151 *
3152 * @returns    : true or false whether the users has already changed his password
3153 *
3154 */
3155function UAM_check_pwgreset($uid)
3156{
3157  $query = '
3158SELECT UAM_pwdreset
3159FROM '.USERS_TABLE.'
3160WHERE id='.$uid.'
3161;';
3162
3163  $result = pwg_db_fetch_assoc(pwg_query($query));
3164
3165  if($result['UAM_pwdreset'] == 'true')
3166  {
3167    return true;
3168  }
3169  else return false; 
3170}
3171
3172
3173/**
3174 * UAM_UsrReg_Verif
3175 * Check if the user who logged-in have validate his registration
3176 *
3177 * @returns : True if validation is OK else False
3178 */
3179function UAM_UsrReg_Verif($user_id)
3180{
3181  global $conf;
3182
3183  $query = '
3184SELECT UAM_validated
3185FROM '.USERS_TABLE.'
3186WHERE id='.$user_id.'
3187;';
3188
3189  $result = pwg_db_fetch_assoc(pwg_query($query));
3190
3191  if($result['UAM_validated'] == 'true' or is_null($result['UAM_validated']))
3192  {
3193    return true;
3194  }
3195  else return false;
3196}
3197
3198
3199/**
3200 * SetUnvalidated
3201 * Set UAM_validated field to false in #_users table
3202 *
3203 **/
3204function SetUnvalidated($user_id)
3205{
3206  $query ='
3207UPDATE '.USERS_TABLE.'
3208SET UAM_validated = "false"
3209WHERE id = '.$user_id.'
3210LIMIT 1
3211;';
3212
3213  pwg_query($query);
3214}
3215
3216
3217/**
3218 * SetValidated
3219 * Set UAM_validated field to true in #_users table
3220 *
3221 **/
3222function SetValidated($user_id)
3223{
3224  $query ='
3225UPDATE '.USERS_TABLE.'
3226SET UAM_validated = "true"
3227WHERE id = '.$user_id.'
3228LIMIT 1
3229;';
3230
3231  pwg_query($query);
3232}
3233
3234
3235/**
3236 * UAM_Set_PwdReset
3237 * Action in user_list to set a password reset for a user
3238 */
3239function UAM_Set_PwdReset($uid)
3240{
3241  $query ='
3242UPDATE '.USERS_TABLE.'
3243SET UAM_pwdreset = "true"
3244WHERE id = '.$uid.'
3245LIMIT 1
3246;';
3247
3248  pwg_query($query);
3249}
3250
3251
3252/**
3253 * UAM_loc_visible_user_list
3254 * Adds a new feature in user_list to allow password reset for selected users by admin
3255 *
3256 */
3257function UAM_loc_visible_user_list($visible_user_list)
3258{
3259  global $template;
3260
3261  $template->append('plugin_user_list_column_titles', l10n('UAM_PwdReset'));
3262
3263  $user_ids = array();
3264
3265  foreach ($visible_user_list as $i => $user)
3266  {
3267    $user_ids[$i] = $user['id'];
3268  }
3269
3270  $user_nums = array_flip($user_ids);
3271
3272  // Query to get information in database
3273  // ------------------------------------
3274  if (!empty($user_ids))
3275  {
3276    $query = '
3277SELECT DISTINCT id, UAM_pwdreset
3278  FROM '.USERS_TABLE.'
3279  WHERE id IN ('.implode(',', $user_ids).')
3280;';
3281    $result = pwg_query($query);
3282
3283    while ($row = pwg_db_fetch_assoc($result))
3284    {
3285      if ($row['UAM_pwdreset'] == 'false')
3286      {
3287        $pwdreset = l10n('UAM_PwdReset_Done');
3288      }
3289      else if ($row['UAM_pwdreset'] == 'true')
3290      {
3291        $pwdreset = l10n('UAM_PwdReset_Todo');
3292      }
3293      else $pwdreset = l10n('UAM_PwdReset_NA');
3294
3295                  $visible_user_list[$user_nums[$row['id']]]['plugin_columns'][] = $pwdreset; // Shows users password state in user_list
3296    }
3297  }
3298  return $visible_user_list;
3299}
3300
3301
3302/**
3303 * UAM specific database dump (only for MySql !)
3304 * Creates an SQL dump of UAM specific tables and configuration settings
3305 *
3306 * @returns  : Boolean to manage appropriate message display
3307 *
3308 */
3309function UAM_dump($download)
3310{
3311  global $conf;
3312
3313  $plugin =  PluginInfos(UAM_PATH);
3314  $version = $plugin['version'];
3315
3316  // Initial backup folder creation and file initialisation
3317  // ------------------------------------------------------
3318  if (!is_dir(UAM_PATH.'/include/backup'))
3319    mkdir(UAM_PATH.'/include/backup');
3320
3321  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3322
3323  $fp = fopen($Backup_File, 'w');
3324
3325  // Writing plugin version
3326  $insertions = "-- ".$version." --\n\n";
3327  fwrite($fp, $insertions);
3328
3329  // Saving UAM specific tables
3330  // --------------------------
3331  $ListTables = array(USER_CONFIRM_MAIL_TABLE, USER_LASTVISIT_TABLE);
3332  $j=0;
3333
3334  while($j < count($ListTables))
3335  {
3336    $sql = 'SHOW CREATE TABLE '.$ListTables[$j];
3337    $res = pwg_query($sql);
3338
3339    if ($res)
3340    {
3341      $insertions = "-- -------------------------------------------------------\n";
3342      $insertions .= "-- Create ".$ListTables[$j]." table\n";
3343      $insertions .= "-- ------------------------------------------------------\n\n";
3344
3345      $insertions .= "DROP TABLE IF EXISTS ".$ListTables[$j].";\n\n";
3346
3347      $array = pwg_db_fetch_row($res);
3348      $array[1] .= ";\n\n";
3349      $insertions .= $array[1];
3350
3351      $req_table = pwg_query('DESCRIBE '.$ListTables[$j].';') or die(my_error());
3352      $nb_fields = pwg_db_num_rows($req_table);
3353      $req_table2 = pwg_query('SELECT * FROM '.$ListTables[$j]) or die(my_error());
3354
3355      while ($line = pwg_db_fetch_row($req_table2))
3356      {
3357        $insertions .= 'INSERT INTO '.$ListTables[$j].' VALUES (';
3358        for ($i=0; $i<$nb_fields; $i++)
3359        {
3360          $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3361        }
3362        $insertions = substr($insertions, 0, -2);
3363        $insertions .= ");\n";
3364      }
3365      $insertions .= "\n\n";
3366    }
3367
3368    fwrite($fp, $insertions);   
3369    $j++;
3370  }
3371
3372  // Saving UAM configuration
3373  // ------------------------
3374  $insertions = "-- -------------------------------------------------------\n";
3375  $insertions .= "-- Insert UAM configuration in ".CONFIG_TABLE."\n";
3376  $insertions .= "-- ------------------------------------------------------\n\n";
3377
3378  fwrite($fp, $insertions);
3379
3380  $pattern = "UserAdvManager%";
3381  $req_table = pwg_query('SELECT * FROM '.CONFIG_TABLE.' WHERE param LIKE "'.$pattern.'";') or die(my_error());
3382  $nb_fields = pwg_db_num_rows($req_table);
3383  $nb_fields = $nb_fields - 1;  // Fix the number of fields because pwg_db_num_rows() returns a bad number
3384
3385  while ($line = pwg_db_fetch_row($req_table))
3386  {
3387    $insertions = 'INSERT INTO '.CONFIG_TABLE.' VALUES (';
3388    for ($i=0; $i<$nb_fields; $i++)
3389    {
3390      $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3391    }
3392    $insertions = substr($insertions, 0, -2);
3393    $insertions .= ");\n";
3394
3395    fwrite($fp, $insertions);
3396  }
3397
3398  fclose($fp);
3399
3400  // Download generated dump file
3401  // ----------------------------
3402  if ($download == 'true')
3403  {
3404    if (@filesize($Backup_File))
3405    {
3406      $http_headers = array(
3407        'Content-Length: '.@filesize($Backup_File),
3408        'Content-Type: text/x-sql',
3409        'Content-Disposition: attachment; filename="UAM_dbbackup.sql";',
3410        'Content-Transfer-Encoding: binary',
3411        );
3412
3413      foreach ($http_headers as $header)
3414      {
3415        header($header);
3416      }
3417
3418      @readfile($Backup_File);
3419      exit();
3420    }
3421  }
3422
3423  return true;
3424}
3425
3426
3427/**
3428 * UAM_Restore_backup_file
3429 * Restore backup database file
3430 *
3431 * @returns : Boolean
3432 */
3433function UAM_Restore_backup_file() 
3434{
3435  global $prefixeTable, $dblayer, $conf;
3436
3437  define('DEFAULT_PREFIX_TABLE', 'piwigo_');
3438
3439  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3440
3441  // Cleanup database before restoring
3442  // ---------------------------------
3443
3444  // Delete UserAdvManager global config in #_config table
3445  $q = '
3446DELETE FROM '.CONFIG_TABLE.'
3447WHERE param="UserAdvManager"
3448;';
3449
3450  pwg_query($q);
3451
3452  // Delete UserAdvManager_ConfirmMail global config in #_config table
3453  $q = '
3454DELETE FROM '.CONFIG_TABLE.'
3455WHERE param="UserAdvManager_ConfirmMail"
3456;';
3457
3458  pwg_query($q);
3459
3460  // Delete UserAdvManager_Redir config in #_config table
3461  $q = '
3462DELETE FROM '.CONFIG_TABLE.'
3463WHERE param="UserAdvManager_Redir"
3464;';
3465
3466  pwg_query($q);
3467
3468  // Delete UserAdvManager_Version config in #_config table
3469  $q = '
3470DELETE FROM '.CONFIG_TABLE.'
3471WHERE param="UserAdvManager_Version"
3472;';
3473
3474  pwg_query($q);
3475
3476  // Restore sql backup file - DROP TABLE queries are executed
3477  // ---------------------------------------------------------
3478  UAM_execute_sqlfile(
3479    $Backup_File,
3480    DEFAULT_PREFIX_TABLE,
3481    $prefixeTable,
3482    $dblayer
3483  );
3484}
3485
3486
3487/**
3488 * loads an sql file and executes all queries / Based on Piwigo's original install file
3489 *
3490 * Before executing a query, $replaced is... replaced by $replacing. This is
3491 * useful when the SQL file contains generic words.
3492 *
3493 * @param string filepath
3494 * @param string replaced
3495 * @param string replacing
3496 * @return void
3497 */
3498function UAM_execute_sqlfile($filepath, $replaced, $replacing, $dblayer)
3499{
3500  $sql_lines = file($filepath);
3501  $query = '';
3502  foreach ($sql_lines as $sql_line)
3503  {
3504    $sql_line = trim($sql_line);
3505    if (preg_match('/(^--|^$)/', $sql_line))
3506    {
3507      continue;
3508    }
3509
3510    $query.= ' '.$sql_line;
3511
3512    // if we reached the end of query, we execute it and reinitialize the
3513    // variable "query"
3514    if (preg_match('/;$/', $sql_line))
3515    {
3516      $query = trim($query);
3517      $query = str_replace($replaced, $replacing, $query);
3518      if ('mysql' == $dblayer)
3519      {
3520        if (preg_match('/^(CREATE TABLE .*)[\s]*;[\s]*/im', $query, $matches))
3521        {
3522          $query = $matches[1].' DEFAULT CHARACTER SET utf8'.';';
3523        }
3524      }
3525      pwg_query($query);
3526      $query = '';
3527    }
3528  }
3529}
3530
3531
3532/**
3533 * Delete obsolete files on plugin upgrade
3534 * Obsolete files are listed in file obsolete.list
3535 *
3536 */
3537function clean_obsolete_files()
3538{
3539  if (file_exists(UAM_PATH.'obsolete.list')
3540    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
3541    and !empty($old_files))
3542  {
3543    array_push($old_files, 'obsolete.list');
3544    foreach($old_files as $old_file)
3545    {
3546      $path = UAM_PATH.$old_file;
3547      if (is_file($path))
3548      {
3549        @unlink($path);
3550      }
3551      elseif (is_dir($path))
3552      {
3553        @rmdir($path);
3554      }
3555    }
3556  }
3557}
3558
3559
3560/**
3561 * Function called from maintain.inc.php - to check if database upgrade is needed
3562 *
3563 * @param : table name
3564 *
3565 * @return : boolean
3566 *
3567 */
3568function table_exist($table)
3569{
3570  $query = 'DESC '.$table.';';
3571  return (bool)($res=pwg_query($query));
3572}
3573
3574
3575/**
3576 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
3577 *
3578 * @param : plugin directory
3579 *
3580 * @return : plugin's version and name
3581 *
3582 */
3583function PluginInfos($dir)
3584{
3585  $path = $dir;
3586
3587  $plg_data = implode( '', file($path.'main.inc.php') );
3588  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
3589  {
3590    $plugin['name'] = trim( $val[1] );
3591  }
3592  if (preg_match("|Version: (.*)|", $plg_data, $val))
3593  {
3594    $plugin['version'] = trim($val[1]);
3595  }
3596  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
3597  {
3598    $plugin['uri'] = trim($val[1]);
3599  }
3600  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
3601  {
3602    $plugin['description'] = trim($desc);
3603  }
3604  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
3605  {
3606    $plugin['description'] = trim($val[1]);
3607  }
3608  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
3609  {
3610    $plugin['author'] = trim($val[1]);
3611  }
3612  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
3613  {
3614    $plugin['author uri'] = trim($val[1]);
3615  }
3616  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
3617  {
3618    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
3619    if (is_numeric($extension)) $plugin['extension'] = $extension;
3620  }
3621// IMPORTANT SECURITY !
3622// --------------------
3623  $plugin = array_map('htmlspecialchars', $plugin);
3624
3625  return $plugin ;
3626}
3627
3628
3629/**
3630 * Useful for debugging - 4 vars can be set
3631 * Output result to log.txt file
3632 *
3633 */
3634function UAMLog($var1, $var2, $var3, $var4)
3635{
3636   $fo=fopen (UAM_PATH.'log.txt','a') ;
3637   fwrite($fo,"======================\n") ;
3638   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
3639   fwrite($fo,$var1 ."\r\n") ;
3640   fwrite($fo,$var2 ."\r\n") ;
3641   fwrite($fo,$var3 ."\r\n") ;
3642   fwrite($fo,$var4 ."\r\n") ;
3643   fclose($fo) ;
3644}
3645
3646?>
Note: See TracBrowser for help on using the repository browser.