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

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

Bug 2620 fixed - Display of ConfirmMail, rejected and del_account pages have been improved
Bug 2621 fixed - Display of ConfirmMail, rejected and del_account pages have been improved for IE8 and IE9 render
Bug 2631 fixed - Piwigo 2.4 compliance : $confgallery_url replaced by get_gallery_home_url() for [myurl] tag

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