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

Last change on this file since 18235 was 18235, checked in by flop25, 12 years ago

big mistake from me corrected
use of !empty()

  • Property svn:eol-style set to LF
File size: 97.3 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 informations
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(UAM_PATH.'USR_del_account.php');
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 informations
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
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}
951/**
952 * Triggered on init
953 *
954 * Check the key and display a message
955 */
956function UAM_ConfirmMail()
957{
958
959  if (isset($_GET['key']) and isset($_GET['userid']))
960  {
961 
962    global $user, $lang, $conf, $page;
963   
964    $key = $_GET['key'];
965    $userid = $_GET['userid'];
966   
967    $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
968    $conf_UAM = unserialize($conf['UserAdvManager']);
969 
970    $query = '
971  SELECT '.USERS_TABLE.'.username
972  FROM '.USERS_TABLE.'
973  WHERE ('.USERS_TABLE.'.id ='.$userid.')
974  ;';
975    $result = pwg_db_fetch_assoc(pwg_query($query));
976 
977    if (VerifyConfirmMail($key))
978    {
979      if (isset($conf_UAM[1]) and $conf_UAM[1] == 'local')
980      {
981        validation_mail($userid);
982      }
983  // We have to get the user's language in database
984  // ----------------------------------------------
985      $query = '
986  SELECT language
987  FROM '.USER_INFOS_TABLE.'
988  WHERE '.USER_INFOS_TABLE.'.user_id ='.$userid.'
989  ;';
990      $data = pwg_db_fetch_assoc(pwg_query($query));
991 
992  // Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
993  // -------------------------------------------------------------------------------------------------------------------------------
994      if (empty($data))
995      {
996  // And switch gallery to this language before using personalized and multilangual contents
997  // ---------------------------------------------------------------------------------------
998        $language = pwg_get_session_var('lang_switch', $user['language']);
999        switch_lang_to($language);
1000      }
1001      else
1002      {
1003  // And switch gallery to this language before using personalized and multilangual contents
1004  // ---------------------------------------------------------------------------------------
1005        switch_lang_to($data['language']);
1006        load_language('plugin.lang', UAM_PATH);
1007      }
1008 
1009      if (isset($conf_UAM_ConfirmMail[5]) and $conf_UAM_ConfirmMail[5] <> '')
1010      {
1011        // Management of Extension flags ([username], [mygallery], [myurl])
1012        // ----------------------------------------------------------------
1013        $patterns[] = '#\[username\]#i';
1014        $replacements[] = $result['username'];
1015        $patterns[] = '#\[mygallery\]#i';
1016        $replacements[] = $conf['gallery_title'];
1017        $patterns[] = '#\[myurl\]#i';
1018        $replacements[] = get_gallery_home_url();
1019 
1020        if (function_exists('get_user_language_desc'))
1021        {
1022          $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[5]));
1023        }
1024        else
1025        {
1026          $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[5]));
1027        }
1028        $page['infos'][]=$custom_text;
1029        //print_r($custom_text);
1030      }
1031      //log_user($userid, true);
1032    } 
1033    else
1034    {
1035      if (isset($conf_UAM_ConfirmMail[6]) and $conf_UAM_ConfirmMail[6] <> '')
1036      {
1037        // Management of Extension flags ([username], [mygallery], [myurl])
1038        // ----------------------------------------------------------------
1039        $patterns[] = '#\[username\]#i';
1040        $replacements[] = $result['username'];
1041        $patterns[] = '#\[mygallery\]#i';
1042        $replacements[] = $conf['gallery_title'];
1043        $patterns[] = '#\[myurl\]#i';
1044        $replacements[] = get_gallery_home_url();
1045     
1046        if (function_exists('get_user_language_desc'))
1047        {
1048          $custom_text = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[6]));
1049        }
1050        else
1051        {
1052          $custom_text = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[6]));
1053        }
1054       
1055        $page['errors'][]=$custom_text;
1056      }
1057    }
1058  }
1059}
1060/**
1061 * Triggered on render_lost_password_mail_content
1062 *
1063 * Adds a customized text in lost password email content
1064 * Added text is inserted before users login name and new password
1065 *
1066 * @param : Standard Piwigo email content
1067 *
1068 * @return : Customized content added to standard content
1069 *
1070 */
1071function UAM_lost_password_mail_content($infos)
1072{
1073  global $conf;
1074 
1075  load_language('plugin.lang', UAM_PATH);
1076 
1077  $conf_UAM = unserialize($conf['UserAdvManager']);
1078 
1079  if (isset($conf_UAM[28]) and $conf_UAM[28] == 'true')
1080  {
1081    // Management of Extension flags ([mygallery], [myurl])
1082    $patterns[] = '#\[mygallery\]#i';
1083    $replacements[] = $conf['gallery_title'];
1084    $patterns[] = '#\[myurl\]#i';
1085    $replacements[] = get_gallery_home_url();
1086   
1087    $infos = preg_replace($patterns, $replacements, $conf_UAM[29])."\n"."\n".$infos;
1088  }
1089  return $infos;
1090}
1091
1092
1093/**
1094 * Function called from main.inc.php to send validation email
1095 *
1096 * @param : Type of email, user id, username, email address, confirmation (optional)
1097 *
1098 */
1099function SendMail2User($typemail, $id, $username, $password, $email, $confirm)
1100{
1101  global $conf;
1102
1103  $conf_UAM = unserialize($conf['UserAdvManager']);
1104
1105                include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1106
1107                $infos1_perso = "";
1108  $infos2_perso = "";
1109  $subject = "";
1110
1111// We have to get the user's language in database
1112// ----------------------------------------------
1113  $query ='
1114SELECT user_id, language
1115FROM '.USER_INFOS_TABLE.'
1116WHERE user_id = '.$id.'
1117;';
1118  $data = pwg_db_fetch_assoc(pwg_query($query));
1119
1120// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1121// -------------------------------------------------------------------------------------------------------------------------------
1122  if (empty($data))
1123  {
1124// And switch gallery to this language before using personalized and multilangual contents
1125// ---------------------------------------------------------------------------------------
1126    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1127    switch_lang_to($language);
1128  }
1129  else
1130  {
1131// And switch gallery to this language before using personalized and multilangual contents
1132// ---------------------------------------------------------------------------------------
1133    //$language = $data['language']; // Usefull for debugging
1134    switch_lang_to($data['language']);
1135    load_language('plugin.lang', UAM_PATH);
1136  }
1137
1138  switch($typemail)
1139  {
1140    case 1: // Confirmation email on user registration - Without information email (already managed by Piwigo)
1141      if (isset($conf_UAM[41]) and $conf_UAM[41] <> '')
1142      {
1143        // Management of Extension flags ([username], [mygallery])
1144        // -------------------------------------------------------
1145        $patterns[] = '#\[username\]#i';
1146        $replacements[] = $username;
1147        $patterns[] = '#\[mygallery\]#i';
1148        $replacements[] = $conf['gallery_title'];
1149   
1150        if (function_exists('get_user_language_desc'))
1151        {
1152          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[41]))."\n\n";
1153        }
1154        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[41]))."\n\n"; 
1155      }
1156
1157      break;
1158     
1159    case 2: // Confirmation email on user profile update - With information email if modification done in user profile
1160      if (isset($conf_UAM[41]) and $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      $password = $password <> '' ? $password : l10n('UAM_empty_pwd');
1177
1178      if (isset($conf_UAM[8]) and $conf_UAM[8] <> '')
1179      {
1180        // Management of Extension flags ([username], [mygallery], [myurl])
1181        // ----------------------------------------------------------------
1182        $patterns[] = '#\[username\]#i';
1183        $replacements[] = $username;
1184        $patterns[] = '#\[mygallery\]#i';
1185        $replacements[] = $conf['gallery_title'];
1186        $patterns[] = '#\[myurl\]#i';
1187        $replacements[] = get_gallery_home_url();
1188   
1189        if (function_exists('get_user_language_desc'))
1190        {
1191          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[8]))."\n\n";
1192        }
1193        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM[8]))."\n\n"; 
1194      }
1195
1196      if (isset($conf_UAM[0]) and $conf_UAM[0] == 'true')
1197      {
1198        if (isset($conf_UAM[34]) and $conf_UAM[34] == 'true') // Allow display of clear password in email
1199        {
1200          $infos1 = array(
1201            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1202            get_l10n_args('UAM_User: %s', stripslashes($username)),
1203            get_l10n_args('UAM_Password: %s', $password),
1204            get_l10n_args('Email: %s', $email),
1205            get_l10n_args('', ''),
1206          );
1207        }
1208        else // Do not allow display of clear password in email
1209        {
1210          $infos1 = array(
1211            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1212            get_l10n_args('UAM_User: %s', stripslashes($username)),
1213            get_l10n_args('Email: %s', $email),
1214            get_l10n_args('', ''),
1215          );
1216        }
1217      }
1218
1219      break;
1220       
1221    case 3: // Only information email send to user if checked
1222      if (isset($conf_UAM[43]) and $conf_UAM[43] <> '')
1223      {
1224        // Management of Extension flags ([username], [mygallery])
1225        // -------------------------------------------------------
1226        $patterns[] = '#\[username\]#i';
1227        $replacements[] = $username;
1228        $patterns[] = '#\[mygallery\]#i';
1229        $replacements[] = $conf['gallery_title'];
1230   
1231        if (function_exists('get_user_language_desc'))
1232        {
1233          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[43]))."\n\n";
1234        }
1235        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[43]))."\n\n"; 
1236      }
1237
1238      $password = $password <> '' ? $password : l10n('UAM_no_update_pwd');
1239
1240      if (isset($conf_UAM[8]) and $conf_UAM[8] <> '')
1241      {
1242        // Management of Extension flags ([username], [mygallery], [myurl])
1243        // ----------------------------------------------------------------
1244        $patterns[] = '#\[username\]#i';
1245        $replacements[] = $username;
1246        $patterns[] = '#\[mygallery\]#i';
1247        $replacements[] = $conf['gallery_title'];
1248        $patterns[] = '#\[myurl\]#i';
1249        $replacements[] = get_gallery_home_url();
1250   
1251        if (function_exists('get_user_language_desc'))
1252        {
1253          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[8]))."\n\n";
1254        }
1255        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM[8]))."\n\n"; 
1256      }
1257
1258      if (isset($conf_UAM[0]) and $conf_UAM[0] == 'true')
1259      {
1260        if (isset($conf_UAM[34]) and $conf_UAM[34] == 'true') // Allow display of clear password in email
1261        {
1262          $infos1 = array(
1263            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1264            get_l10n_args('UAM_User: %s', stripslashes($username)),
1265            get_l10n_args('UAM_Password: %s', $password),
1266            get_l10n_args('Email: %s', $email),
1267            get_l10n_args('', ''),
1268          );
1269        }
1270        else // Do not allow display of clear password in email
1271        {
1272          $infos1 = array(
1273            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1274            get_l10n_args('UAM_User: %s', stripslashes($username)),
1275            get_l10n_args('Email: %s', $email),
1276            get_l10n_args('', ''),
1277          );
1278        }
1279      }
1280
1281      break;
1282  }
1283
1284  if (isset($conf_UAM[1]) and ($conf_UAM[1] == 'true' or $conf_UAM[1] == 'local')  and $confirm) // Add confirmation link ?
1285  {
1286    $infos2 = array
1287    (
1288      get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
1289      get_l10n_args('', ''),
1290    );
1291
1292    if (isset($conf_UAM[9]) and $conf_UAM[9] <> '') // Add personal text in confirmation email ?
1293    {
1294      // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1295      // -------------------------------------------------------------------------
1296      $patterns[] = '#\[username\]#i';
1297      $replacements[] = $username;
1298      $patterns[] = '#\[mygallery\]#i';
1299      $replacements[] = $conf['gallery_title'];
1300      $patterns[] = '#\[myurl\]#i';
1301      $replacements[] = get_gallery_home_url();
1302     
1303      if (isset($conf_UAM_ConfirmMail[0]) and $conf_UAM_ConfirmMail[0] == 'true') // [Kdays] replacement only if related option is active
1304      {
1305        $patterns[] = '#\[Kdays\]#i';
1306        $replacements[] = $conf_UAM_ConfirmMail[1];
1307      }
1308     
1309      if (function_exists('get_user_language_desc'))
1310      {
1311        $infos2_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[9]))."\n\n";
1312      }
1313      else $infos2_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM[9]))."\n\n";
1314    }
1315  }
1316
1317// Sending the email with subject and contents
1318// -------------------------------------------
1319                if (isset($conf_UAM[1]) and $conf_UAM[1] == 'local')
1320                {
1321                switch_lang_to(get_default_language());
1322               
1323                load_language('plugin.lang', UAM_PATH);
1324                $subject = get_l10n_args('UAM_Subject admin validation for %s',$username);
1325
1326                  $content = array(
1327                get_l10n_args('UAM_Manual_validation_needed_for %s', stripslashes($username)),
1328    get_l10n_args('', ''),
1329    get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
1330    );
1331
1332    UAM_mail_notification_admins($subject, $content);
1333                }
1334                else
1335                {
1336                pwg_mail($email, array(
1337                'subject' => $subject,
1338                'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1339                ));
1340                }
1341// Switching back to default language
1342// ----------------------------------
1343switch_lang_back();
1344}
1345
1346
1347/**
1348 * Function called from SendMail2User in functions.inc.php to notify admins on user registration validation with validation key
1349 *
1350 * @param:
1351 *   - keyargs_subject: mail subject on l10n_args format
1352 *   - keyargs_content: mail content on l10n_args format
1353 *
1354 * @return boolean (Ok or not)
1355 */
1356function UAM_mail_notification_admins($keyargs_subject, $keyargs_content)
1357{
1358  global $conf, $user;
1359 
1360  // Check arguments
1361  if (empty($keyargs_subject) or empty($keyargs_content))
1362  {
1363    return false;
1364  }
1365
1366  $return = true;
1367
1368  $admins = array();
1369
1370  $query = '
1371SELECT
1372    u.'.$conf['user_fields']['username'].' AS username,
1373    u.'.$conf['user_fields']['email'].' AS mail_address
1374  FROM '.USERS_TABLE.' AS u
1375    JOIN '.USER_INFOS_TABLE.' AS i ON i.user_id =  u.'.$conf['user_fields']['id'].'
1376  WHERE i.status in (\'webmaster\',  \'admin\')
1377    AND '.$conf['user_fields']['email'].' IS NOT NULL
1378    AND i.user_id <> '.$user['id'].'
1379  ORDER BY username
1380;';
1381
1382  $datas = pwg_query($query);
1383  if (!empty($datas))
1384  {
1385    while ($admin = pwg_db_fetch_assoc($datas))
1386    {
1387      if (!empty($admin['mail_address']))
1388      {
1389        array_push($admins, format_email($admin['username'], $admin['mail_address']));
1390      }
1391    }
1392  }
1393
1394  if (count($admins) > 0)
1395  {
1396    $content = l10n_args($keyargs_content)."\n";
1397
1398    $return = pwg_mail(
1399      implode(', ', $admins),
1400      array(
1401        'subject' => '['.$conf['gallery_title'].'] '.l10n_args($keyargs_subject),
1402        'content' => $content,
1403        'content_format' => 'text/plain',
1404        'email_format' => 'text/plain',
1405        )
1406      );
1407  }
1408
1409  return $return;
1410}
1411
1412
1413/**
1414 * Function called from UAM_admin.php to resend validation email with or without new validation key
1415 *
1416 * @param : Type of email, user id, username, email address, confirmation (optional)
1417 *
1418 */
1419function ResendMail2User($typemail, $user_id, $username, $email, $confirm)
1420{
1421  global $conf;
1422 
1423  $subject = "";
1424
1425  $conf_UAM = unserialize($conf['UserAdvManager']);
1426
1427  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1428 
1429                include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1430 
1431// We have to get the user's language in database
1432// ----------------------------------------------
1433  $query ='
1434SELECT user_id, language
1435FROM '.USER_INFOS_TABLE.'
1436WHERE user_id = '.$user_id.'
1437;';
1438  $data = pwg_db_fetch_assoc(pwg_query($query));
1439  $language = $data['language'];
1440 
1441// And switch gallery to this language before using personalized and multilangual contents
1442// ---------------------------------------------------------------------------------------
1443  switch_lang_to($data['language']);
1444   
1445  load_language('plugin.lang', UAM_PATH);
1446
1447  switch($typemail)
1448  {
1449    case 1: //Generating email content for remind with a new key
1450      if (isset($conf_UAM[42]) and $conf_UAM[42] <> '')
1451      {
1452        // Management of Extension flags ([username], [mygallery])
1453        // -------------------------------------------------------
1454        $patterns[] = '#\[username\]#i';
1455        $replacements[] = $username;
1456        $patterns[] = '#\[mygallery\]#i';
1457        $replacements[] = $conf['gallery_title'];
1458   
1459        if (function_exists('get_user_language_desc'))
1460        {
1461          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[42]))."\n\n";
1462        }
1463        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[42]))."\n\n"; 
1464      }
1465     
1466      if (isset($conf_UAM_ConfirmMail[2]) and $conf_UAM_ConfirmMail[2] <> '' and isset($conf_UAM_ConfirmMail[3]) and $conf_UAM_ConfirmMail[3] == 'true' and $confirm)
1467      {
1468                // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1469        // -------------------------------------------------------------------------
1470        $patterns[] = '#\[username\]#i';
1471        $replacements[] = $username;
1472        $patterns[] = '#\[mygallery\]#i';
1473        $replacements[] = $conf['gallery_title'];
1474        $patterns[] = '#\[myurl\]#i';
1475        $replacements[] = get_gallery_home_url();
1476
1477        if (isset($conf_UAM_ConfirmMail[0]) and $conf_UAM_ConfirmMail[0] == 'true') // [Kdays] replacement only if related option is active
1478        {
1479          $patterns[] = '#\[Kdays\]#i';
1480          $replacements[] = $conf_UAM_ConfirmMail[1];
1481        }
1482
1483        if (function_exists('get_user_language_desc'))
1484        {
1485          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[2]))."\n\n";
1486        }
1487                                else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[2]))."\n\n";
1488
1489        $infos2 = array
1490        (
1491          get_l10n_args('UAM_Link: %s', ResetConfirmMail($user_id)),
1492          get_l10n_args('', ''),
1493        );       
1494                                                }
1495
1496// Set reminder true
1497// -----------------     
1498      $query = '
1499UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1500SET reminder = "true"
1501WHERE user_id = '.$user_id.'
1502;';
1503      pwg_query($query);
1504     
1505                                break;
1506     
1507    case 2: //Generating email content for remind without a new key
1508      if (isset($conf_UAM[42]) and $conf_UAM[42] <> '')
1509      {
1510        // Management of Extension flags ([username], [mygallery])
1511        // -------------------------------------------------------
1512        $patterns[] = '#\[username\]#i';
1513        $replacements[] = $username;
1514        $patterns[] = '#\[mygallery\]#i';
1515        $replacements[] = $conf['gallery_title'];
1516   
1517        if (function_exists('get_user_language_desc'))
1518        {
1519          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[42]))."\n\n";
1520        }
1521        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[42]))."\n\n"; 
1522      }
1523     
1524      if (isset($conf_UAM_ConfirmMail[4]) and $conf_UAM_ConfirmMail[4] <> '' and isset($conf_UAM_ConfirmMail[3]) and $conf_UAM_ConfirmMail[3] == 'true' and !$confirm)
1525      {
1526        // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1527        // -------------------------------------------------------------------------
1528        $patterns[] = '#\[username\]#i';
1529        $replacements[] = $username;
1530        $patterns[] = '#\[mygallery\]#i';
1531        $replacements[] = $conf['gallery_title'];
1532        $patterns[] = '#\[myurl\]#i';
1533        $replacements[] = get_gallery_home_url();
1534
1535        if (isset($conf_UAM_ConfirmMail[0]) and $conf_UAM_ConfirmMail[0] == 'true') // [Kdays] replacement only if related option is active
1536        {
1537          $patterns[] = '#\[Kdays\]#i';
1538          $replacements[] = $conf_UAM_ConfirmMail[1];
1539        }
1540       
1541        if (function_exists('get_user_language_desc'))
1542        {
1543          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[4]))."\n\n";
1544        }
1545        else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail[4]))."\n\n";
1546      }
1547     
1548// Set reminder true
1549// -----------------
1550      $query = '
1551UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1552SET reminder = "true"
1553WHERE user_id = '.$user_id.'
1554;';
1555      pwg_query($query);
1556     
1557    break;
1558        }
1559 
1560  pwg_mail($email, array(
1561    'subject' => $subject,
1562    'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1563  ));
1564
1565                // Switching back to default language
1566                // ----------------------------------
1567                switch_lang_back();
1568}
1569
1570
1571/**
1572 * Function called from UAM_admin.php to send a reminder mail for ghost users
1573 *
1574 * @param : User id, username, email address
1575 *
1576 */
1577function ghostreminder($user_id, $username, $email)
1578{
1579  global $conf;
1580
1581  $conf_UAM = unserialize($conf['UserAdvManager']);
1582  $subject = "";
1583 
1584                include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1585
1586// We have to get the user's language in database
1587// ----------------------------------------------
1588  $query ='
1589SELECT user_id, language
1590FROM '.USER_INFOS_TABLE.'
1591WHERE user_id = '.$user_id.'
1592;';
1593  $data = pwg_db_fetch_assoc(pwg_query($query));
1594  $language = $data['language'];
1595
1596// And switch gallery to this language before using personalized and multilangual contents
1597// ---------------------------------------------------------------------------------------
1598  switch_lang_to($data['language']);
1599   
1600  load_language('plugin.lang', UAM_PATH);
1601
1602  if (isset($conf_UAM[45]) and $conf_UAM[45] <> '')
1603  {
1604    // Management of Extension flags ([username], [mygallery])
1605    // -------------------------------------------------------
1606    $patterns[] = '#\[username\]#i';
1607    $replacements[] = $username;
1608    $patterns[] = '#\[mygallery\]#i';
1609    $replacements[] = $conf['gallery_title'];
1610
1611    if (function_exists('get_user_language_desc'))
1612    {
1613      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[45]))."\n\n";
1614    }
1615    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[45]))."\n\n"; 
1616  }
1617
1618  if (isset($conf_UAM[17]) and $conf_UAM[17] <> '' and isset($conf_UAM[15]) and $conf_UAM[15] == 'true')
1619  {
1620    // Management of Extension flags ([username], [mygallery], [myurl], [days])
1621    // ------------------------------------------------------------------------
1622    $patterns[] = '#\[username\]#i';
1623    $replacements[] = $username;
1624    $patterns[] = '#\[mygallery\]#i';
1625    $replacements[] = $conf['gallery_title'];
1626    $patterns[] = '#\[myurl\]#i';
1627    $replacements[] = get_gallery_home_url();
1628    $patterns[] = '#\[days\]#i';
1629    $replacements[] = $conf_UAM[16];
1630
1631    if (function_exists('get_user_language_desc'))
1632    {
1633      $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[17]))."\n\n";
1634    }
1635    else
1636    {
1637      $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM[17]))."\n\n";
1638    }
1639
1640    resetlastvisit($user_id);
1641  }
1642
1643  pwg_mail($email, array(
1644    'subject' => $subject,
1645    'content' => $infos1.get_absolute_root_url(),
1646  ));
1647
1648                // Switching back to default language
1649                // ----------------------------------
1650                switch_lang_back();
1651}
1652
1653
1654/**
1655 * Function called from functions.inc.php to send notification email when user have been downgraded
1656 *
1657 * @param : user id, username, email address
1658 *
1659 */
1660function demotion_mail($id, $username, $email)
1661{
1662  global $conf;
1663
1664  $conf_UAM = unserialize($conf['UserAdvManager']);
1665 
1666                include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1667 
1668                $custom_txt = "";
1669                $subject = "";
1670
1671// We have to get the user's language in database
1672// ----------------------------------------------
1673  $query = '
1674SELECT user_id, language
1675FROM '.USER_INFOS_TABLE.'
1676WHERE user_id = '.$id.'
1677;';
1678  $data = pwg_db_fetch_assoc(pwg_query($query));
1679
1680// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1681// -------------------------------------------------------------------------------------------------------------------------------
1682  if (empty($data))
1683  {
1684// And switch gallery to this language before using personalized and multilangual contents
1685// ---------------------------------------------------------------------------------------
1686    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1687    switch_lang_to($language);
1688  }
1689  else
1690  {
1691// And switch gallery to this language before using personalized and multilangual contents
1692// ---------------------------------------------------------------------------------------
1693    $language = $data['language']; // Usefull for debugging
1694    switch_lang_to($data['language']);
1695    load_language('plugin.lang', UAM_PATH);
1696  }
1697
1698  if (isset($conf_UAM[44]) and $conf_UAM[44] <> '')
1699  {
1700    // Management of Extension flags ([username], [mygallery])
1701    // -------------------------------------------------------
1702    $patterns[] = '#\[username\]#i';
1703    $replacements[] = $username;
1704    $patterns[] = '#\[mygallery\]#i';
1705    $replacements[] = $conf['gallery_title'];
1706
1707    if (function_exists('get_user_language_desc'))
1708    {
1709      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[44]))."\n\n";
1710    }
1711    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[44]))."\n\n"; 
1712  }
1713     
1714  if (isset($conf_UAM[24]) and $conf_UAM[24] <> '')
1715  {
1716    // Management of Extension flags ([username], [mygallery], [myurl])
1717    // ----------------------------------------------------------------
1718    $patterns[] = '#\[username\]#i';
1719    $replacements[] = stripslashes($username);
1720    $patterns[] = '#\[mygallery\]#i';
1721    $replacements[] = $conf['gallery_title'];
1722    $patterns[] = '#\[myurl\]#i';
1723    $replacements[] = get_gallery_home_url();
1724
1725    if (function_exists('get_user_language_desc'))
1726    {
1727      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[24]))."\n\n";
1728    }
1729    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM[24]))."\n\n"; 
1730  }
1731
1732  $infos1 = array(
1733    get_l10n_args('UAM_User: %s', stripslashes($username)),
1734    get_l10n_args('Email: %s', $email),
1735    get_l10n_args('', ''),
1736  );
1737
1738  $infos2 = array
1739  (
1740    get_l10n_args('UAM_Link: %s', ResetConfirmMail($id)),
1741    get_l10n_args('', ''),
1742  ); 
1743
1744  resetlastvisit($id);
1745
1746// Sending the email with subject and contents
1747// -------------------------------------------
1748  pwg_mail($email, array(
1749    'subject' => $subject,
1750    'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url(),
1751  ));
1752
1753                // Switching back to default language
1754                // ----------------------------------
1755                switch_lang_back();
1756}
1757
1758
1759/**
1760 * Function called from UAM_admin.php to send notification email when user registration have been manually validated by admin
1761 *
1762 * @param : user id
1763 *
1764 */
1765function validation_mail($id)
1766{
1767  global $conf;
1768
1769  $conf_UAM = unserialize($conf['UserAdvManager']);
1770 
1771                include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1772 
1773                $custom_txt = "";
1774  $subject = "";
1775
1776// We have to get the user's language in database
1777// ----------------------------------------------
1778  $query ='
1779SELECT user_id, language
1780FROM '.USER_INFOS_TABLE.'
1781WHERE user_id = '.$id.'
1782;';
1783  $data = pwg_db_fetch_assoc(pwg_query($query));
1784
1785// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1786// -------------------------------------------------------------------------------------------------------------------------------
1787  if (empty($data))
1788  {
1789// And switch gallery to this language before using personalized and multilangual contents
1790// ---------------------------------------------------------------------------------------
1791    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1792    switch_lang_to($language);
1793  }
1794  else
1795  {
1796// And switch gallery to this language before using personalized and multilangual contents
1797// ---------------------------------------------------------------------------------------
1798    $language = $data['language']; // Usefull for debugging
1799    switch_lang_to($data['language']);
1800    load_language('plugin.lang', UAM_PATH);
1801  }
1802
1803// Retreive users email and user name from id
1804// ------------------------------------------
1805  $query ='
1806SELECT id, username, mail_address
1807FROM '.USERS_TABLE.'
1808WHERE id = '.$id.'
1809;';
1810  $result = pwg_db_fetch_assoc(pwg_query($query));
1811
1812  if (isset($conf_UAM[46]) and $conf_UAM[46] <> '')
1813  {
1814    // Management of Extension flags ([username], [mygallery])
1815    // -------------------------------------------------------
1816    $patterns[] = '#\[username\]#i';
1817    $replacements[] = $result['username'];
1818    $patterns[] = '#\[mygallery\]#i';
1819    $replacements[] = $conf['gallery_title'];
1820
1821    if (function_exists('get_user_language_desc'))
1822    {
1823      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[46]))."\n\n";
1824    }
1825    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM[46]))."\n\n";
1826  }
1827     
1828  if (isset($conf_UAM[27]) and $conf_UAM[27] <> '')
1829  {
1830    // Management of Extension flags ([username], [mygallery], [myurl])
1831    // ----------------------------------------------------------------
1832    $patterns[] = '#\[username\]#i';
1833    $replacements[] = $result['username'];
1834    $patterns[] = '#\[mygallery\]#i';
1835    $replacements[] = $conf['gallery_title'];
1836    $patterns[] = '#\[myurl\]#i';
1837    $replacements[] = get_gallery_home_url();
1838    if (function_exists('get_user_language_desc'))
1839    {
1840      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM[27]))."\n\n";
1841    }
1842    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM[27]))."\n\n";
1843  }
1844
1845  $infos = array(
1846    get_l10n_args('UAM_User: %s', stripslashes($result['username'])),
1847    get_l10n_args('Email: %s', $result['mail_address']),
1848    get_l10n_args('', ''),
1849  );
1850
1851// Sending the email with subject and contents
1852// -------------------------------------------
1853  pwg_mail($result['mail_address'], array(
1854    'subject' => $subject,
1855    'content' => (l10n_args($infos)."\n\n".$custom_txt),
1856  ));
1857
1858                // Switching back to default language
1859                // ----------------------------------
1860                switch_lang_back();
1861}
1862
1863
1864/**
1865 * Function called from functions AddConfirmMail and ResetConfirmMail for validation key generation
1866 *
1867 * @return : validation key
1868 *
1869 */
1870function FindAvailableConfirmMailID()
1871{
1872  while (true)
1873  {
1874    $id = generate_key(16);
1875    $query = '
1876SELECT COUNT(*)
1877  FROM '.USER_CONFIRM_MAIL_TABLE.'
1878WHERE id = "'.$id.'"
1879;';
1880    list($count) = pwg_db_fetch_row(pwg_query($query));
1881
1882    if ($count == 0)
1883      return $id;
1884  }
1885}
1886
1887
1888/**
1889 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
1890 *
1891 * @param : User id, email address
1892 *
1893 * @return : Build validation key in URL
1894 *
1895 */
1896function AddConfirmMail($user_id, $email)
1897{
1898  global $conf;
1899
1900  $conf_UAM = unserialize($conf['UserAdvManager']);
1901  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1902
1903  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
1904 
1905  if (isset($Confirm_Mail_ID))
1906  {
1907    $query = '
1908SELECT status
1909  FROM '.USER_INFOS_TABLE.'
1910WHERE user_id = '.$user_id.'
1911;';
1912    list($status) = pwg_db_fetch_row(pwg_query($query));
1913   
1914    $query = '
1915INSERT INTO '.USER_CONFIRM_MAIL_TABLE.'
1916  (id, user_id, mail_address, status, date_check)
1917VALUES
1918  ("'.$Confirm_Mail_ID.'", '.$user_id.', "'.$email.'", "'.$status.'", null)
1919;';
1920    pwg_query($query);
1921
1922    // Delete user from all groups
1923    // ---------------------------
1924    $query = '
1925DELETE FROM '.USER_GROUP_TABLE.'
1926WHERE user_id = '.$user_id.'
1927  AND (
1928    group_id = '.$conf_UAM[2].'
1929  OR
1930    group_id = '.$conf_UAM[3].'
1931  )
1932;';
1933    pwg_query($query);
1934
1935    // Set user unvalidated status
1936    // ---------------------------
1937    if (!is_admin() and $conf_UAM[7] <> -1)
1938    {
1939      $query = '
1940UPDATE '.USER_INFOS_TABLE.'
1941SET status = "'.$conf_UAM[7].'"
1942WHERE user_id = '.$user_id.'
1943;';
1944      pwg_query($query);
1945    }
1946
1947    // Set user unvalidated group
1948    // --------------------------
1949    if (!is_admin() and $conf_UAM[2] <> -1)
1950    {
1951      $query = '
1952INSERT INTO '.USER_GROUP_TABLE.'
1953  (user_id, group_id)
1954VALUES
1955  ('.$user_id.', '.$conf_UAM[2].')
1956;';
1957      pwg_query($query);
1958    }
1959
1960    // Set user unvalidated privacy level
1961    // ----------------------------------
1962    if (!is_admin() and $conf_UAM[35] <> -1)
1963    {
1964      $query = '
1965UPDATE '.USER_INFOS_TABLE.'
1966SET level = "'.$conf_UAM[35].'"
1967WHERE user_id = '.$user_id.'
1968;';
1969      pwg_query($query);
1970    }
1971   
1972    // Set UAM_validated field to false in #_users table
1973    // -------------------------------------------------
1974    SetUnvalidated($user_id);
1975   
1976    if ( $conf['guest_access'] )
1977    {
1978      return( get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
1979    }
1980    else
1981    {
1982      return( get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
1983    }
1984  }
1985}
1986
1987
1988/**
1989 * Function called from UAM_Adduser() to set group/status/level to new users if manual validation is set
1990 *
1991 * @param : User id
1992 *
1993 *
1994 */
1995function SetPermission($user_id)
1996{
1997  global $conf;
1998 
1999  $conf_UAM = unserialize($conf['UserAdvManager']);
2000
2001// Groups cleanup
2002// --------------
2003  $query = '
2004DELETE FROM '.USER_GROUP_TABLE.'
2005WHERE user_id = '.$user_id.'
2006  AND (
2007    group_id = '.$conf_UAM[2].'
2008  OR
2009    group_id = '.$conf_UAM[3].'
2010  )
2011;';
2012  pwg_query($query);
2013
2014  if (!is_admin() and $conf_UAM[7] <> -1) // Set status
2015  {
2016    $query = '
2017UPDATE '.USER_INFOS_TABLE.'
2018SET status = "'.$conf_UAM[7].'"
2019WHERE user_id = '.$user_id.'
2020;';
2021    pwg_query($query);
2022  }
2023
2024  if (!is_admin() and $conf_UAM[2] <> -1) // Set group
2025  {
2026    $query = '
2027INSERT INTO '.USER_GROUP_TABLE.'
2028  (user_id, group_id)
2029VALUES
2030  ('.$user_id.', '.$conf_UAM[2].')
2031;';
2032    pwg_query($query);
2033  }
2034
2035  if (!is_admin() and $conf_UAM[35] <> -1) // Set privacy level
2036  {
2037    $query = '
2038INSERT INTO '.USER_INFOS_TABLE.'
2039  (user_id, level)
2040VALUES
2041  ('.$user_id.', "'.$conf_UAM[35].'")
2042;';
2043    pwg_query($query);
2044  }
2045}
2046
2047
2048/**
2049 * Function called from UAM_admin.php to reset validation key
2050 *
2051 * @param : User id
2052 *
2053 * @return : Build validation key in URL
2054 *
2055 */
2056function ResetConfirmMail($user_id)
2057{
2058  global $conf;
2059 
2060  $Confirm_Mail_ID = FindAvailableConfirmMailID();
2061
2062  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2063 
2064  if (isset($Confirm_Mail_ID))
2065  { 
2066    $query = '
2067UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2068SET id = "'.$Confirm_Mail_ID.'"
2069WHERE user_id = '.$user_id.'
2070;';
2071    pwg_query($query);
2072
2073    $query = '
2074UPDATE '.USER_INFOS_TABLE.'
2075SET registration_date = "'.$dbnow.'"
2076WHERE user_id = '.$user_id.'
2077;';
2078    pwg_query($query);
2079   
2080    if ( $conf['guest_access'] )
2081    {
2082      return( get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2083    }
2084    else
2085    {
2086      return( get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2087    }
2088  }
2089}
2090
2091
2092/**
2093 * Function called from functions.inc.php to reset last visit date after sending a reminder
2094 *
2095 * @param : User id
2096 *
2097 */
2098function resetlastvisit($user_id)
2099{
2100  global $conf;
2101
2102  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2103
2104  $query = '
2105UPDATE '.USER_LASTVISIT_TABLE.'
2106SET lastvisit = "'.$dbnow.'", reminder = "true"
2107WHERE user_id = '.$user_id.'
2108;';
2109  pwg_query($query);
2110}
2111
2112
2113/**
2114 * Function called from main.inc.php - Triggered on user deletion
2115 *
2116 */
2117function DeleteConfirmMail($user_id)
2118{
2119  $query = '
2120DELETE FROM '.USER_CONFIRM_MAIL_TABLE.'
2121WHERE user_id = '.$user_id.'
2122;';
2123  pwg_query($query);
2124}
2125
2126/**
2127 * Function called from main.inc.php - Triggered on user deletion
2128 *
2129 */
2130function DeleteLastVisit($user_id)
2131{
2132  $query = '
2133DELETE FROM '.USER_LASTVISIT_TABLE.'
2134WHERE user_id = '.$user_id.'
2135;';
2136  pwg_query($query);
2137}
2138
2139
2140/**
2141 * Function called from main.inc.php - Triggered on user deletion
2142 *
2143 * @param : User id
2144 *
2145 */
2146function DeleteRedir($user_id)
2147{
2148  $tab = array();
2149
2150  $query = '
2151SELECT value
2152FROM '.CONFIG_TABLE.'
2153WHERE param = "UserAdvManager_Redir"
2154;';
2155
2156  $tab = pwg_db_fetch_row(pwg_query($query));
2157 
2158  $values = explode(',', $tab[0]);
2159
2160  unset($values[array_search($user_id, $values)]);
2161     
2162  $query = '
2163UPDATE '.CONFIG_TABLE.'
2164SET value = "'.implode(',', $values).'"
2165WHERE param = "UserAdvManager_Redir";';
2166
2167  pwg_query($query);
2168}
2169
2170
2171/**
2172 * Function called from ConfirmMail.php to verify validation key used by user according time limit
2173 * Return true is key validation is OK else return false
2174 *
2175 * @param : User id
2176 *
2177 * @return : Bool
2178 *
2179 */
2180function VerifyConfirmMail($id)
2181{
2182  global $conf;
2183
2184  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2185 
2186  $conf_UAM = unserialize($conf['UserAdvManager']);
2187
2188  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2189
2190  $query = '
2191SELECT COUNT(*)
2192FROM '.USER_CONFIRM_MAIL_TABLE.'
2193WHERE id = "'.$id.'"
2194;';
2195  list($count) = pwg_db_fetch_row(pwg_query($query));
2196
2197  if ($count == 1)
2198  {
2199    $query = '
2200SELECT user_id, status, date_check
2201FROM '.USER_CONFIRM_MAIL_TABLE.'
2202WHERE id = "'.$id.'"
2203;';
2204    $data = pwg_db_fetch_assoc(pwg_query($query));
2205
2206    if (!empty($data) and isset($data['user_id']) and is_null($data['date_check']))
2207    {
2208      $query = '
2209SELECT registration_date
2210FROM '.USER_INFOS_TABLE.'
2211WHERE user_id = '.$data['user_id'].'
2212;';
2213      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2214
2215//              Time limit process             
2216// ******************************************** 
2217      if (!empty($registration_date))
2218      {
2219                                                                // Verify Confirmmail with time limit ON
2220                                // -------------------------------------
2221                                                                if (isset ($conf_UAM_ConfirmMail[1]))
2222                                                                {
2223                                                                                // Dates formating and compare
2224                                        // ---------------------------
2225                                                                                $today = date("d-m-Y"); // Get today's date
2226                                                                                list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2227                                                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2228
2229                                                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2230                                                                                list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2231                                                                                $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2232
2233                                                                                $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
2234                                                                                $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2235
2236                                                                                // Condition with the value set for time limit
2237                                        // -------------------------------------------
2238                                                                                if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
2239                                                                                {
2240                                                                                                list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2241
2242                                        // Update ConfirmMail table
2243                                        // ------------------------
2244                                                                                                $query = '
2245UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2246SET date_check="'.$dbnow.'", reminder="false"
2247WHERE id = "'.$id.'"
2248;';
2249                                                                                                pwg_query($query);
2250
2251                                        // Update LastVisit table - Force reminder field to false
2252                                        // Usefull when a user has been automatically downgraded and revalidate its registration
2253                                        // -------------------------------------------------------------------------------------
2254                                                                                                $query = '
2255UPDATE '.USER_LASTVISIT_TABLE.'
2256SET reminder="false"
2257WHERE user_id = "'.$data['user_id'].'"
2258;';
2259                                                                                                pwg_query($query);
2260     
2261                                                                                                if ($conf_UAM[2] <> -1) // Delete user from unvalidated users group
2262                                                                                                {
2263                                                                                                                $query = '
2264DELETE FROM '.USER_GROUP_TABLE.'
2265WHERE user_id = '.$data['user_id'].'
2266  AND group_id = '.$conf_UAM[2].'
2267;';
2268                                                                                                                pwg_query($query);
2269                                                                                                }
2270
2271                                                                                                if ($conf_UAM[3] <> -1) // Add user to validated users group
2272                                                                                                {
2273                                                                                                                $query = '
2274INSERT INTO '.USER_GROUP_TABLE.'
2275  (user_id, group_id)
2276VALUES
2277  ('.$data['user_id'].', '.$conf_UAM[3].')
2278;';
2279                                                                                                                pwg_query($query);
2280                                                                                                }
2281
2282                                                                                                if ($conf_UAM[4] <> -1) // Change user's status
2283                                                                                                {
2284                                                                                                                $query = '
2285UPDATE '.USER_INFOS_TABLE.'
2286SET status = "'.$conf_UAM[4].'"
2287WHERE user_id = '.$data['user_id'].'
2288;';
2289                                                                                                                pwg_query($query);
2290                                                                                                }
2291
2292                                                                                                if ($conf_UAM[36] <> -1) // Change user's privacy level
2293                                                                                                {
2294                                                                                                                $query = '
2295UPDATE '.USER_INFOS_TABLE.'
2296SET level = "'.$conf_UAM[36].'"
2297WHERE user_id = '.$data['user_id'].'
2298;';
2299                                                                                                                pwg_query($query);
2300                                                                                                }
2301
2302                                                                                                // Set UAM_validated field to True in #_users table
2303                                                                                                $query = '
2304UPDATE '.USERS_TABLE.'
2305SET UAM_validated = "true"
2306WHERE id = '.$data['user_id'].'
2307;';
2308                                                                                                pwg_query($query);
2309
2310                                                                                                // Refresh user's category cache
2311                                                // -----------------------------
2312                                                                                                invalidate_user_cache();
2313
2314                                                                                                return true;
2315                                                                                }
2316                                                                                elseif ($deltadays > $conf_UAM_ConfirmMail[1]) // If timelimit exeeds
2317                                                                                {
2318                                                                                                return false;
2319                                                                                }
2320                                                                }
2321                                                                // Verify Confirmmail with time limit OFF
2322                                // --------------------------------------
2323                                                                else
2324                                                                {
2325                                                                                list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2326
2327                                // Update ConfirmMail table
2328                                // ------------------------
2329                                                                                $query = '
2330UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2331SET date_check="'.$dbnow.'"
2332WHERE id = "'.$id.'"
2333;';
2334                                                                                pwg_query($query);
2335
2336                                // Update LastVisit table - Force reminder field to false
2337                                // Usefull when a user has been automatically downgraded and revalidate its registration
2338                                // -------------------------------------------------------------------------------------
2339                                                                                $query = '
2340UPDATE '.USER_LASTVISIT_TABLE.'
2341SET reminder="false"
2342WHERE user_id = "'.$data['user_id'].'"
2343;';
2344                                pwg_query($query);
2345
2346                                                                                if ($conf_UAM[2] <> -1) // Delete user from unvalidated users group
2347                                                                                {
2348                                                                                                $query = '
2349DELETE FROM '.USER_GROUP_TABLE.'
2350WHERE user_id = '.$data['user_id'].'
2351AND group_id = '.$conf_UAM[2].'
2352;';
2353                                                                                                pwg_query($query);
2354                                                                                }
2355
2356                                                                                if ($conf_UAM[3] <> -1)
2357                                                                                {
2358                                                                                                $query = '
2359DELETE FROM '.USER_GROUP_TABLE.'
2360WHERE user_id = '.$data['user_id'].'
2361AND group_id = '.$conf_UAM[3].'
2362;';
2363                                                                                                pwg_query($query);
2364
2365                                                                                                $query = '
2366INSERT INTO '.USER_GROUP_TABLE.'
2367  (user_id, group_id)
2368VALUES
2369  ('.$data['user_id'].', '.$conf_UAM[3].')
2370;';
2371                                                                                                pwg_query($query);
2372                                                                                }
2373
2374                                                                                if ($conf_UAM[4] <> -1) // Change user's status
2375                                                                                {
2376                                                                                                $query = '
2377UPDATE '.USER_INFOS_TABLE.'
2378SET status = "'.$conf_UAM[4].'"
2379WHERE user_id = '.$data['user_id'].'
2380;';
2381                                                                                                pwg_query($query);
2382                                                                                }
2383
2384                                                                                if ($conf_UAM[36] <> -1) // Change user's privacy level
2385                                                                                {
2386                                                                                                $query = '
2387UPDATE '.USER_INFOS_TABLE.'
2388SET level = "'.$conf_UAM[36].'"
2389WHERE user_id = '.$data['user_id'].'
2390;';
2391                                                                                                pwg_query($query);
2392                                                                                }
2393
2394                                                                                // Set UAM_validated field to True in #_users table
2395                                                                                $query = '
2396UPDATE '.USERS_TABLE.'
2397SET UAM_validated = "true"
2398WHERE id = '.$data['user_id'].'
2399;';
2400                                                                                pwg_query($query);
2401
2402                                                                                // Refresh user's category cache
2403                                // -----------------------------
2404                                                                                invalidate_user_cache();
2405
2406                                                                                return true;
2407                                                                }
2408                                                }
2409                                }
2410    else if (!empty($data) and !is_null($data['date_check']))
2411    {
2412      return false;
2413    }
2414                }
2415  else
2416    return false;
2417}
2418
2419
2420/**
2421 * Function called from UAM_admin.php for manual validation by admin
2422 *
2423 * @param : User id
2424 *
2425 */
2426function ManualValidation($id)
2427{
2428                global $conf;
2429
2430                $conf_UAM = unserialize($conf['UserAdvManager']);
2431
2432                if (isset($conf_UAM[1]) and $conf_UAM[1] == 'true') // Set date of validation
2433                {
2434                                list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
2435
2436                                $query = '
2437UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2438SET date_check="'.$dbnow.'"
2439WHERE user_id = '.$id.'
2440;';
2441                                pwg_query($query);
2442                }
2443
2444                if ($conf_UAM[2] <> -1) // Delete user from waiting group
2445                {
2446                                $query = '
2447DELETE FROM '.USER_GROUP_TABLE.'
2448WHERE user_id = '.$id.'
2449                AND group_id = '.$conf_UAM[2].'
2450;';
2451                                pwg_query($query);
2452                }
2453 
2454                if ($conf_UAM[3] <> -1) // Set user's valid group
2455                {
2456                                $query = '
2457DELETE FROM '.USER_GROUP_TABLE.'
2458WHERE user_id = '.$id.'
2459                AND group_id = '.$conf_UAM[3].'
2460;';
2461                                pwg_query($query);
2462       
2463                                $query = '
2464INSERT INTO '.USER_GROUP_TABLE.'
2465                (user_id, group_id)
2466VALUES
2467                ('.$id.', '.$conf_UAM[3].')
2468;';
2469                                pwg_query($query);
2470                }
2471
2472                if ($conf_UAM[4] <> -1) // Set user's valid status
2473                {
2474                                $query = '
2475UPDATE '.USER_INFOS_TABLE.'
2476SET status = "'.$conf_UAM[4].'"
2477WHERE user_id = '.$id.'
2478;';
2479                                pwg_query($query);
2480                }
2481
2482                if ($conf_UAM[36] <> -1) // Set user's valid privacy level
2483                {
2484                                $query = '
2485UPDATE '.USER_INFOS_TABLE.'
2486SET level = "'.$conf_UAM[36].'"
2487WHERE user_id = '.$id.'
2488;';
2489                                pwg_query($query);
2490                }
2491
2492                // Set UAM_validated field to True in #_users table
2493                $query = '
2494UPDATE '.USERS_TABLE.'
2495SET UAM_validated = "true"
2496WHERE id = '.$id.'
2497;';
2498                pwg_query($query);
2499}
2500
2501
2502/**
2503 * Function called from functions.inc.php - Check if username matches forbidden characters
2504 *
2505 * @param : User login
2506 *
2507 * @return : Bool
2508 *
2509 */
2510function ValidateUsername($login)
2511{
2512  global $conf;
2513
2514  $conf_UAM = unserialize($conf['UserAdvManager']);
2515
2516  if (isset($login) and isset($conf_UAM[6]) and $conf_UAM[6] <> '')
2517  {
2518    $conf_CharExclusion = preg_split("/,/",$conf_UAM[6]);
2519    for ($i = 0 ; $i < count($conf_CharExclusion) ; $i++)
2520    {
2521      //Detect meta-characters (# ! ^ $ ( ) [ ] { } ? + * . \ -) for special pattern
2522      if ($conf_CharExclusion[$i] == "#"
2523       or $conf_CharExclusion[$i] == "$"
2524       or $conf_CharExclusion[$i] == "!"
2525       or $conf_CharExclusion[$i] == "^"
2526       or $conf_CharExclusion[$i] == "*"
2527       or $conf_CharExclusion[$i] == "?"
2528       or $conf_CharExclusion[$i] == "+"
2529       or $conf_CharExclusion[$i] == "."
2530       or $conf_CharExclusion[$i] == "\\"
2531       or $conf_CharExclusion[$i] == "|"
2532       or $conf_CharExclusion[$i] == "["
2533       or $conf_CharExclusion[$i] == "]"
2534       or $conf_CharExclusion[$i] == "("
2535       or $conf_CharExclusion[$i] == ")"
2536       or $conf_CharExclusion[$i] == "{"
2537       or $conf_CharExclusion[$i] == "}"
2538       or $conf_CharExclusion[$i] == "-")
2539      {
2540        $pattern = '/[][^$.\*+?(){}#|-]/i';
2541      }
2542      else
2543      {
2544        $pattern = '/'.$conf_CharExclusion[$i].'/i';
2545      }
2546
2547      if (preg_match($pattern, $login))
2548      {
2549        return true;
2550      }
2551    }
2552  }
2553  else
2554  {
2555    return false;
2556  }
2557}
2558
2559
2560/**
2561 * Function called from main.inc.php - Check if user's email is in excluded email providers list
2562 * Doesn't work on call - Must be copied in main.inc.php to work
2563 *
2564 * @param : Email address
2565 *
2566 * @return : Bool
2567 *
2568 */
2569function ValidateEmailProvider($email)
2570{
2571  global $conf;
2572
2573  $conf_UAM = unserialize($conf['UserAdvManager']);
2574 
2575                if (isset($email) and isset($conf_UAM[11]) and $conf_UAM[11] <> '')
2576                {
2577                                $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM[11]);
2578                                for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
2579                                {
2580                                                $pattern = '/'.$conf_MailExclusion[$i].'/i';
2581                                                if (preg_match($pattern, $email))
2582      {
2583                return true;
2584      }
2585                                }
2586                }
2587  else
2588  {
2589    return false;
2590  }
2591}
2592
2593
2594/**
2595 * Function called from UAM_admin.php - Get unvalidated users according time limit
2596 *
2597 * @return : List of users
2598 *
2599 */
2600function get_unvalid_user_list()
2601{
2602                global $conf, $page;
2603         
2604                // Get ConfirmMail configuration
2605  // -----------------------------
2606  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2607  // Get UAM configuration
2608  // ---------------------
2609  $conf_UAM = unserialize($conf['UserAdvManager']);
2610 
2611  $users = array();
2612
2613                // Search users depending expiration date
2614  // --------------------------------------
2615  $query = '
2616SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2617                u.'.$conf['user_fields']['username'].' AS username,
2618                u.'.$conf['user_fields']['email'].' AS email,
2619                ui.status,
2620                ui.enabled_high,
2621                ui.level,
2622                ui.registration_date
2623FROM '.USERS_TABLE.' AS u
2624  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2625    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2626  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
2627    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2628WHERE u.'.$conf['user_fields']['id'].' >= 3
2629  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'"
2630  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail[1].'")
2631                AND u.UAM_validated = "false"
2632ORDER BY ui.registration_date ASC
2633;';
2634
2635                $result = pwg_query($query);
2636     
2637  while ($row = pwg_db_fetch_assoc($result))
2638  {
2639                $user = $row;
2640    $user['groups'] = array();
2641
2642    array_push($users, $user);
2643                }
2644
2645                // Add groups list
2646  // ---------------
2647  $user_ids = array();
2648  foreach ($users as $i => $user)
2649  {
2650                $user_ids[$i] = $user['id'];
2651                }
2652
2653                $user_nums = array_flip($user_ids);
2654
2655  if (count($user_ids) > 0)
2656  {
2657                $query = '
2658SELECT user_id, group_id
2659  FROM '.USER_GROUP_TABLE.'
2660WHERE user_id IN ('.implode(',', $user_ids).')
2661;';
2662       
2663                                $result = pwg_query($query);
2664       
2665    while ($row = pwg_db_fetch_assoc($result))
2666    {
2667                array_push(
2668                $users[$user_nums[$row['user_id']]]['groups'],
2669        $row['group_id']
2670                                                );
2671                                }
2672                }
2673
2674                return $users;
2675}
2676
2677
2678/**
2679 * Function called from functions.inc.php - Get all users who haven't validate their registration in configured time
2680 * to delete or remail them automatically
2681 *
2682 * @return : List of users
2683 *
2684 */
2685function get_unvalid_user_autotasks()
2686{
2687                global $conf, $page;
2688         
2689                // Get ConfirmMail configuration
2690  // -----------------------------
2691  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2692 
2693  $users = array();
2694
2695                // search users depending expiration date
2696  // --------------------------------------
2697  $query = '
2698SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2699                ui.registration_date
2700FROM '.USERS_TABLE.' AS u
2701  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2702    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2703WHERE u.'.$conf['user_fields']['id'].' >= 3
2704  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail[1].'")
2705ORDER BY ui.registration_date ASC;';
2706
2707                $result = pwg_query($query);
2708
2709  while ($row = pwg_db_fetch_assoc($result))
2710  {
2711    array_push($users, $row);
2712                }
2713
2714                return $users;
2715}
2716
2717
2718/**
2719 * Function called from UAM_admin.php - Get ghost users
2720 *
2721 * @return : List of users
2722 *
2723 */
2724function get_ghost_user_list()
2725{
2726                global $conf, $page;
2727
2728  $conf_UAM = unserialize($conf['UserAdvManager']);
2729
2730  $users = array();
2731
2732                // Search users depending expiration date
2733  // --------------------------------------
2734  $query = '
2735SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2736                u.'.$conf['user_fields']['username'].' AS username,
2737                u.'.$conf['user_fields']['email'].' AS email,
2738                lv.lastvisit,
2739                lv.reminder
2740FROM '.USERS_TABLE.' AS u
2741  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2742    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2743WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[16].'")
2744ORDER BY lv.lastvisit ASC;';
2745
2746                $result = pwg_query($query);
2747     
2748  while ($row = pwg_db_fetch_assoc($result))
2749  {
2750                $user = $row;
2751    $user['groups'] = array();
2752
2753    array_push($users, $user);
2754                }
2755
2756                // Add groups list
2757  // ---------------
2758  $user_ids = array();
2759  foreach ($users as $i => $user)
2760  {
2761        $user_ids[$i] = $user['id'];
2762                }
2763
2764                return $users;
2765}
2766
2767
2768/**
2769 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
2770 *
2771 * @return : List of users to delete or downgrade automatically
2772 *
2773 */
2774function get_ghosts_autotasks()
2775{
2776                global $conf, $page;
2777
2778  $conf_UAM = unserialize($conf['UserAdvManager']);
2779 
2780  $users = array();
2781 
2782                // Search users depending expiration date and reminder sent
2783  // --------------------------------------------------------
2784  $query = '
2785SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2786                lv.lastvisit
2787FROM '.USERS_TABLE.' AS u
2788  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2789    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2790WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM[16].'")
2791ORDER BY lv.lastvisit ASC;';
2792
2793                $result = pwg_query($query);
2794     
2795                while ($row = pwg_db_fetch_assoc($result))
2796  {
2797    array_push($users, $row);
2798                }
2799 
2800                return $users;
2801}
2802
2803
2804/**
2805 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
2806 *
2807 * @return : List of users
2808 *
2809 */
2810function get_user_list()
2811{
2812                global $conf, $page;
2813 
2814  $users = array();
2815
2816                // Search users depending expiration date with exclusion of Adult_Content generic users
2817  // ------------------------------------------------------------------------------------
2818  $query = '
2819SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2820                u.'.$conf['user_fields']['username'].' AS username,
2821                u.'.$conf['user_fields']['email'].' AS email,
2822                ug.lastvisit
2823FROM '.USERS_TABLE.' AS u
2824  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
2825    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2826WHERE u.'.$conf['user_fields']['id'].' >= 3
2827  AND u.username NOT LIKE "16"
2828  AND u.username NOT LIKE "18"
2829ORDER BY ug.lastvisit DESC
2830;';
2831
2832                $result = pwg_query($query);
2833     
2834  while ($row = pwg_db_fetch_assoc($result))
2835  {
2836                $user = $row;
2837    $user['groups'] = array();
2838
2839    array_push($users, $user);
2840                }
2841
2842                // Add groups list
2843  // ---------------
2844  $user_ids = array();
2845  foreach ($users as $i => $user)
2846  {
2847                        $user_ids[$i] = $user['id'];
2848                }
2849
2850                return $users;
2851}
2852
2853
2854/**
2855 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
2856 *
2857 * @param : user id
2858 *
2859 * @return : Bool
2860 *
2861 */
2862function expiration($id)
2863{
2864        global $conf, $page;
2865         
2866                // Get ConfirmMail configuration
2867  // -----------------------------
2868  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2869         
2870                // Get UAM configuration
2871  // ---------------------
2872  $conf_UAM = unserialize($conf['UserAdvManager']);
2873       
2874                $query = '
2875SELECT registration_date
2876  FROM '.USER_INFOS_TABLE.'
2877WHERE user_id = '.$id.'
2878;';
2879                list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2880
2881//              Time limit process             
2882// ******************************************** 
2883                if (!empty($registration_date))
2884  {
2885                                // Dates formating and compare
2886                // ---------------------------
2887                                $today = date("d-m-Y"); // Get today's date
2888                                list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2889                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2890               
2891                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2892                                list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2893                                $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2894                       
2895                                $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps     
2896                                $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2897
2898                                // Condition with the value set for time limit
2899    // -------------------------------------------
2900                                if ($deltadays <= $conf_UAM_ConfirmMail[1]) // If Nb of days is less than the limit set
2901                                {
2902                                                return false;
2903                                }
2904                                else
2905                                {
2906                                                return true;
2907                                }
2908                }
2909}
2910
2911
2912/**
2913 * Returns a password's score for password complexity check
2914 *
2915 * @param : password filled by user
2916 *
2917 * @return : Score calculation
2918 *
2919 * Thanx to MathieuGut from http://m-gut.developpez.com
2920 */
2921function testpassword($password) // $password given by user
2922{
2923
2924  // Variables initiation
2925  // --------------------
2926  $points = 0;
2927  $point_lowercase = 0;
2928  $point_uppercase = 0;
2929  $point_numbers = 0;
2930  $point_characters = 0;
2931
2932  // Getting password lengh
2933  // ----------------------
2934  $length = strlen($password);
2935
2936  // Loop to read password characters
2937  for($i = 0; $i < $length; $i++)
2938  {
2939    // Select each letters
2940    // $i is 0 at first turn
2941    // ---------------------
2942    $letters = $password[$i];
2943
2944    if ($letters>='a' && $letters<='z')
2945    {
2946      // Adding 1 point to score for a lowercase
2947      // ---------------------------------------
2948                                $points = $points + 1;
2949
2950                                // Adding bonus points for lowercase
2951      // ---------------------------------
2952                  $point_lowercase = 1;
2953    }
2954    else if ($letters>='A' && $letters <='Z')
2955    {
2956      // Adding 2 points to score for uppercase
2957      // --------------------------------------
2958      $points = $points + 2;
2959               
2960      // Adding bonus points for uppercase
2961      // ---------------------------------
2962      $point_uppercase = 2;
2963    }
2964    else if ($letters>='0' && $letters<='9')
2965    {
2966      // Adding 3 points to score for numbers
2967      // ------------------------------------
2968      $points = $points + 3;
2969               
2970      // Adding bonus points for numbers
2971      // -------------------------------
2972      $point_numbers = 3;
2973    }
2974    else
2975    {
2976      // Adding 5 points to score for special characters
2977      // -----------------------------------------------
2978      $points = $points + 5;
2979               
2980      // Adding bonus points for special characters
2981      // ------------------------------------------
2982      $point_characters = 5;
2983    }
2984  }
2985
2986  // Calculating the coefficient points/length
2987  // -----------------------------------------
2988  $step1 = $points / $length;
2989
2990  // Calculation of the diversity of character types...
2991  // --------------------------------------------------
2992  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
2993
2994  // Multiplying the coefficient of diversity with that of the length
2995  // ----------------------------------------------------------------
2996  $score = $step1 * $step2;
2997
2998  // Multiplying the result by the length of the string
2999  // --------------------------------------------------
3000  $finalscore = $score * $length;
3001
3002  return $finalscore;
3003}
3004
3005
3006/**
3007 * UAM_check_profile - Thx to LucMorizur
3008 * checks if a user id is registered as having already
3009 * visited his profile page.
3010 *
3011 * @uid        : the user id
3012 *
3013 * @user_idsOK : (returned) array of all users ids having already visited
3014 *               their profile.php pages
3015 *
3016 * @returns    : true or false whether the users has already visited his
3017 *               profile.php page or not
3018 *
3019 */
3020function UAM_check_profile($uid, &$user_idsOK)
3021{
3022  $t = array();
3023  $v = false;
3024 
3025  $query = '
3026SELECT value
3027FROM '.CONFIG_TABLE.'
3028WHERE param = "UserAdvManager_Redir"
3029;';
3030 
3031  if ($v = (($t = pwg_db_fetch_row(pwg_query($query))) !== false))
3032  {
3033    $user_idsOK = explode(',', $t[0]);
3034    $v = (in_array($uid, $user_idsOK));
3035  }
3036  return $v;
3037}
3038
3039
3040/**
3041 * UAM_check_pwdreset
3042 * checks if a user id is registered as having already
3043 * changed his password.
3044 *
3045 * @uid        : the user id
3046 *
3047 * @returns    : true or false whether the users has already changed his password
3048 *
3049 */
3050function UAM_check_pwgreset($uid)
3051{
3052  $query = '
3053SELECT UAM_pwdreset
3054FROM '.USERS_TABLE.'
3055WHERE id='.$uid.'
3056;';
3057
3058  $result = pwg_db_fetch_assoc(pwg_query($query));
3059 
3060  if($result['UAM_pwdreset'] == 'true')
3061  {
3062    return true;
3063  }
3064  else return false; 
3065}
3066
3067
3068/**
3069 * UAM_UsrReg_Verif
3070 * Check if the user who logged-in have validate his registration
3071 *
3072 * @returns : True if validation is OK else False
3073 */
3074function UAM_UsrReg_Verif($user_id)
3075{
3076  global $conf;
3077
3078  $query = '
3079SELECT UAM_validated
3080FROM '.USERS_TABLE.'
3081WHERE id='.$user_id.'
3082;';
3083
3084  $result = pwg_db_fetch_assoc(pwg_query($query));
3085
3086  if($result['UAM_validated'] == 'true')
3087  {
3088    return true;
3089  }
3090  else return false;
3091}
3092
3093
3094/**
3095 * SetUnvalidated
3096 * Set UAM_validated field to false in #_users table
3097 *
3098 **/
3099function SetUnvalidated($user_id)
3100{
3101  $query ='
3102UPDATE '.USERS_TABLE.'
3103SET UAM_validated = "false"
3104WHERE id = '.$user_id.'
3105LIMIT 1
3106;';
3107
3108  pwg_query($query);
3109}
3110
3111
3112/**
3113 * UAM_Set_PwdReset
3114 * Action in user_list to set a password reset for a user
3115 */
3116function UAM_Set_PwdReset($uid)
3117{
3118  $query ='
3119UPDATE '.USERS_TABLE.'
3120SET UAM_pwdreset = "true"
3121WHERE id = '.$uid.'
3122LIMIT 1
3123;';
3124
3125  pwg_query($query);
3126}
3127
3128
3129/**
3130 * UAM_loc_visible_user_list
3131 * Adds a new feature in user_list to allow password reset for selected users by admin
3132 *
3133 */
3134function UAM_loc_visible_user_list($visible_user_list)
3135{
3136  global $template;
3137 
3138  $template->append('plugin_user_list_column_titles', l10n('UAM_PwdReset'));
3139 
3140  $user_ids = array();
3141 
3142  foreach ($visible_user_list as $i => $user)
3143  {
3144    $user_ids[$i] = $user['id'];
3145  }
3146 
3147  $user_nums = array_flip($user_ids);
3148
3149  // Query to get informations in database
3150  // -------------------------------------
3151  if (!empty($user_ids))
3152  {
3153    $query = '
3154SELECT DISTINCT id, UAM_pwdreset
3155  FROM '.USERS_TABLE.'
3156  WHERE id IN ('.implode(',', $user_ids).')
3157;';
3158    $result = pwg_query($query);
3159   
3160    while ($row = mysql_fetch_array($result))
3161    {
3162      if ($row['UAM_pwdreset'] == 'false')
3163      {
3164        $pwdreset = l10n('UAM_PwdReset_Done');
3165      }
3166      else if ($row['UAM_pwdreset'] == 'true')
3167      {
3168        $pwdreset = l10n('UAM_PwdReset_Todo');
3169      }
3170      else $pwdreset = l10n('UAM_PwdReset_NA');
3171     
3172                  $visible_user_list[$user_nums[$row['id']]]['plugin_columns'][] = $pwdreset; // Shows users password state in user_list
3173    }
3174  }
3175  return $visible_user_list;
3176}
3177
3178
3179/**
3180 * UAM specific database dump (only for MySql !)
3181 * Creates an SQL dump of UAM specific tables and configuration settings
3182 *
3183 * @returns  : Boolean to manage appropriate message display
3184 *
3185 */
3186function UAM_dump($download)
3187{
3188  global $conf;
3189
3190  $plugin =  PluginInfos(UAM_PATH);
3191  $version = $plugin['version'];
3192
3193  // Initial backup folder creation and file initialisation
3194  // ------------------------------------------------------
3195  if (!is_dir(UAM_PATH.'/include/backup'))
3196    mkdir(UAM_PATH.'/include/backup');
3197
3198  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3199
3200  $fp = fopen($Backup_File, 'w');
3201
3202  // Writing plugin version
3203  $insertions = "-- ".$version." --\n\n";
3204  fwrite($fp, $insertions);
3205
3206  // Saving UAM specific tables
3207  // --------------------------
3208  $ListTables = array(USER_CONFIRM_MAIL_TABLE, USER_LASTVISIT_TABLE);
3209  $j=0;
3210
3211  while($j < count($ListTables))
3212  {
3213    $sql = 'SHOW CREATE TABLE '.$ListTables[$j];
3214    $res = pwg_query($sql);
3215
3216    if ($res)
3217    {
3218      $insertions = "-- -------------------------------------------------------\n";
3219      $insertions .= "-- Create ".$ListTables[$j]." table\n";
3220      $insertions .= "-- ------------------------------------------------------\n\n";
3221
3222      $insertions .= "DROP TABLE IF EXISTS ".$ListTables[$j].";\n\n";
3223
3224      $array = mysql_fetch_array($res);
3225      $array[1] .= ";\n\n";
3226      $insertions .= $array[1];
3227
3228      $req_table = pwg_query('SELECT * FROM '.$ListTables[$j]) or die(mysql_error());
3229      $nb_fields = mysql_num_fields($req_table);
3230      while ($line = mysql_fetch_array($req_table))
3231      {
3232        $insertions .= 'INSERT INTO '.$ListTables[$j].' VALUES (';
3233        for ($i=0; $i<$nb_fields; $i++)
3234        {
3235          $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3236        }
3237        $insertions = substr($insertions, 0, -2);
3238        $insertions .= ");\n";
3239      }
3240      $insertions .= "\n\n";
3241    }
3242
3243    fwrite($fp, $insertions);   
3244    $j++;
3245  }
3246 
3247  // Saving UAM configuration
3248  // ------------------------
3249  $insertions = "-- -------------------------------------------------------\n";
3250  $insertions .= "-- Insert UAM configuration in ".CONFIG_TABLE."\n";
3251  $insertions .= "-- ------------------------------------------------------\n\n";
3252
3253  fwrite($fp, $insertions);
3254
3255  $pattern = "UserAdvManager%";
3256  $req_table = pwg_query('SELECT * FROM '.CONFIG_TABLE.' WHERE param LIKE "'.$pattern.'";') or die(mysql_error());
3257  $nb_fields = mysql_num_fields($req_table);
3258
3259  while ($line = mysql_fetch_array($req_table))
3260  {
3261    $insertions = 'INSERT INTO '.CONFIG_TABLE.' VALUES (';
3262    for ($i=0; $i<$nb_fields; $i++)
3263    {
3264      $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3265    }
3266    $insertions = substr($insertions, 0, -2);
3267    $insertions .= ");\n";
3268
3269    fwrite($fp, $insertions);
3270  }
3271
3272  fclose($fp);
3273
3274  // Download generated dump file
3275  // ----------------------------
3276  if ($download == 'true')
3277  {
3278    if (@filesize($Backup_File))
3279    {
3280      $http_headers = array(
3281        'Content-Length: '.@filesize($Backup_File),
3282        'Content-Type: text/x-sql',
3283        'Content-Disposition: attachment; filename="UAM_dbbackup.sql";',
3284        'Content-Transfer-Encoding: binary',
3285        );
3286
3287      foreach ($http_headers as $header)
3288      {
3289        header($header);
3290      }
3291
3292      @readfile($Backup_File);
3293      exit();
3294    }
3295  }
3296
3297  return true;
3298}
3299
3300
3301/**
3302 * UAM_Restore_backup_file
3303 * Restore backup database file
3304 *
3305 * @returns : Boolean
3306 */
3307function UAM_Restore_backup_file() 
3308{
3309  global $prefixeTable, $dblayer, $conf;
3310 
3311  define('DEFAULT_PREFIX_TABLE', 'piwigo_');
3312 
3313  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3314
3315  // Cleanup database before restoring
3316  // ---------------------------------
3317
3318  // Delete UserAdvManager global config in #_config table
3319  $q = '
3320DELETE FROM '.CONFIG_TABLE.'
3321WHERE param="UserAdvManager"
3322;';
3323
3324  pwg_query($q);
3325
3326  // Delete UserAdvManager_ConfirmMail global config in #_config table
3327  $q = '
3328DELETE FROM '.CONFIG_TABLE.'
3329WHERE param="UserAdvManager_ConfirmMail"
3330;';
3331
3332  pwg_query($q);
3333
3334  // Delete UserAdvManager_Redir config in #_config table
3335  $q = '
3336DELETE FROM '.CONFIG_TABLE.'
3337WHERE param="UserAdvManager_Redir"
3338;';
3339
3340  pwg_query($q);
3341
3342  // Delete UserAdvManager_Version config in #_config table
3343  $q = '
3344DELETE FROM '.CONFIG_TABLE.'
3345WHERE param="UserAdvManager_Version"
3346;';
3347
3348  pwg_query($q);
3349
3350  // Restore sql backup file - DROP TABLE queries are executed
3351  // ---------------------------------------------------------
3352  UAM_execute_sqlfile(
3353    $Backup_File,
3354    DEFAULT_PREFIX_TABLE,
3355    $prefixeTable,
3356    $dblayer
3357  );
3358}
3359
3360
3361/**
3362 * loads an sql file and executes all queries / Based on Piwigo's original install file
3363 *
3364 * Before executing a query, $replaced is... replaced by $replacing. This is
3365 * useful when the SQL file contains generic words.
3366 *
3367 * @param string filepath
3368 * @param string replaced
3369 * @param string replacing
3370 * @return void
3371 */
3372function UAM_execute_sqlfile($filepath, $replaced, $replacing, $dblayer)
3373{
3374  $sql_lines = file($filepath);
3375  $query = '';
3376  foreach ($sql_lines as $sql_line)
3377  {
3378    $sql_line = trim($sql_line);
3379    if (preg_match('/(^--|^$)/', $sql_line))
3380    {
3381      continue;
3382    }
3383   
3384    $query.= ' '.$sql_line;
3385   
3386    // if we reached the end of query, we execute it and reinitialize the
3387    // variable "query"
3388    if (preg_match('/;$/', $sql_line))
3389    {
3390      $query = trim($query);
3391      $query = str_replace($replaced, $replacing, $query);
3392      if ('mysql' == $dblayer)
3393      {
3394        if (preg_match('/^(CREATE TABLE .*)[\s]*;[\s]*/im', $query, $matches))
3395        {
3396          $query = $matches[1].' DEFAULT CHARACTER SET utf8'.';';
3397        }
3398      }
3399      pwg_query($query);
3400      $query = '';
3401    }
3402  }
3403}
3404
3405
3406/**
3407 * Delete obsolete files on plugin upgrade
3408 * Obsolete files are listed in file obsolete.list
3409 *
3410 */
3411function clean_obsolete_files()
3412{
3413  if (file_exists(UAM_PATH.'obsolete.list')
3414    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
3415    and !empty($old_files))
3416  {
3417    array_push($old_files, 'obsolete.list');
3418    foreach($old_files as $old_file)
3419    {
3420      $path = UAM_PATH.$old_file;
3421      if (is_file($path))
3422      {
3423        @unlink($path);
3424      }
3425      elseif (is_dir($path))
3426      {
3427        @rmdir($path);
3428      }
3429    }
3430  }
3431}
3432
3433
3434/**
3435 * Function called from maintain.inc.php - to check if database upgrade is needed
3436 *
3437 * @param : table name
3438 *
3439 * @return : boolean
3440 *
3441 */
3442function table_exist($table)
3443{
3444  $query = 'DESC '.$table.';';
3445  return (bool)($res=pwg_query($query));
3446}
3447
3448
3449/**
3450 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
3451 *
3452 * @param : plugin directory
3453 *
3454 * @return : plugin's version and name
3455 *
3456 */
3457function PluginInfos($dir)
3458{
3459  $path = $dir;
3460
3461  $plg_data = implode( '', file($path.'main.inc.php') );
3462  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
3463  {
3464    $plugin['name'] = trim( $val[1] );
3465  }
3466  if (preg_match("|Version: (.*)|", $plg_data, $val))
3467  {
3468    $plugin['version'] = trim($val[1]);
3469  }
3470  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
3471  {
3472    $plugin['uri'] = trim($val[1]);
3473  }
3474  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
3475  {
3476    $plugin['description'] = trim($desc);
3477  }
3478  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
3479  {
3480    $plugin['description'] = trim($val[1]);
3481  }
3482  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
3483  {
3484    $plugin['author'] = trim($val[1]);
3485  }
3486  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
3487  {
3488    $plugin['author uri'] = trim($val[1]);
3489  }
3490  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
3491  {
3492    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
3493    if (is_numeric($extension)) $plugin['extension'] = $extension;
3494  }
3495// IMPORTANT SECURITY !
3496// --------------------
3497  $plugin = array_map('htmlspecialchars', $plugin);
3498
3499  return $plugin ;
3500}
3501
3502
3503/**
3504 * Useful for debugging - 4 vars can be set
3505 * Output result to log.txt file
3506 *
3507 */
3508function UAMLog($var1, $var2, $var3, $var4)
3509{
3510   $fo=fopen (UAM_PATH.'log.txt','a') ;
3511   fwrite($fo,"======================\n") ;
3512   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
3513   fwrite($fo,$var1 ."\r\n") ;
3514   fwrite($fo,$var2 ."\r\n") ;
3515   fwrite($fo,$var3 ."\r\n") ;
3516   fwrite($fo,$var4 ."\r\n") ;
3517   fclose($fo) ;
3518}
3519
3520?>
Note: See TracBrowser for help on using the repository browser.