source: extensions/UserAdvManager/branches/2.41/include/functions.inc.php @ 19235

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

Merge r19234 from trunk to branch 2.41 :
Bug 2765 fixed - Code cleanup
Bug 2788 fixed : Warning message on email exclusion no more remains if misconfiguration is fixed. But it's still necessary to refresh the current page once for the warning message to disappear.
Bug 2796 fixed - Use of php date() function instead od MySql NOW() - Usefull if MySql server is not set at the same date-time as Apache/Php server
Update da_DK, thanks to : Kaare
Update it_IT, thanks to : virgigiole
Update lv_LV, thanks to : agrisans

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