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

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

Small code cleanup

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