source: extensions/UserAdvManager/branches/2.30/include/functions.inc.php @ 27153

Last change on this file since 27153 was 17806, checked in by Eric, 12 years ago

r17804 merged from trunk to branch 2.30

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