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

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

bug 2788 re-fixed (mistake in previous commit)

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