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

Last change on this file since 21519 was 21519, checked in by Eric, 11 years ago

Next version is 2.50.2 :
Bug 2866 fixed - Fatal error message (Fatal error: Call to undefined function switch_lang_to()) when using validation link

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