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

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

UAM_UsrReg_Verif() function refactory - Step 2. Now an admin is able to validate a pending user even if no groups / status or PL are set in UAM.

Next step : Check is auto-demotion feature still works and fix if not.

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