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

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

Last try to use pwg_mail_notification_admins() to send validation link to admins and webmaster but keys are still not translated.

Still under investigation

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