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

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

bug 2878 fixed : [Kdays] flag was not translated in confirmation email sent to users

  • Property svn:eol-style set to LF
File size: 102.0 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  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1137
1138  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1139
1140        $infos1_perso = "";
1141  $infos2_perso = "";
1142  $subject = "";
1143
1144// We have to get the user's language in database
1145// ----------------------------------------------
1146  $query ='
1147SELECT user_id, language
1148FROM '.USER_INFOS_TABLE.'
1149WHERE user_id = '.$id.'
1150;';
1151  $data = pwg_db_fetch_assoc(pwg_query($query));
1152
1153// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1154// -------------------------------------------------------------------------------------------------------------------------------
1155  if (empty($data))
1156  {
1157// And switch gallery to this language before using personalized and multilangual contents
1158// ---------------------------------------------------------------------------------------
1159    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1160    switch_lang_to($language);
1161  }
1162  else
1163  {
1164// And switch gallery to this language before using personalized and multilangual contents
1165// ---------------------------------------------------------------------------------------
1166    //$language = $data['language']; // Usefull for debugging
1167    switch_lang_to($data['language']);
1168    load_language('plugin.lang', UAM_PATH);
1169  }
1170
1171  switch($typemail)
1172  {
1173    case 1: // Confirmation email on user registration - Without information email (already managed by Piwigo)
1174      if (isset($conf_UAM['CONFIRMMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_SUBJECT']))
1175      {
1176        // Management of Extension flags ([username], [mygallery])
1177        // -------------------------------------------------------
1178        $patterns[] = '#\[username\]#i';
1179        $replacements[] = $username;
1180        $patterns[] = '#\[mygallery\]#i';
1181        $replacements[] = $conf['gallery_title'];
1182
1183        if (function_exists('get_user_language_desc'))
1184        {
1185          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n";
1186        }
1187        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n"; 
1188      }
1189
1190      break;
1191
1192    case 2: // Confirmation email on user profile update - With information email if modification done in user profile
1193      if (isset($conf_UAM['CONFIRMMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_SUBJECT']))
1194      {
1195        // Management of Extension flags ([username], [mygallery])
1196        // -------------------------------------------------------
1197        $patterns[] = '#\[username\]#i';
1198        $replacements[] = $username;
1199        $patterns[] = '#\[mygallery\]#i';
1200        $replacements[] = $conf['gallery_title'];
1201
1202        if (function_exists('get_user_language_desc'))
1203        {
1204          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n";
1205        }
1206        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_SUBJECT']))."\n\n"; 
1207      }
1208
1209      $password = !empty($password) ? $password : l10n('UAM_empty_pwd');
1210
1211      if (isset($conf_UAM['MAILINFO_TEXT']) and !empty($conf_UAM['MAILINFO_TEXT']))
1212      {
1213        // Management of Extension flags ([username], [mygallery], [myurl])
1214        // ----------------------------------------------------------------
1215        $patterns[] = '#\[username\]#i';
1216        $replacements[] = $username;
1217        $patterns[] = '#\[mygallery\]#i';
1218        $replacements[] = $conf['gallery_title'];
1219        $patterns[] = '#\[myurl\]#i';
1220        $replacements[] = get_gallery_home_url();
1221
1222        if (function_exists('get_user_language_desc'))
1223        {
1224          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n";
1225        }
1226        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n"; 
1227      }
1228
1229      if (isset($conf_UAM['MAIL_INFO']) and $conf_UAM['MAIL_INFO'] == 'true')
1230      {
1231        if (isset($conf_UAM['HIDEPASSW']) and $conf_UAM['HIDEPASSW'] == 'true') // Allow display of clear password in email
1232        {
1233          $infos1 = array(
1234            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1235            get_l10n_args('UAM_User: %s', stripslashes($username)),
1236            get_l10n_args('UAM_Password: %s', $password),
1237            get_l10n_args('Email: %s', $email),
1238            get_l10n_args('', ''),
1239          );
1240        }
1241        else // Do not allow display of clear password in email
1242        {
1243          $infos1 = array(
1244            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1245            get_l10n_args('UAM_User: %s', stripslashes($username)),
1246            get_l10n_args('Email: %s', $email),
1247            get_l10n_args('', ''),
1248          );
1249        }
1250      }
1251
1252      break;
1253
1254    case 3: // Only information email send to user if checked
1255      if (isset($conf_UAM['INFOMAIL_SUBJECT']) and !empty($conf_UAM['INFOMAIL_SUBJECT']))
1256      {
1257        // Management of Extension flags ([username], [mygallery])
1258        // -------------------------------------------------------
1259        $patterns[] = '#\[username\]#i';
1260        $replacements[] = $username;
1261        $patterns[] = '#\[mygallery\]#i';
1262        $replacements[] = $conf['gallery_title'];
1263
1264        if (function_exists('get_user_language_desc'))
1265        {
1266          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['INFOMAIL_SUBJECT']))."\n\n";
1267        }
1268        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['INFOMAIL_SUBJECT']))."\n\n"; 
1269      }
1270
1271      $password = !empty($password) ? $password : l10n('UAM_no_update_pwd');
1272
1273      if (isset($conf_UAM['MAILINFO_TEXT']) and !empty($conf_UAM['MAILINFO_TEXT']))
1274      {
1275        // Management of Extension flags ([username], [mygallery], [myurl])
1276        // ----------------------------------------------------------------
1277        $patterns[] = '#\[username\]#i';
1278        $replacements[] = $username;
1279        $patterns[] = '#\[mygallery\]#i';
1280        $replacements[] = $conf['gallery_title'];
1281        $patterns[] = '#\[myurl\]#i';
1282        $replacements[] = get_gallery_home_url();
1283
1284        if (function_exists('get_user_language_desc'))
1285        {
1286          $infos1_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n";
1287        }
1288        else $infos1_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM['MAILINFO_TEXT']))."\n\n"; 
1289      }
1290
1291      if (isset($conf_UAM['MAIL_INFO']) and $conf_UAM['MAIL_INFO'] == 'true')
1292      {
1293        if (isset($conf_UAM['HIDEPASSW']) and $conf_UAM['HIDEPASSW'] == 'true') // Allow display of clear password in email
1294        {
1295          $infos1 = array(
1296            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1297            get_l10n_args('UAM_User: %s', stripslashes($username)),
1298            get_l10n_args('UAM_Password: %s', $password),
1299            get_l10n_args('Email: %s', $email),
1300            get_l10n_args('', ''),
1301          );
1302        }
1303        else // Do not allow display of clear password in email
1304        {
1305          $infos1 = array(
1306            get_l10n_args('UAM_infos_mail %s', stripslashes($username)),
1307            get_l10n_args('UAM_User: %s', stripslashes($username)),
1308            get_l10n_args('Email: %s', $email),
1309            get_l10n_args('', ''),
1310          );
1311        }
1312      }
1313
1314      break;
1315  }
1316
1317  if ((isset($conf_UAM['CONFIRM_MAIL']) and ($conf_UAM['CONFIRM_MAIL'] == 'true')) and $confirm) // Add confirmation link ?
1318  {
1319    $infos2 = array(
1320      get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
1321      get_l10n_args('', ''),
1322    );
1323
1324    if (isset($conf_UAM['CONFIRMMAIL_TEXT']) and !empty($conf_UAM['CONFIRMMAIL_TEXT'])) // Add personal text in confirmation email ?
1325    {
1326      // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1327      // -------------------------------------------------------------------------
1328      $patterns[] = '#\[username\]#i';
1329      $replacements[] = $username;
1330      $patterns[] = '#\[mygallery\]#i';
1331      $replacements[] = $conf['gallery_title'];
1332      $patterns[] = '#\[myurl\]#i';
1333      $replacements[] = get_gallery_home_url();
1334
1335      if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT'] == 'true') // [Kdays] replacement only if related option is active
1336      {
1337        $patterns[] = '#\[Kdays\]#i';
1338        $replacements[] = $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'];
1339      }
1340
1341      if (function_exists('get_user_language_desc'))
1342      {
1343        $infos2_perso = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_TEXT']))."\n\n";
1344      }
1345      else $infos2_perso = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_TEXT']))."\n\n";
1346    }
1347  }
1348
1349// Sending the email with subject and contents
1350// -------------------------------------------
1351  if ((isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'local') and $confirm)
1352        {
1353    switch_lang_to(get_default_language());
1354
1355        load_language('plugin.lang', UAM_PATH);
1356        $subject = get_l10n_args('UAM_Subject admin validation for %s',$username);
1357
1358                $content = array(
1359         get_l10n_args('UAM_Manual_validation_needed_for %s', stripslashes($username)),
1360     get_l10n_args('', ''),
1361     get_l10n_args('UAM_Link: %s', AddConfirmMail($id, $email)),
1362    );
1363
1364    UAM_mail_notification_admins($subject, $content);
1365  }
1366        elseif ((isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true') and $confirm)
1367        {
1368    pwg_mail($email, array(
1369      'subject' => $subject,
1370        'content' => (isset($infos1) ? $infos1_perso.l10n_args($infos1)."\n\n" : "").(isset($infos2) ? $infos2_perso.l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1371    ));
1372        }
1373// Switching back to default language
1374// ----------------------------------
1375switch_lang_back();
1376}
1377
1378
1379/**
1380 * Function called from SendMail2User in functions.inc.php to notify admins on user registration validation with validation key
1381 *
1382 * @param:
1383 *   - keyargs_subject: mail subject on l10n_args format
1384 *   - keyargs_content: mail content on l10n_args format
1385 *
1386 * @return boolean (Ok or not)
1387 */
1388function UAM_mail_notification_admins($keyargs_subject, $keyargs_content)
1389{
1390  global $conf, $user;
1391
1392  // Check arguments
1393  if (empty($keyargs_subject) or empty($keyargs_content))
1394  {
1395    return false;
1396  }
1397
1398  $return = true;
1399
1400  $admins = array();
1401
1402  $query = '
1403SELECT
1404    u.username AS username,
1405    u.mail_address AS mail_address
1406  FROM '.USERS_TABLE.' AS u
1407    JOIN '.USER_INFOS_TABLE.' AS i ON i.user_id = id
1408  WHERE i.status in (\'webmaster\',  \'admin\')
1409    AND mail_address IS NOT NULL
1410    AND i.user_id = id
1411  ORDER BY username
1412;';
1413
1414  $datas = pwg_query($query);
1415  if (!empty($datas))
1416  {
1417    while ($admin = pwg_db_fetch_assoc($datas))
1418    {
1419      if (!empty($admin['mail_address']))
1420      {
1421        array_push($admins, format_email($admin['username'], $admin['mail_address']));
1422      }
1423    }
1424  }
1425
1426  if (count($admins) > 0)
1427  {
1428    $content = l10n_args($keyargs_content)."\n";
1429
1430    $return = pwg_mail(
1431      implode(', ', $admins),
1432      array(
1433        'subject' => '['.$conf['gallery_title'].'] '.l10n_args($keyargs_subject),
1434        'content' => $content,
1435        'content_format' => 'text/plain',
1436        'email_format' => 'text/plain',
1437        )
1438      );
1439  }
1440
1441  return $return;
1442}
1443
1444
1445/**
1446 * Function called from UAM_admin.php to resend validation email with or without new validation key
1447 *
1448 * @param : Type of email, user id, username, email address, confirmation (optional)
1449 *
1450 */
1451function ResendMail2User($typemail, $user_id, $username, $email, $confirm)
1452{
1453  global $conf;
1454 
1455  $subject = "";
1456
1457  $conf_UAM = unserialize($conf['UserAdvManager']);
1458
1459  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
1460 
1461  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1462 
1463// We have to get the user's language in database
1464// ----------------------------------------------
1465  $query ='
1466SELECT user_id, language
1467FROM '.USER_INFOS_TABLE.'
1468WHERE user_id = '.$user_id.'
1469;';
1470  $data = pwg_db_fetch_assoc(pwg_query($query));
1471  $language = $data['language'];
1472
1473// And switch gallery to this language before using personalized and multilangual contents
1474// ---------------------------------------------------------------------------------------
1475  switch_lang_to($data['language']);
1476
1477  load_language('plugin.lang', UAM_PATH);
1478
1479  switch($typemail)
1480  {
1481    case 1: //Generating email content for remind with a new key
1482      if (isset($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))
1483      {
1484        // Management of Extension flags ([username], [mygallery])
1485        // -------------------------------------------------------
1486        $patterns[] = '#\[username\]#i';
1487        $replacements[] = $username;
1488        $patterns[] = '#\[mygallery\]#i';
1489        $replacements[] = $conf['gallery_title'];
1490
1491        if (function_exists('get_user_language_desc'))
1492        {
1493          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n";
1494        }
1495        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n"; 
1496      }
1497
1498      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)
1499      {
1500                // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1501        // -------------------------------------------------------------------------
1502        $patterns[] = '#\[username\]#i';
1503        $replacements[] = $username;
1504        $patterns[] = '#\[mygallery\]#i';
1505        $replacements[] = $conf['gallery_title'];
1506        $patterns[] = '#\[myurl\]#i';
1507        $replacements[] = get_gallery_home_url();
1508
1509        if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT'] == 'true') // [Kdays] replacement only if related option is active
1510        {
1511          $patterns[] = '#\[Kdays\]#i';
1512          $replacements[] = $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'];
1513        }
1514
1515        if (function_exists('get_user_language_desc'))
1516        {
1517          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT1']))."\n\n";
1518        }
1519                                else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT1']))."\n\n";
1520
1521        $infos2 = array
1522        (
1523          get_l10n_args('UAM_Link: %s', ResetConfirmMail($user_id)),
1524          get_l10n_args('', ''),
1525        );
1526      }
1527
1528// Set reminder true
1529// -----------------     
1530      $query = '
1531UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1532SET reminder = "true"
1533WHERE user_id = '.$user_id.'
1534;';
1535      pwg_query($query);
1536
1537      break;
1538
1539    case 2: //Generating email content for remind without a new key
1540      if (isset($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']) and !empty($conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))
1541      {
1542        // Management of Extension flags ([username], [mygallery])
1543        // -------------------------------------------------------
1544        $patterns[] = '#\[username\]#i';
1545        $replacements[] = $username;
1546        $patterns[] = '#\[mygallery\]#i';
1547        $replacements[] = $conf['gallery_title'];
1548   
1549        if (function_exists('get_user_language_desc'))
1550        {
1551          $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n";
1552        }
1553        else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['CONFIRMMAIL_REMAIL_SUBJECT']))."\n\n"; 
1554      }
1555
1556      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)
1557      {
1558        // Management of Extension flags ([username], [mygallery], [myurl], [Kdays])
1559        // -------------------------------------------------------------------------
1560        $patterns[] = '#\[username\]#i';
1561        $replacements[] = $username;
1562        $patterns[] = '#\[mygallery\]#i';
1563        $replacements[] = $conf['gallery_title'];
1564        $patterns[] = '#\[myurl\]#i';
1565        $replacements[] = get_gallery_home_url();
1566
1567        if (isset($conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT']) and $conf_UAM_ConfirmMail['CONFIRMMAIL_TIMEOUT'] == 'true') // [Kdays] replacement only if related option is active
1568        {
1569          $patterns[] = '#\[Kdays\]#i';
1570          $replacements[] = $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'];
1571        }
1572
1573        if (function_exists('get_user_language_desc'))
1574        {
1575          $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT2']))."\n\n";
1576        }
1577        else $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM_ConfirmMail['CONFIRMMAIL_REMAIL_TXT2']))."\n\n";
1578      }
1579
1580// Set reminder true
1581// -----------------
1582      $query = '
1583UPDATE '.USER_CONFIRM_MAIL_TABLE.'
1584SET reminder = "true"
1585WHERE user_id = '.$user_id.'
1586;';
1587      pwg_query($query);
1588     
1589    break;
1590        }
1591 
1592  pwg_mail($email, array(
1593    'subject' => $subject,
1594    'content' => ($infos1."\n\n").(isset($infos2) ? l10n_args($infos2)."\n\n" : "").get_absolute_root_url(),
1595  ));
1596
1597                // Switching back to default language
1598                // ----------------------------------
1599                switch_lang_back();
1600}
1601
1602
1603/**
1604 * Function called from UAM_admin.php to send a reminder mail for ghost users
1605 *
1606 * @param : User id, username, email address
1607 *
1608 */
1609function ghostreminder($user_id, $username, $email)
1610{
1611  global $conf;
1612
1613  $conf_UAM = unserialize($conf['UserAdvManager']);
1614  $subject = "";
1615
1616  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1617
1618// We have to get the user's language in database
1619// ----------------------------------------------
1620  $query ='
1621SELECT user_id, language
1622FROM '.USER_INFOS_TABLE.'
1623WHERE user_id = '.$user_id.'
1624;';
1625  $data = pwg_db_fetch_assoc(pwg_query($query));
1626  $language = $data['language'];
1627
1628// And switch gallery to this language before using personalized and multilangual contents
1629// ---------------------------------------------------------------------------------------
1630  switch_lang_to($data['language']);
1631
1632  load_language('plugin.lang', UAM_PATH);
1633
1634  if (isset($conf_UAM['GTREMINDER_SUBJECT']) and !empty($conf_UAM['GTREMINDER_SUBJECT']))
1635  {
1636    // Management of Extension flags ([username], [mygallery])
1637    // -------------------------------------------------------
1638    $patterns[] = '#\[username\]#i';
1639    $replacements[] = $username;
1640    $patterns[] = '#\[mygallery\]#i';
1641    $replacements[] = $conf['gallery_title'];
1642
1643    if (function_exists('get_user_language_desc'))
1644    {
1645      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTREMINDER_SUBJECT']))."\n\n";
1646    }
1647    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTREMINDER_SUBJECT']))."\n\n"; 
1648  }
1649
1650  if (isset($conf_UAM['GHOSTRACKER_REMINDERTEXT']) and !empty($conf_UAM['GHOSTRACKER_REMINDERTEXT']) and isset($conf_UAM['GHOSTRACKER']) and $conf_UAM['GHOSTRACKER'] == 'true')
1651  {
1652    // Management of Extension flags ([username], [mygallery], [myurl], [days])
1653    // ------------------------------------------------------------------------
1654    $patterns[] = '#\[username\]#i';
1655    $replacements[] = $username;
1656    $patterns[] = '#\[mygallery\]#i';
1657    $replacements[] = $conf['gallery_title'];
1658    $patterns[] = '#\[myurl\]#i';
1659    $replacements[] = get_gallery_home_url();
1660    $patterns[] = '#\[days\]#i';
1661    $replacements[] = $conf_UAM['GHOSTRACKER_DAYLIMIT'];
1662
1663    if (function_exists('get_user_language_desc'))
1664    {
1665      $infos1 = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GHOSTRACKER_REMINDERTEXT']))."\n\n";
1666    }
1667    else
1668    {
1669      $infos1 = l10n(preg_replace($patterns, $replacements, $conf_UAM['GHOSTRACKER_REMINDERTEXT']))."\n\n";
1670    }
1671
1672    resetlastvisit($user_id);
1673  }
1674
1675  pwg_mail($email, array(
1676    'subject' => $subject,
1677    'content' => $infos1.get_absolute_root_url(),
1678  ));
1679
1680                // Switching back to default language
1681                // ----------------------------------
1682                switch_lang_back();
1683}
1684
1685
1686/**
1687 * Function called from functions.inc.php to send notification email when user have been downgraded
1688 *
1689 * @param : user id, username, email address
1690 *
1691 */
1692function demotion_mail($id, $username, $email)
1693{
1694  global $conf;
1695
1696  $conf_UAM = unserialize($conf['UserAdvManager']);
1697
1698  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1699 
1700        $custom_txt = "";
1701        $subject = "";
1702
1703// We have to get the user's language in database
1704// ----------------------------------------------
1705  $query = '
1706SELECT user_id, language
1707FROM '.USER_INFOS_TABLE.'
1708WHERE user_id = '.$id.'
1709;';
1710
1711  $data = pwg_db_fetch_assoc(pwg_query($query));
1712
1713// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1714// -------------------------------------------------------------------------------------------------------------------------------
1715  if (empty($data))
1716  {
1717// And switch gallery to this language before using personalized and multilangual contents
1718// ---------------------------------------------------------------------------------------
1719    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1720    switch_lang_to($language);
1721  }
1722  else
1723  {
1724// And switch gallery to this language before using personalized and multilangual contents
1725// ---------------------------------------------------------------------------------------
1726    $language = $data['language']; // Usefull for debugging
1727    switch_lang_to($data['language']);
1728    load_language('plugin.lang', UAM_PATH);
1729  }
1730
1731  if (isset($conf_UAM['GTAUTOMAIL_SUBJECT']) and !empty($conf_UAM['GTAUTOMAIL_SUBJECT']))
1732  {
1733    // Management of Extension flags ([username], [mygallery])
1734    // -------------------------------------------------------
1735    $patterns[] = '#\[username\]#i';
1736    $replacements[] = $username;
1737    $patterns[] = '#\[mygallery\]#i';
1738    $replacements[] = $conf['gallery_title'];
1739
1740    if (function_exists('get_user_language_desc'))
1741    {
1742      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAIL_SUBJECT']))."\n\n";
1743    }
1744    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAIL_SUBJECT']))."\n\n"; 
1745  }
1746
1747  if (isset($conf_UAM['GTAUTOMAILTEXT']) and !empty($conf_UAM['GTAUTOMAILTEXT']))
1748  {
1749    // Management of Extension flags ([username], [mygallery], [myurl])
1750    // ----------------------------------------------------------------
1751    $patterns[] = '#\[username\]#i';
1752    $replacements[] = stripslashes($username);
1753    $patterns[] = '#\[mygallery\]#i';
1754    $replacements[] = $conf['gallery_title'];
1755    $patterns[] = '#\[myurl\]#i';
1756    $replacements[] = get_gallery_home_url();
1757
1758    if (function_exists('get_user_language_desc'))
1759    {
1760      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAILTEXT']))."\n\n";
1761    }
1762    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM['GTAUTOMAILTEXT']))."\n\n"; 
1763  }
1764
1765  $infos1 = array(
1766    get_l10n_args('UAM_User: %s', stripslashes($username)),
1767    get_l10n_args('Email: %s', $email),
1768    get_l10n_args('', ''),
1769  );
1770
1771  $infos2 = array
1772  (
1773    get_l10n_args('UAM_Link: %s', ResetConfirmMail($id)),
1774    get_l10n_args('', ''),
1775  ); 
1776
1777  resetlastvisit($id);
1778
1779// Sending the email with subject and contents
1780// -------------------------------------------
1781  pwg_mail($email, array(
1782    'subject' => $subject,
1783    'content' => ($custom_txt.l10n_args($infos1)."\n\n".l10n_args($infos2)."\n\n").get_absolute_root_url(),
1784  ));
1785
1786                // Switching back to default language
1787                // ----------------------------------
1788                switch_lang_back();
1789}
1790
1791
1792/**
1793 * Function called from UAM_admin.php to send notification email when user registration have been manually validated by admin
1794 *
1795 * @param : user id
1796 *
1797 */
1798function validation_mail($id)
1799{
1800  global $conf;
1801
1802  $conf_UAM = unserialize($conf['UserAdvManager']);
1803
1804  include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
1805
1806        $custom_txt = "";
1807  $subject = "";
1808
1809// We have to get the user's language in database
1810// ----------------------------------------------
1811  $query ='
1812SELECT user_id, language
1813FROM '.USER_INFOS_TABLE.'
1814WHERE user_id = '.$id.'
1815;';
1816
1817  $data = pwg_db_fetch_assoc(pwg_query($query));
1818
1819// Check if user is already registered (profile changing) - If not (new registration), language is set to current gallery language
1820// -------------------------------------------------------------------------------------------------------------------------------
1821  if (empty($data))
1822  {
1823// And switch gallery to this language before using personalized and multilangual contents
1824// ---------------------------------------------------------------------------------------
1825    $language = pwg_get_session_var( 'lang_switch', $user['language'] );
1826    switch_lang_to($language);
1827  }
1828  else
1829  {
1830// And switch gallery to this language before using personalized and multilangual contents
1831// ---------------------------------------------------------------------------------------
1832    $language = $data['language']; // Usefull for debugging
1833    switch_lang_to($data['language']);
1834    load_language('plugin.lang', UAM_PATH);
1835  }
1836
1837// Retreive users email and user name from id
1838// ------------------------------------------
1839  $query ='
1840SELECT id, username, mail_address
1841FROM '.USERS_TABLE.'
1842WHERE id = '.$id.'
1843;';
1844
1845  $result = pwg_db_fetch_assoc(pwg_query($query));
1846
1847  if (isset($conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']) and !empty($conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']))
1848  {
1849    // Management of Extension flags ([username], [mygallery])
1850    // -------------------------------------------------------
1851    $patterns[] = '#\[username\]#i';
1852    $replacements[] = $result['username'];
1853    $patterns[] = '#\[mygallery\]#i';
1854    $replacements[] = $conf['gallery_title'];
1855
1856    if (function_exists('get_user_language_desc'))
1857    {
1858      $subject = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']))."\n\n";
1859    }
1860    else $subject = l10n(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL_SUBJECT']))."\n\n";
1861  }
1862
1863  if (isset($conf_UAM['ADMINVALIDATIONMAIL']) and !empty($conf_UAM['ADMINVALIDATIONMAIL']))
1864  {
1865    // Management of Extension flags ([username], [mygallery], [myurl])
1866    // ----------------------------------------------------------------
1867    $patterns[] = '#\[username\]#i';
1868    $replacements[] = $result['username'];
1869    $patterns[] = '#\[mygallery\]#i';
1870    $replacements[] = $conf['gallery_title'];
1871    $patterns[] = '#\[myurl\]#i';
1872    $replacements[] = get_gallery_home_url();
1873    if (function_exists('get_user_language_desc'))
1874    {
1875      $custom_txt = get_user_language_desc(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL']))."\n\n";
1876    }
1877    else $custom_txt = l10n(preg_replace($patterns, $replacements, $conf_UAM['ADMINVALIDATIONMAIL']))."\n\n";
1878  }
1879
1880  $infos = array(
1881    get_l10n_args('UAM_User: %s', stripslashes($result['username'])),
1882    get_l10n_args('Email: %s', $result['mail_address']),
1883    get_l10n_args('', ''),
1884  );
1885
1886// Sending the email with subject and contents
1887// -------------------------------------------
1888  pwg_mail($result['mail_address'], array(
1889    'subject' => $subject,
1890    'content' => (l10n_args($infos)."\n\n".$custom_txt),
1891  ));
1892
1893                // Switching back to default language
1894                // ----------------------------------
1895                switch_lang_back();
1896}
1897
1898
1899/**
1900 * Function called from functions AddConfirmMail and ResetConfirmMail for validation key generation
1901 *
1902 * @return : validation key
1903 *
1904 */
1905function FindAvailableConfirmMailID()
1906{
1907  while (true)
1908  {
1909    $id = generate_key(16);
1910
1911    $query = '
1912SELECT COUNT(*)
1913FROM '.USER_CONFIRM_MAIL_TABLE.'
1914WHERE id = "'.$id.'"
1915;';
1916    list($count) = pwg_db_fetch_row(pwg_query($query));
1917
1918    if ($count == 0)
1919      return $id;
1920  }
1921}
1922
1923
1924/**
1925 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
1926 *
1927 * @param : User id, email address
1928 *
1929 * @return : Build validation key in URL
1930 *
1931 */
1932function AddConfirmMail($user_id, $email)
1933{
1934  global $conf;
1935
1936  $conf_UAM = unserialize($conf['UserAdvManager']);
1937  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1938
1939  $dbnow = date("Y-m-d H:i:s");
1940
1941  if (isset($Confirm_Mail_ID))
1942  {
1943    $query = "
1944SELECT status
1945  FROM ".USER_INFOS_TABLE."
1946WHERE user_id = '".$user_id."'
1947;";
1948    list($status) = pwg_db_fetch_row(pwg_query($query));
1949
1950    // Insert $Confirm_Mail_ID in USER_CONFIRM_MAIL_TABLE
1951    $query = "
1952INSERT INTO ".USER_CONFIRM_MAIL_TABLE."
1953  (id, user_id, mail_address, status, date_check, reminder)
1954VALUES
1955  ('".$Confirm_Mail_ID."', '".$user_id."', '".$email."', '".$status."', null, 'false')
1956;";
1957    pwg_query($query);
1958
1959    // Set user permissions
1960    // --------------------
1961    SetPermission($user_id);
1962
1963    // Set UAM_validated field to false in #_users table
1964    // -------------------------------------------------
1965    SetUnvalidated($user_id);
1966
1967    if ($conf['guest_access'])
1968    {
1969      return(get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
1970    }
1971    else
1972    {
1973      return(get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
1974    }
1975  }
1976}
1977
1978
1979/**
1980 * Function called from UAM_Adduser() to set group/status/level to new users if manual validation is set
1981 *
1982 * @param : User id
1983 *
1984 *
1985 */
1986function SetPermission($user_id)
1987{
1988  global $conf;
1989
1990  $conf_UAM = unserialize($conf['UserAdvManager']);
1991
1992// Groups cleanup
1993// --------------
1994  $query = '
1995DELETE FROM '.USER_GROUP_TABLE.'
1996WHERE user_id = '.$user_id.'
1997  AND (
1998    group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
1999  OR
2000    group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2001  )
2002;';
2003
2004  pwg_query($query);
2005
2006  if ($conf_UAM['NO_CONFIRM_STATUS'] <> -1) // Set status
2007  {
2008    $query = '
2009UPDATE '.USER_INFOS_TABLE.'
2010SET status = "'.$conf_UAM['NO_CONFIRM_STATUS'].'"
2011WHERE user_id = '.$user_id.'
2012;';
2013
2014    pwg_query($query);
2015  }
2016
2017  if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Set group
2018  {
2019    $query = '
2020INSERT INTO '.USER_GROUP_TABLE.'
2021  (user_id, group_id)
2022VALUES
2023  ('.$user_id.', '.$conf_UAM['NO_CONFIRM_GROUP'].')
2024;';
2025
2026    pwg_query($query);
2027  }
2028
2029  if ($conf_UAM['NO_VALID_LEVEL'] <> -1) // Set privacy level
2030  {
2031    $query = '
2032INSERT INTO '.USER_INFOS_TABLE.'
2033  (user_id, level)
2034VALUES
2035  ('.$user_id.', "'.$conf_UAM['NO_VALID_LEVEL'].'")
2036;';
2037
2038    pwg_query($query);
2039  }
2040}
2041
2042
2043/**
2044 * Function called from UAM_admin.php to reset validation key
2045 *
2046 * @param : User id
2047 *
2048 * @return : Build validation key in URL
2049 *
2050 */
2051function ResetConfirmMail($user_id)
2052{
2053  global $conf;
2054
2055  $Confirm_Mail_ID = FindAvailableConfirmMailID();
2056
2057  $dbnow = date("Y-m-d H:i:s");
2058
2059  if (isset($Confirm_Mail_ID))
2060  { 
2061    $query = '
2062UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2063SET id = "'.$Confirm_Mail_ID.'"
2064WHERE user_id = '.$user_id.'
2065;';
2066
2067    pwg_query($query);
2068
2069    $query = '
2070UPDATE '.USER_INFOS_TABLE.'
2071SET registration_date = "'.$dbnow.'"
2072WHERE user_id = '.$user_id.'
2073;';
2074
2075    pwg_query($query);
2076
2077    if ( $conf['guest_access'] )
2078    {
2079      return(get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2080    }
2081    else
2082    {
2083      return(get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2084    }
2085  }
2086}
2087
2088
2089/**
2090 * Function called from functions.inc.php to reset last visit date after sending a reminder
2091 *
2092 * @param : User id
2093 *
2094 */
2095function resetlastvisit($user_id)
2096{
2097  global $conf;
2098
2099  $dbnow = date("Y-m-d H:i:s");
2100
2101  $query = '
2102UPDATE '.USER_LASTVISIT_TABLE.'
2103SET lastvisit = "'.$dbnow.'", reminder = "true"
2104WHERE user_id = '.$user_id.'
2105;';
2106
2107  pwg_query($query);
2108}
2109
2110
2111/**
2112 * Function called from main.inc.php - Triggered on user deletion
2113 *
2114 */
2115function DeleteConfirmMail($user_id)
2116{
2117  $query = '
2118DELETE FROM '.USER_CONFIRM_MAIL_TABLE.'
2119WHERE user_id = '.$user_id.'
2120;';
2121
2122  pwg_query($query);
2123}
2124
2125
2126/**
2127 * Function called from main.inc.php - Triggered on user deletion
2128 *
2129 */
2130function DeleteLastVisit($user_id)
2131{
2132  $query = '
2133DELETE FROM '.USER_LASTVISIT_TABLE.'
2134WHERE user_id = '.$user_id.'
2135;';
2136
2137  pwg_query($query);
2138}
2139
2140
2141/**
2142 * Function called from main.inc.php - Triggered on user deletion
2143 *
2144 * @param : User id
2145 *
2146 */
2147function DeleteRedir($user_id)
2148{
2149  $tab = array();
2150
2151  $query = '
2152SELECT value
2153FROM '.CONFIG_TABLE.'
2154WHERE param = "UserAdvManager_Redir"
2155;';
2156
2157  $tab = pwg_db_fetch_row(pwg_query($query));
2158
2159  $values = explode(',', $tab[0]);
2160
2161  unset($values[array_search($user_id, $values)]);
2162
2163  $query = '
2164UPDATE '.CONFIG_TABLE.'
2165SET value = "'.implode(',', $values).'"
2166WHERE param = "UserAdvManager_Redir";';
2167
2168  pwg_query($query);
2169}
2170
2171
2172/**
2173 * Function called from ConfirmMail.php to verify validation key used by user according time limit
2174 * Return true is key validation is OK else return false
2175 *
2176 * @param : User id
2177 *
2178 * @return : Bool
2179 *
2180 */
2181function VerifyConfirmMail($id)
2182{
2183  global $conf;
2184
2185  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2186
2187  $conf_UAM = unserialize($conf['UserAdvManager']);
2188
2189  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2190
2191  $query = '
2192SELECT COUNT(*)
2193FROM '.USER_CONFIRM_MAIL_TABLE.'
2194WHERE id = "'.$id.'"
2195;';
2196
2197  list($count) = pwg_db_fetch_row(pwg_query($query));
2198
2199  if ($count == 1)
2200  {
2201    $query = '
2202SELECT user_id, status, date_check
2203FROM '.USER_CONFIRM_MAIL_TABLE.'
2204WHERE id = "'.$id.'"
2205;';
2206    $data = pwg_db_fetch_assoc(pwg_query($query));
2207
2208    if (!empty($data) and isset($data['user_id']) and is_null($data['date_check']))
2209    {
2210      $query = '
2211SELECT registration_date
2212FROM '.USER_INFOS_TABLE.'
2213WHERE user_id = '.$data['user_id'].'
2214;';
2215
2216      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2217
2218//              Time limit process             
2219// ******************************************** 
2220      if (!empty($registration_date))
2221      {
2222        // Verify Confirmmail with time limit ON
2223                // -------------------------------------
2224                                if (isset ($conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']))
2225        {
2226                                  // Dates formating and compare
2227                        // ---------------------------
2228                                        $today = date("d-m-Y"); // Get today's date
2229                                        list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2230                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2231
2232                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2233                                        list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2234                                        $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2235
2236          $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps   
2237                                        $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2238
2239                                        // Condition with the value set for time limit
2240                        // -------------------------------------------
2241                                        if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If Nb of days is less than the limit set
2242          {
2243            $dbnow = date("Y-m-d H:i:s");
2244
2245                        // Update ConfirmMail table
2246                        // ------------------------
2247                                                $query = '
2248UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2249SET date_check="'.$dbnow.'", reminder="false"
2250WHERE id = "'.$id.'"
2251;';
2252                                                pwg_query($query);
2253
2254                        // Update LastVisit table - Force reminder field to false
2255                        // Usefull when a user has been automatically downgraded and revalidate its registration
2256                        // -------------------------------------------------------------------------------------
2257                                                $query = '
2258UPDATE '.USER_LASTVISIT_TABLE.'
2259SET reminder="false"
2260WHERE user_id = "'.$data['user_id'].'"
2261;';
2262                                                pwg_query($query);
2263     
2264                                                if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from unvalidated users group
2265                                                {
2266              $query = '
2267DELETE FROM '.USER_GROUP_TABLE.'
2268WHERE user_id = '.$data['user_id'].'
2269  AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2270;';
2271                                                        pwg_query($query);
2272            }
2273
2274                                                if ($conf_UAM['VALIDATED_GROUP'] <> -1) // Add user to validated users group
2275                                                {
2276              $query = '
2277INSERT INTO '.USER_GROUP_TABLE.'
2278  (user_id, group_id)
2279VALUES
2280  ('.$data['user_id'].', '.$conf_UAM['VALIDATED_GROUP'].')
2281;';
2282                                                        pwg_query($query);
2283            }
2284
2285                                                if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Change user's status
2286                                                {
2287              $query = '
2288UPDATE '.USER_INFOS_TABLE.'
2289SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2290WHERE user_id = '.$data['user_id'].'
2291;';
2292                                                        pwg_query($query);
2293            }
2294
2295                                                if ($conf_UAM['VALID_LEVEL'] <> -1) // Change user's privacy level
2296                                                {
2297              $query = '
2298UPDATE '.USER_INFOS_TABLE.'
2299SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2300WHERE user_id = '.$data['user_id'].'
2301;';
2302                                                        pwg_query($query);
2303            }
2304
2305                                                // Set UAM_validated field to True in #_users table
2306            SetValidated($data['user_id']);
2307
2308                                                // Refresh user's category cache
2309            // -----------------------------
2310                                                invalidate_user_cache();
2311
2312                                                return true;
2313          }
2314          elseif ($deltadays > $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If timelimit exeeds
2315          {
2316            return false;
2317          }
2318        }
2319        // Verify Confirmmail with time limit OFF
2320        // --------------------------------------
2321        else
2322        {
2323          $dbnow = date("Y-m-d H:i:s");
2324
2325          // Update ConfirmMail table
2326          // ------------------------
2327                                        $query = '
2328UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2329SET date_check="'.$dbnow.'"
2330WHERE id = "'.$id.'"
2331;';
2332                                        pwg_query($query);
2333
2334          // Update LastVisit table - Force reminder field to false
2335          // Usefull when a user has been automatically downgraded and revalidate its registration
2336          // -------------------------------------------------------------------------------------
2337          $query = '
2338UPDATE '.USER_LASTVISIT_TABLE.'
2339SET reminder="false"
2340WHERE user_id = "'.$data['user_id'].'"
2341;';
2342          pwg_query($query);
2343
2344          if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from unvalidated users group
2345          {
2346            $query = '
2347DELETE FROM '.USER_GROUP_TABLE.'
2348WHERE user_id = '.$data['user_id'].'
2349AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2350;';
2351            pwg_query($query);
2352          }
2353
2354          if ($conf_UAM['VALIDATED_GROUP'] <> -1)
2355          {
2356            $query = '
2357DELETE FROM '.USER_GROUP_TABLE.'
2358WHERE user_id = '.$data['user_id'].'
2359AND group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2360;';
2361            pwg_query($query);
2362
2363            $query = '
2364INSERT INTO '.USER_GROUP_TABLE.'
2365  (user_id, group_id)
2366VALUES
2367  ('.$data['user_id'].', '.$conf_UAM['VALIDATED_GROUP'].')
2368;';
2369            pwg_query($query);
2370          }
2371
2372          if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Change user's status
2373          {
2374            $query = '
2375UPDATE '.USER_INFOS_TABLE.'
2376SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2377WHERE user_id = '.$data['user_id'].'
2378;';
2379            pwg_query($query);
2380          }
2381
2382          if ($conf_UAM['VALID_LEVEL'] <> -1) // Change user's privacy level
2383          {
2384            $query = '
2385UPDATE '.USER_INFOS_TABLE.'
2386SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2387WHERE user_id = '.$data['user_id'].'
2388;';
2389            pwg_query($query);
2390          }
2391
2392          // Set UAM_validated field to True in #_users table
2393          SetValidated($data['user_id']);
2394
2395          // Refresh user's category cache
2396          // -----------------------------
2397          invalidate_user_cache();
2398
2399          return true;
2400        }
2401      }
2402    }
2403    else if (!empty($data) and !is_null($data['date_check']))
2404    {
2405      return false;
2406    }
2407  }
2408  else
2409    return false;
2410}
2411
2412
2413/**
2414 * Function called from UAM_admin.php for manual validation by admin
2415 *
2416 * @param : User id
2417 *
2418 */
2419function ManualValidation($id)
2420{
2421                global $conf;
2422
2423                $conf_UAM = unserialize($conf['UserAdvManager']);
2424
2425                if (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true') // Set date of validation
2426                {
2427      $dbnow = date("Y-m-d H:i:s");
2428
2429                        $query = '
2430UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2431SET date_check="'.$dbnow.'"
2432WHERE user_id = '.$id.'
2433;';
2434                        pwg_query($query);
2435                }
2436
2437                if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from waiting group
2438                {
2439                                $query = '
2440DELETE FROM '.USER_GROUP_TABLE.'
2441WHERE user_id = '.$id.'
2442                AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2443;';
2444                                pwg_query($query);
2445                }
2446
2447                if ($conf_UAM['VALIDATED_GROUP'] <> -1) // Set user's valid group
2448                {
2449      $query = '
2450DELETE FROM '.USER_GROUP_TABLE.'
2451WHERE user_id = '.$id.'
2452                AND group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2453;';
2454      pwg_query($query);
2455
2456      $query = '
2457INSERT INTO '.USER_GROUP_TABLE.'
2458                (user_id, group_id)
2459VALUES
2460                ('.$id.', '.$conf_UAM['VALIDATED_GROUP'].')
2461;';
2462      pwg_query($query);
2463                }
2464
2465                if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Set user's valid status
2466                {
2467      $query = '
2468UPDATE '.USER_INFOS_TABLE.'
2469SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2470WHERE user_id = '.$id.'
2471;';
2472      pwg_query($query);
2473                }
2474
2475                if ($conf_UAM['VALID_LEVEL'] <> -1) // Set user's valid privacy level
2476                {
2477      $query = '
2478UPDATE '.USER_INFOS_TABLE.'
2479SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2480WHERE user_id = '.$id.'
2481;';
2482      pwg_query($query);
2483                }
2484
2485                // Set UAM_validated field to True in #_users table
2486                SetValidated($id);
2487}
2488
2489
2490/**
2491 * Function called from functions.inc.php - Check if username matches forbidden characters
2492 *
2493 * @param : User login
2494 *
2495 * @return : Bool
2496 *
2497 */
2498function ValidateUsername($login)
2499{
2500  global $conf;
2501
2502  $conf_UAM = unserialize($conf['UserAdvManager']);
2503
2504  if (isset($login) and isset($conf_UAM['USERNAME_CHAR_LIST']) and !empty($conf_UAM['USERNAME_CHAR_LIST']))
2505  {
2506    $conf_CharExclusion = preg_split("/,/",$conf_UAM['USERNAME_CHAR_LIST']);
2507    for ($i = 0 ; $i < count($conf_CharExclusion) ; $i++)
2508    {
2509      //Detect meta-characters (# ! ^ $ ( ) [ ] { } ? + * . \ -) for special pattern
2510      if ($conf_CharExclusion[$i] == "#"
2511       or $conf_CharExclusion[$i] == "$"
2512       or $conf_CharExclusion[$i] == "!"
2513       or $conf_CharExclusion[$i] == "^"
2514       or $conf_CharExclusion[$i] == "*"
2515       or $conf_CharExclusion[$i] == "?"
2516       or $conf_CharExclusion[$i] == "+"
2517       or $conf_CharExclusion[$i] == "."
2518       or $conf_CharExclusion[$i] == "\\"
2519       or $conf_CharExclusion[$i] == "|"
2520       or $conf_CharExclusion[$i] == "["
2521       or $conf_CharExclusion[$i] == "]"
2522       or $conf_CharExclusion[$i] == "("
2523       or $conf_CharExclusion[$i] == ")"
2524       or $conf_CharExclusion[$i] == "{"
2525       or $conf_CharExclusion[$i] == "}"
2526       or $conf_CharExclusion[$i] == "-")
2527      {
2528        $pattern = '/[][^$.\*+?(){}#|-]/i';
2529      }
2530      else
2531      {
2532        $pattern = '/'.$conf_CharExclusion[$i].'/i';
2533      }
2534
2535      if (preg_match($pattern, $login))
2536      {
2537        return true;
2538      }
2539    }
2540  }
2541  else
2542  {
2543    return false;
2544  }
2545}
2546
2547
2548/**
2549 * Function called from main.inc.php - Check if user's email is in excluded email providers list
2550 * Doesn't work on call - Must be copied in main.inc.php to work
2551 *
2552 * @param : Email address
2553 *
2554 * @return : Bool
2555 *
2556 */
2557function ValidateEmailProvider($email)
2558{
2559  global $conf;
2560
2561  $conf_UAM = unserialize($conf['UserAdvManager']);
2562
2563                if (isset($email) and isset($conf_UAM['MAILEXCLUSION_LIST']) and !empty($conf_UAM['MAILEXCLUSION_LIST']))
2564                {
2565      $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM['MAILEXCLUSION_LIST']);
2566      for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
2567      {
2568        $pattern = '/'.$conf_MailExclusion[$i].'/i';
2569        if (preg_match($pattern, $email))
2570        {
2571          return true;
2572        }
2573      }
2574    }
2575    else
2576    {
2577      return false;
2578    }
2579}
2580
2581
2582/**
2583 * Function called from UAM_admin.php - Get unvalidated users according time limit
2584 *
2585 * @return : List of users
2586 *
2587 */
2588function get_unvalid_user_list()
2589{
2590  global $conf, $page;
2591
2592  // Get ConfirmMail configuration
2593  // -----------------------------
2594  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2595  // Get UAM configuration
2596  // ---------------------
2597  $conf_UAM = unserialize($conf['UserAdvManager']);
2598
2599  $users = array();
2600
2601  // Search users depending expiration date
2602  // --------------------------------------
2603  $query = '
2604SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2605                u.'.$conf['user_fields']['username'].' AS username,
2606                u.'.$conf['user_fields']['email'].' AS email,
2607                ui.status,
2608                ui.enabled_high,
2609                ui.level,
2610                ui.registration_date
2611FROM '.USERS_TABLE.' AS u
2612  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2613    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2614  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
2615    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2616WHERE u.'.$conf['user_fields']['id'].' >= 3
2617  AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2618  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'"
2619  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'")
2620                AND u.UAM_validated = "false"
2621ORDER BY ui.registration_date ASC
2622;';
2623
2624  $result = pwg_query($query);
2625
2626  while ($row = pwg_db_fetch_assoc($result))
2627  {
2628    $user = $row;
2629    $user['groups'] = array();
2630
2631    array_push($users, $user);
2632  }
2633
2634  // Add groups list
2635  // ---------------
2636  $user_ids = array();
2637  foreach ($users as $i => $user)
2638  {
2639    $user_ids[$i] = $user['id'];
2640  }
2641
2642                $user_nums = array_flip($user_ids);
2643
2644  if (count($user_ids) > 0)
2645  {
2646    $query = '
2647SELECT user_id, group_id
2648  FROM '.USER_GROUP_TABLE.'
2649WHERE user_id IN ('.implode(',', $user_ids).')
2650;';
2651       
2652    $result = pwg_query($query);
2653       
2654    while ($row = pwg_db_fetch_assoc($result))
2655    {
2656      array_push(
2657        $users[$user_nums[$row['user_id']]]['groups'],
2658        $row['group_id']
2659      );
2660    }
2661  }
2662
2663  return $users;
2664}
2665
2666
2667/**
2668 * Function called from functions.inc.php - Get all users who haven't validate their registration in configured time
2669 * to delete or remail them automatically
2670 *
2671 * @return : List of users
2672 *
2673 */
2674function get_unvalid_user_autotasks()
2675{
2676  global $conf, $page;
2677
2678  // Get ConfirmMail configuration
2679  // -----------------------------
2680  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2681
2682  $users = array();
2683
2684  // search users depending expiration date
2685  // --------------------------------------
2686  $query = '
2687SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2688                ui.registration_date
2689FROM '.USERS_TABLE.' AS u
2690  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2691    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2692WHERE u.'.$conf['user_fields']['id'].' >= 3
2693  AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2694  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'")
2695ORDER BY ui.registration_date ASC;';
2696
2697  $result = pwg_query($query);
2698
2699  while ($row = pwg_db_fetch_assoc($result))
2700  {
2701    array_push($users, $row);
2702  }
2703
2704  return $users;
2705}
2706
2707
2708/**
2709 * Function called from UAM_admin.php - Get ghost users
2710 *
2711 * @return : List of users
2712 *
2713 */
2714function get_ghost_user_list()
2715{
2716  global $conf, $page;
2717
2718  $conf_UAM = unserialize($conf['UserAdvManager']);
2719
2720  $users = array();
2721
2722  // Search users depending expiration date
2723  // --------------------------------------
2724  $query = '
2725SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2726                u.'.$conf['user_fields']['username'].' AS username,
2727                u.'.$conf['user_fields']['email'].' AS email,
2728                lv.lastvisit,
2729                lv.reminder
2730FROM '.USERS_TABLE.' AS u
2731  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2732    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2733WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM['GHOSTRACKER_DAYLIMIT'].'")
2734AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2735ORDER BY lv.lastvisit ASC;';
2736
2737  $result = pwg_query($query);
2738     
2739  while ($row = pwg_db_fetch_assoc($result))
2740  {
2741    $user = $row;
2742    $user['groups'] = array();
2743
2744    array_push($users, $user);
2745  }
2746
2747  // Add groups list
2748  // ---------------
2749  $user_ids = array();
2750  foreach ($users as $i => $user)
2751  {
2752        $user_ids[$i] = $user['id'];
2753  }
2754
2755  return $users;
2756}
2757
2758
2759/**
2760 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
2761 *
2762 * @return : List of users to delete or downgrade automatically
2763 *
2764 */
2765function get_ghosts_autotasks()
2766{
2767  global $conf, $page;
2768
2769  $conf_UAM = unserialize($conf['UserAdvManager']);
2770
2771  $users = array();
2772 
2773  // Search users depending expiration date and reminder sent
2774  // --------------------------------------------------------
2775  $query = '
2776SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2777                lv.lastvisit
2778FROM '.USERS_TABLE.' AS u
2779  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2780    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2781WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM['GHOSTRACKER_DAYLIMIT'].'")
2782AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2783ORDER BY lv.lastvisit ASC;';
2784
2785  $result = pwg_query($query);
2786     
2787  while ($row = pwg_db_fetch_assoc($result))
2788  {
2789    array_push($users, $row);
2790  }
2791
2792  return $users;
2793}
2794
2795
2796/**
2797 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
2798 *
2799 * @return : List of users
2800 *
2801 */
2802function get_user_list()
2803{
2804  global $conf, $page;
2805
2806  $users = array();
2807
2808  // Search users depending expiration date with exclusion of Adult_Content generic users
2809  // ------------------------------------------------------------------------------------
2810  $query = '
2811SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2812                u.'.$conf['user_fields']['username'].' AS username,
2813                u.'.$conf['user_fields']['email'].' AS email,
2814                ug.lastvisit
2815FROM '.USERS_TABLE.' AS u
2816  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
2817    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2818WHERE u.'.$conf['user_fields']['id'].' >= 3
2819  AND u.'.$conf['user_fields']['id'].' <> '.$conf['default_user_id'].'
2820  AND u.username NOT LIKE "16"
2821  AND u.username NOT LIKE "18"
2822ORDER BY ug.lastvisit DESC
2823;';
2824
2825  $result = pwg_query($query);
2826     
2827  while ($row = pwg_db_fetch_assoc($result))
2828  {
2829    $user = $row;
2830    $user['groups'] = array();
2831
2832    array_push($users, $user);
2833  }
2834
2835  // Add groups list
2836  // ---------------
2837  $user_ids = array();
2838  foreach ($users as $i => $user)
2839  {
2840    $user_ids[$i] = $user['id'];
2841  }
2842
2843  return $users;
2844}
2845
2846
2847/**
2848 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
2849 *
2850 * @param : user id
2851 *
2852 * @return : Bool
2853 *
2854 */
2855function expiration($id)
2856{
2857        global $conf, $page;
2858
2859  // Get ConfirmMail configuration
2860  // -----------------------------
2861  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2862         
2863  // Get UAM configuration
2864  // ---------------------
2865  $conf_UAM = unserialize($conf['UserAdvManager']);
2866
2867  $query = '
2868SELECT registration_date
2869  FROM '.USER_INFOS_TABLE.'
2870WHERE user_id = '.$id.'
2871;';
2872  list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2873
2874//              Time limit process             
2875// ******************************************** 
2876  if (!empty($registration_date))
2877  {
2878    // Dates formating and compare
2879    // ---------------------------
2880    $today = date("d-m-Y"); // Get today's date
2881    list($day, $month, $year) = explode('-', $today); // explode date of today                                           
2882    $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2883
2884    list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2885    list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2886    $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2887
2888    $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps
2889    $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2890
2891    // Condition with the value set for time limit
2892    // -------------------------------------------
2893    if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If Nb of days is less than the limit set
2894    {
2895      return false;
2896    }
2897    else
2898    {
2899      return true;
2900    }
2901  }
2902}
2903
2904
2905/**
2906 * Returns a password's score for password complexity check
2907 *
2908 * @param : password filled by user
2909 *
2910 * @return : Score calculation
2911 *
2912 * Thanx to MathieuGut from http://m-gut.developpez.com
2913 */
2914function testpassword($password) // $password given by user
2915{
2916
2917  // Variables initiation
2918  // --------------------
2919  $points = 0;
2920  $point_lowercase = 0;
2921  $point_uppercase = 0;
2922  $point_numbers = 0;
2923  $point_characters = 0;
2924
2925  // Getting password lengh
2926  // ----------------------
2927  $length = strlen($password);
2928
2929  // Loop to read password characters
2930  for($i = 0; $i < $length; $i++)
2931  {
2932    // Select each letters
2933    // $i is 0 at first turn
2934    // ---------------------
2935    $letters = $password[$i];
2936
2937    if ($letters>='a' && $letters<='z')
2938    {
2939      // Adding 1 point to score for a lowercase
2940      // ---------------------------------------
2941                                $points = $points + 1;
2942
2943      // Adding bonus points for lowercase
2944      // ---------------------------------
2945                  $point_lowercase = 1;
2946    }
2947    else if ($letters>='A' && $letters <='Z')
2948    {
2949      // Adding 2 points to score for uppercase
2950      // --------------------------------------
2951      $points = $points + 2;
2952
2953      // Adding bonus points for uppercase
2954      // ---------------------------------
2955      $point_uppercase = 2;
2956    }
2957    else if ($letters>='0' && $letters<='9')
2958    {
2959      // Adding 3 points to score for numbers
2960      // ------------------------------------
2961      $points = $points + 3;
2962
2963      // Adding bonus points for numbers
2964      // -------------------------------
2965      $point_numbers = 3;
2966    }
2967    else
2968    {
2969      // Adding 5 points to score for special characters
2970      // -----------------------------------------------
2971      $points = $points + 5;
2972               
2973      // Adding bonus points for special characters
2974      // ------------------------------------------
2975      $point_characters = 5;
2976    }
2977  }
2978
2979  // Calculating the coefficient points/length
2980  // -----------------------------------------
2981  $step1 = $points / $length;
2982
2983  // Calculation of the diversity of character types...
2984  // --------------------------------------------------
2985  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
2986
2987  // Multiplying the coefficient of diversity with that of the length
2988  // ----------------------------------------------------------------
2989  $score = $step1 * $step2;
2990
2991  // Multiplying the result by the length of the string
2992  // --------------------------------------------------
2993  $finalscore = $score * $length;
2994
2995  return $finalscore;
2996}
2997
2998
2999/**
3000 * UAM_check_profile - Thx to LucMorizur
3001 * checks if a user id is registered as having already
3002 * visited his profile page.
3003 *
3004 * @uid        : the user id
3005 *
3006 * @user_idsOK : (returned) array of all users ids having already visited
3007 *               their profile.php pages
3008 *
3009 * @returns    : true or false whether the users has already visited his
3010 *               profile.php page or not
3011 *
3012 */
3013function UAM_check_profile($uid, &$user_idsOK)
3014{
3015  $t = array();
3016  $v = false;
3017
3018  $query = '
3019SELECT value
3020FROM '.CONFIG_TABLE.'
3021WHERE param = "UserAdvManager_Redir"
3022;';
3023
3024  if ($v = (($t = pwg_db_fetch_row(pwg_query($query))) !== false))
3025  {
3026    $user_idsOK = explode(',', $t[0]);
3027    $v = (in_array($uid, $user_idsOK));
3028  }
3029  return $v;
3030}
3031
3032
3033/**
3034 * UAM_check_pwdreset
3035 * checks if a user id is registered as having already
3036 * changed his password.
3037 *
3038 * @uid        : the user id
3039 *
3040 * @returns    : true or false whether the users has already changed his password
3041 *
3042 */
3043function UAM_check_pwgreset($uid)
3044{
3045  $query = '
3046SELECT UAM_pwdreset
3047FROM '.USERS_TABLE.'
3048WHERE id='.$uid.'
3049;';
3050
3051  $result = pwg_db_fetch_assoc(pwg_query($query));
3052
3053  if($result['UAM_pwdreset'] == 'true')
3054  {
3055    return true;
3056  }
3057  else return false; 
3058}
3059
3060
3061/**
3062 * UAM_UsrReg_Verif
3063 * Check if the user who logged-in have validate his registration
3064 *
3065 * @returns : True if validation is OK else False
3066 */
3067function UAM_UsrReg_Verif($user_id)
3068{
3069  global $conf;
3070
3071  $query = '
3072SELECT UAM_validated
3073FROM '.USERS_TABLE.'
3074WHERE id='.$user_id.'
3075;';
3076
3077  $result = pwg_db_fetch_assoc(pwg_query($query));
3078
3079  if($result['UAM_validated'] == 'true' or is_null($result['UAM_validated']))
3080  {
3081    return true;
3082  }
3083  else return false;
3084}
3085
3086
3087/**
3088 * SetUnvalidated
3089 * Set UAM_validated field to false in #_users table
3090 *
3091 **/
3092function SetUnvalidated($user_id)
3093{
3094  $query ='
3095UPDATE '.USERS_TABLE.'
3096SET UAM_validated = "false"
3097WHERE id = '.$user_id.'
3098LIMIT 1
3099;';
3100
3101  pwg_query($query);
3102}
3103
3104
3105/**
3106 * SetValidated
3107 * Set UAM_validated field to true in #_users table
3108 *
3109 **/
3110function SetValidated($user_id)
3111{
3112  $query ='
3113UPDATE '.USERS_TABLE.'
3114SET UAM_validated = "true"
3115WHERE id = '.$user_id.'
3116LIMIT 1
3117;';
3118
3119  pwg_query($query);
3120}
3121
3122
3123/**
3124 * UAM_Set_PwdReset
3125 * Action in user_list to set a password reset for a user
3126 */
3127function UAM_Set_PwdReset($uid)
3128{
3129  $query ='
3130UPDATE '.USERS_TABLE.'
3131SET UAM_pwdreset = "true"
3132WHERE id = '.$uid.'
3133LIMIT 1
3134;';
3135
3136  pwg_query($query);
3137}
3138
3139
3140/**
3141 * UAM_loc_visible_user_list
3142 * Adds a new feature in user_list to allow password reset for selected users by admin
3143 *
3144 */
3145function UAM_loc_visible_user_list($visible_user_list)
3146{
3147  global $template;
3148
3149  $template->append('plugin_user_list_column_titles', l10n('UAM_PwdReset'));
3150
3151  $user_ids = array();
3152
3153  foreach ($visible_user_list as $i => $user)
3154  {
3155    $user_ids[$i] = $user['id'];
3156  }
3157
3158  $user_nums = array_flip($user_ids);
3159
3160  // Query to get information in database
3161  // ------------------------------------
3162  if (!empty($user_ids))
3163  {
3164    $query = '
3165SELECT DISTINCT id, UAM_pwdreset
3166  FROM '.USERS_TABLE.'
3167  WHERE id IN ('.implode(',', $user_ids).')
3168;';
3169    $result = pwg_query($query);
3170
3171    while ($row = pwg_db_fetch_assoc($result))
3172    {
3173      if ($row['UAM_pwdreset'] == 'false')
3174      {
3175        $pwdreset = l10n('UAM_PwdReset_Done');
3176      }
3177      else if ($row['UAM_pwdreset'] == 'true')
3178      {
3179        $pwdreset = l10n('UAM_PwdReset_Todo');
3180      }
3181      else $pwdreset = l10n('UAM_PwdReset_NA');
3182
3183                  $visible_user_list[$user_nums[$row['id']]]['plugin_columns'][] = $pwdreset; // Shows users password state in user_list
3184    }
3185  }
3186  return $visible_user_list;
3187}
3188
3189
3190/**
3191 * UAM specific database dump (only for MySql !)
3192 * Creates an SQL dump of UAM specific tables and configuration settings
3193 *
3194 * @returns  : Boolean to manage appropriate message display
3195 *
3196 */
3197function UAM_dump($download)
3198{
3199  global $conf;
3200
3201  $plugin =  PluginInfos(UAM_PATH);
3202  $version = $plugin['version'];
3203
3204  // Initial backup folder creation and file initialisation
3205  // ------------------------------------------------------
3206  if (!is_dir(UAM_PATH.'/include/backup'))
3207    mkdir(UAM_PATH.'/include/backup');
3208
3209  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3210
3211  $fp = fopen($Backup_File, 'w');
3212
3213  // Writing plugin version
3214  $insertions = "-- ".$version." --\n\n";
3215  fwrite($fp, $insertions);
3216
3217  // Saving UAM specific tables
3218  // --------------------------
3219  $ListTables = array(USER_CONFIRM_MAIL_TABLE, USER_LASTVISIT_TABLE);
3220  $j=0;
3221
3222  while($j < count($ListTables))
3223  {
3224    $sql = 'SHOW CREATE TABLE '.$ListTables[$j];
3225    $res = pwg_query($sql);
3226
3227    if ($res)
3228    {
3229      $insertions = "-- -------------------------------------------------------\n";
3230      $insertions .= "-- Create ".$ListTables[$j]." table\n";
3231      $insertions .= "-- ------------------------------------------------------\n\n";
3232
3233      $insertions .= "DROP TABLE IF EXISTS ".$ListTables[$j].";\n\n";
3234
3235      $array = pwg_db_fetch_row($res);
3236      $array[1] .= ";\n\n";
3237      $insertions .= $array[1];
3238
3239      $req_table = pwg_query('DESCRIBE '.$ListTables[$j].';') or die(my_error());
3240      $nb_fields = pwg_db_num_rows($req_table);
3241      $req_table2 = pwg_query('SELECT * FROM '.$ListTables[$j]) or die(my_error());
3242
3243      while ($line = pwg_db_fetch_row($req_table2))
3244      {
3245        $insertions .= 'INSERT INTO '.$ListTables[$j].' VALUES (';
3246        for ($i=0; $i<$nb_fields; $i++)
3247        {
3248          $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3249        }
3250        $insertions = substr($insertions, 0, -2);
3251        $insertions .= ");\n";
3252      }
3253      $insertions .= "\n\n";
3254    }
3255
3256    fwrite($fp, $insertions);   
3257    $j++;
3258  }
3259
3260  // Saving UAM configuration
3261  // ------------------------
3262  $insertions = "-- -------------------------------------------------------\n";
3263  $insertions .= "-- Insert UAM configuration in ".CONFIG_TABLE."\n";
3264  $insertions .= "-- ------------------------------------------------------\n\n";
3265
3266  fwrite($fp, $insertions);
3267
3268  $pattern = "UserAdvManager%";
3269  $req_table = pwg_query('SELECT * FROM '.CONFIG_TABLE.' WHERE param LIKE "'.$pattern.'";') or die(my_error());
3270  $nb_fields = pwg_db_num_rows($req_table);
3271  $nb_fields = $nb_fields - 1;  // Fix the number of fields because pwg_db_num_rows() returns a bad number
3272
3273  while ($line = pwg_db_fetch_row($req_table))
3274  {
3275    $insertions = 'INSERT INTO '.CONFIG_TABLE.' VALUES (';
3276    for ($i=0; $i<$nb_fields; $i++)
3277    {
3278      $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3279    }
3280    $insertions = substr($insertions, 0, -2);
3281    $insertions .= ");\n";
3282
3283    fwrite($fp, $insertions);
3284  }
3285
3286  fclose($fp);
3287
3288  // Download generated dump file
3289  // ----------------------------
3290  if ($download == 'true')
3291  {
3292    if (@filesize($Backup_File))
3293    {
3294      $http_headers = array(
3295        'Content-Length: '.@filesize($Backup_File),
3296        'Content-Type: text/x-sql',
3297        'Content-Disposition: attachment; filename="UAM_dbbackup.sql";',
3298        'Content-Transfer-Encoding: binary',
3299        );
3300
3301      foreach ($http_headers as $header)
3302      {
3303        header($header);
3304      }
3305
3306      @readfile($Backup_File);
3307      exit();
3308    }
3309  }
3310
3311  return true;
3312}
3313
3314
3315/**
3316 * UAM_Restore_backup_file
3317 * Restore backup database file
3318 *
3319 * @returns : Boolean
3320 */
3321function UAM_Restore_backup_file() 
3322{
3323  global $prefixeTable, $dblayer, $conf;
3324
3325  define('DEFAULT_PREFIX_TABLE', 'piwigo_');
3326
3327  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3328
3329  // Cleanup database before restoring
3330  // ---------------------------------
3331
3332  // Delete UserAdvManager global config in #_config table
3333  $q = '
3334DELETE FROM '.CONFIG_TABLE.'
3335WHERE param="UserAdvManager"
3336;';
3337
3338  pwg_query($q);
3339
3340  // Delete UserAdvManager_ConfirmMail global config in #_config table
3341  $q = '
3342DELETE FROM '.CONFIG_TABLE.'
3343WHERE param="UserAdvManager_ConfirmMail"
3344;';
3345
3346  pwg_query($q);
3347
3348  // Delete UserAdvManager_Redir config in #_config table
3349  $q = '
3350DELETE FROM '.CONFIG_TABLE.'
3351WHERE param="UserAdvManager_Redir"
3352;';
3353
3354  pwg_query($q);
3355
3356  // Delete UserAdvManager_Version config in #_config table
3357  $q = '
3358DELETE FROM '.CONFIG_TABLE.'
3359WHERE param="UserAdvManager_Version"
3360;';
3361
3362  pwg_query($q);
3363
3364  // Restore sql backup file - DROP TABLE queries are executed
3365  // ---------------------------------------------------------
3366  UAM_execute_sqlfile(
3367    $Backup_File,
3368    DEFAULT_PREFIX_TABLE,
3369    $prefixeTable,
3370    $dblayer
3371  );
3372}
3373
3374
3375/**
3376 * loads an sql file and executes all queries / Based on Piwigo's original install file
3377 *
3378 * Before executing a query, $replaced is... replaced by $replacing. This is
3379 * useful when the SQL file contains generic words.
3380 *
3381 * @param string filepath
3382 * @param string replaced
3383 * @param string replacing
3384 * @return void
3385 */
3386function UAM_execute_sqlfile($filepath, $replaced, $replacing, $dblayer)
3387{
3388  $sql_lines = file($filepath);
3389  $query = '';
3390  foreach ($sql_lines as $sql_line)
3391  {
3392    $sql_line = trim($sql_line);
3393    if (preg_match('/(^--|^$)/', $sql_line))
3394    {
3395      continue;
3396    }
3397
3398    $query.= ' '.$sql_line;
3399
3400    // if we reached the end of query, we execute it and reinitialize the
3401    // variable "query"
3402    if (preg_match('/;$/', $sql_line))
3403    {
3404      $query = trim($query);
3405      $query = str_replace($replaced, $replacing, $query);
3406      if ('mysql' == $dblayer)
3407      {
3408        if (preg_match('/^(CREATE TABLE .*)[\s]*;[\s]*/im', $query, $matches))
3409        {
3410          $query = $matches[1].' DEFAULT CHARACTER SET utf8'.';';
3411        }
3412      }
3413      pwg_query($query);
3414      $query = '';
3415    }
3416  }
3417}
3418
3419
3420/**
3421 * Delete obsolete files on plugin upgrade
3422 * Obsolete files are listed in file obsolete.list
3423 *
3424 */
3425function clean_obsolete_files()
3426{
3427  if (file_exists(UAM_PATH.'obsolete.list')
3428    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
3429    and !empty($old_files))
3430  {
3431    array_push($old_files, 'obsolete.list');
3432    foreach($old_files as $old_file)
3433    {
3434      $path = UAM_PATH.$old_file;
3435      if (is_file($path))
3436      {
3437        @unlink($path);
3438      }
3439      elseif (is_dir($path))
3440      {
3441        @rmdir($path);
3442      }
3443    }
3444  }
3445}
3446
3447
3448/**
3449 * Function called from maintain.inc.php - to check if database upgrade is needed
3450 *
3451 * @param : table name
3452 *
3453 * @return : boolean
3454 *
3455 */
3456function table_exist($table)
3457{
3458  $query = 'DESC '.$table.';';
3459  return (bool)($res=pwg_query($query));
3460}
3461
3462
3463/**
3464 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
3465 *
3466 * @param : plugin directory
3467 *
3468 * @return : plugin's version and name
3469 *
3470 */
3471function PluginInfos($dir)
3472{
3473  $path = $dir;
3474
3475  $plg_data = implode( '', file($path.'main.inc.php') );
3476  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
3477  {
3478    $plugin['name'] = trim( $val[1] );
3479  }
3480  if (preg_match("|Version: (.*)|", $plg_data, $val))
3481  {
3482    $plugin['version'] = trim($val[1]);
3483  }
3484  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
3485  {
3486    $plugin['uri'] = trim($val[1]);
3487  }
3488  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
3489  {
3490    $plugin['description'] = trim($desc);
3491  }
3492  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
3493  {
3494    $plugin['description'] = trim($val[1]);
3495  }
3496  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
3497  {
3498    $plugin['author'] = trim($val[1]);
3499  }
3500  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
3501  {
3502    $plugin['author uri'] = trim($val[1]);
3503  }
3504  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
3505  {
3506    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
3507    if (is_numeric($extension)) $plugin['extension'] = $extension;
3508  }
3509// IMPORTANT SECURITY !
3510// --------------------
3511  $plugin = array_map('htmlspecialchars', $plugin);
3512
3513  return $plugin ;
3514}
3515
3516
3517/**
3518 * Useful for debugging - 4 vars can be set
3519 * Output result to log.txt file
3520 *
3521 */
3522function UAMLog($var1, $var2, $var3, $var4)
3523{
3524   $fo=fopen (UAM_PATH.'log.txt','a') ;
3525   fwrite($fo,"======================\n") ;
3526   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
3527   fwrite($fo,$var1 ."\r\n") ;
3528   fwrite($fo,$var2 ."\r\n") ;
3529   fwrite($fo,$var3 ."\r\n") ;
3530   fwrite($fo,$var4 ."\r\n") ;
3531   fclose($fo) ;
3532}
3533
3534?>
Note: See TracBrowser for help on using the repository browser.