source: extensions/UserAdvManager/branches/2.50/include/functions.inc.php @ 24213

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

r24212 merged from trunk to branch 2.50Next version is 2.5.14:
Evolution 2951 fixed - Add an option to add the gallery URL at the end of emails sent by UAM
Update ru_RU, thanks to : Konve
Update lv_LV, thanks to : agrisans
Add pt_PT, thanks to : ANO

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