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

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

New feature : Send the validation key by email to webmaster (not admins !) to allow it to validate manually a user registration whithout having to connect the gallery. This is when manual validation by admins is set in UAM options.

By the way, I fixed a bug in VerifyConfirmMail($key) function. I'm wondering it worked before...

I don't remember why I used $conf_UAM[4] <> -1 or isset($datastatus) in VerifyConfirmMail($key) function. Now only $conf_UAM[4] <> -1 is used and all works fine.

Next step : Extending the send of validation key to all admins in addition of webmaster.

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