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

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

bug 2744 fixed
Small code refactory

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