source: extensions/UserAdvManager/branches/2.40/include/functions.inc.php @ 17512

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

r17510 merged from trunk to branch 2.40

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