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

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

Next version is 2.41.4 ready for publication

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