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

Last change on this file since 12314 was 12314, checked in by Eric, 13 years ago

Bug 2455 fixed - Exclusion of specific users (généric and admins users) for password reset function.
Bug 2451 fixed - Unable to handle Sql errors but control of backup file validity have been enforced.

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