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

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

Bug 2877 - Disabling Confirmation of registration main option disables child options (child options remain configured and shown but no force or effect)

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