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

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

UAM_UsrReg_Verif() function refactory - Step 1. problem still remains when $confguest_access = false;

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