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

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

Removing "new feature" marks in admin panel
Reference language files updated

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