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

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

Blocking bug fixed : New registrants could not validate their registration with the confirmation link
Next version is 2.50.1

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