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

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

Bug 2829 fixed - Workflow refactory if confirmation of registrations are done by admins :

  • Admins add manually user *and* confirmation of registration for admins is set to OFF -> new added users are considered automatically as validated.
  • Admins add manually user *and* confirmation of registration for admins is set to ON -> new added users receive the confirmation email.
  • Finally, if a user registers himself, admins receive the validation link.
  • Property svn:eol-style set to LF
File size: 101.1 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    $query = '
1907SELECT COUNT(*)
1908FROM '.USER_CONFIRM_MAIL_TABLE.'
1909WHERE id = "'.$id.'"
1910;';
1911    list($count) = pwg_db_fetch_row(pwg_query($query));
1912
1913    if ($count == 0)
1914      return $id;
1915  }
1916}
1917
1918
1919/**
1920 * Function called from functions SendMail2User to process unvalidated users and generate validation key link
1921 *
1922 * @param : User id, email address
1923 *
1924 * @return : Build validation key in URL
1925 *
1926 */
1927function AddConfirmMail($user_id, $email)
1928{
1929  global $conf;
1930
1931  $conf_UAM = unserialize($conf['UserAdvManager']);
1932  $Confirm_Mail_ID = FindAvailableConfirmMailID();
1933
1934  $dbnow = date("Y-m-d H:i:s");
1935
1936  if (isset($Confirm_Mail_ID))
1937  {
1938    // Set user permissions
1939    // --------------------
1940    SetPermission($user_id);
1941
1942    // Set UAM_validated field to false in #_users table
1943    // -------------------------------------------------
1944    SetUnvalidated($user_id);
1945
1946    if ($conf['guest_access'])
1947    {
1948      return(get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
1949    }
1950    else
1951    {
1952      return(get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
1953    }
1954  }
1955}
1956
1957
1958/**
1959 * Function called from UAM_Adduser() to set group/status/level to new users if manual validation is set
1960 *
1961 * @param : User id
1962 *
1963 *
1964 */
1965function SetPermission($user_id)
1966{
1967  global $conf;
1968
1969  $conf_UAM = unserialize($conf['UserAdvManager']);
1970
1971// Groups cleanup
1972// --------------
1973  $query = '
1974DELETE FROM '.USER_GROUP_TABLE.'
1975WHERE user_id = '.$user_id.'
1976  AND (
1977    group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
1978  OR
1979    group_id = '.$conf_UAM['VALIDATED_GROUP'].'
1980  )
1981;';
1982
1983  pwg_query($query);
1984
1985  if ($conf_UAM['NO_CONFIRM_STATUS'] <> -1) // Set status
1986  {
1987    $query = '
1988UPDATE '.USER_INFOS_TABLE.'
1989SET status = "'.$conf_UAM['NO_CONFIRM_STATUS'].'"
1990WHERE user_id = '.$user_id.'
1991;';
1992
1993    pwg_query($query);
1994  }
1995
1996  if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Set group
1997  {
1998    $query = '
1999INSERT INTO '.USER_GROUP_TABLE.'
2000  (user_id, group_id)
2001VALUES
2002  ('.$user_id.', '.$conf_UAM['NO_CONFIRM_GROUP'].')
2003;';
2004
2005    pwg_query($query);
2006  }
2007
2008  if ($conf_UAM['NO_VALID_LEVEL'] <> -1) // Set privacy level
2009  {
2010    $query = '
2011INSERT INTO '.USER_INFOS_TABLE.'
2012  (user_id, level)
2013VALUES
2014  ('.$user_id.', "'.$conf_UAM['NO_VALID_LEVEL'].'")
2015;';
2016
2017    pwg_query($query);
2018  }
2019}
2020
2021
2022/**
2023 * Function called from UAM_admin.php to reset validation key
2024 *
2025 * @param : User id
2026 *
2027 * @return : Build validation key in URL
2028 *
2029 */
2030function ResetConfirmMail($user_id)
2031{
2032  global $conf;
2033
2034  $Confirm_Mail_ID = FindAvailableConfirmMailID();
2035
2036  $dbnow = date("Y-m-d H:i:s");
2037
2038  if (isset($Confirm_Mail_ID))
2039  { 
2040    $query = '
2041UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2042SET id = "'.$Confirm_Mail_ID.'"
2043WHERE user_id = '.$user_id.'
2044;';
2045
2046    pwg_query($query);
2047
2048    $query = '
2049UPDATE '.USER_INFOS_TABLE.'
2050SET registration_date = "'.$dbnow.'"
2051WHERE user_id = '.$user_id.'
2052;';
2053
2054    pwg_query($query);
2055
2056    if ( $conf['guest_access'] )
2057    {
2058      return(get_absolute_root_url().'?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2059    }
2060    else
2061    {
2062      return(get_absolute_root_url().'identification.php?key='.$Confirm_Mail_ID.'&userid='.$user_id);
2063    }
2064  }
2065}
2066
2067
2068/**
2069 * Function called from functions.inc.php to reset last visit date after sending a reminder
2070 *
2071 * @param : User id
2072 *
2073 */
2074function resetlastvisit($user_id)
2075{
2076  global $conf;
2077
2078  $dbnow = date("Y-m-d H:i:s");
2079
2080  $query = '
2081UPDATE '.USER_LASTVISIT_TABLE.'
2082SET lastvisit = "'.$dbnow.'", reminder = "true"
2083WHERE user_id = '.$user_id.'
2084;';
2085
2086  pwg_query($query);
2087}
2088
2089
2090/**
2091 * Function called from main.inc.php - Triggered on user deletion
2092 *
2093 */
2094function DeleteConfirmMail($user_id)
2095{
2096  $query = '
2097DELETE FROM '.USER_CONFIRM_MAIL_TABLE.'
2098WHERE user_id = '.$user_id.'
2099;';
2100
2101  pwg_query($query);
2102}
2103
2104
2105/**
2106 * Function called from main.inc.php - Triggered on user deletion
2107 *
2108 */
2109function DeleteLastVisit($user_id)
2110{
2111  $query = '
2112DELETE FROM '.USER_LASTVISIT_TABLE.'
2113WHERE user_id = '.$user_id.'
2114;';
2115
2116  pwg_query($query);
2117}
2118
2119
2120/**
2121 * Function called from main.inc.php - Triggered on user deletion
2122 *
2123 * @param : User id
2124 *
2125 */
2126function DeleteRedir($user_id)
2127{
2128  $tab = array();
2129
2130  $query = '
2131SELECT value
2132FROM '.CONFIG_TABLE.'
2133WHERE param = "UserAdvManager_Redir"
2134;';
2135
2136  $tab = pwg_db_fetch_row(pwg_query($query));
2137
2138  $values = explode(',', $tab[0]);
2139
2140  unset($values[array_search($user_id, $values)]);
2141
2142  $query = '
2143UPDATE '.CONFIG_TABLE.'
2144SET value = "'.implode(',', $values).'"
2145WHERE param = "UserAdvManager_Redir";';
2146
2147  pwg_query($query);
2148}
2149
2150
2151/**
2152 * Function called from ConfirmMail.php to verify validation key used by user according time limit
2153 * Return true is key validation is OK else return false
2154 *
2155 * @param : User id
2156 *
2157 * @return : Bool
2158 *
2159 */
2160function VerifyConfirmMail($id)
2161{
2162  global $conf;
2163
2164  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
2165
2166  $conf_UAM = unserialize($conf['UserAdvManager']);
2167
2168  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2169
2170  $query = '
2171SELECT COUNT(*)
2172FROM '.USER_CONFIRM_MAIL_TABLE.'
2173WHERE id = "'.$id.'"
2174;';
2175
2176  list($count) = pwg_db_fetch_row(pwg_query($query));
2177
2178  if ($count == 1)
2179  {
2180    $query = '
2181SELECT user_id, status, date_check
2182FROM '.USER_CONFIRM_MAIL_TABLE.'
2183WHERE id = "'.$id.'"
2184;';
2185    $data = pwg_db_fetch_assoc(pwg_query($query));
2186
2187    if (!empty($data) and isset($data['user_id']) and is_null($data['date_check']))
2188    {
2189      $query = '
2190SELECT registration_date
2191FROM '.USER_INFOS_TABLE.'
2192WHERE user_id = '.$data['user_id'].'
2193;';
2194
2195      list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2196
2197//              Time limit process             
2198// ******************************************** 
2199      if (!empty($registration_date))
2200      {
2201        // Verify Confirmmail with time limit ON
2202                // -------------------------------------
2203                                if (isset ($conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']))
2204        {
2205                                  // Dates formating and compare
2206                        // ---------------------------
2207                                        $today = date("d-m-Y"); // Get today's date
2208                                        list($day, $month, $year) = explode('-', $today); // explode date of today                                               
2209                                        $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2210
2211                                list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2212                                        list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2213                                        $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2214
2215          $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps   
2216                                        $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2217
2218                                        // Condition with the value set for time limit
2219                        // -------------------------------------------
2220                                        if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If Nb of days is less than the limit set
2221          {
2222            $dbnow = date("Y-m-d H:i:s");
2223
2224                        // Update ConfirmMail table
2225                        // ------------------------
2226                                                $query = '
2227UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2228SET date_check="'.$dbnow.'", reminder="false"
2229WHERE id = "'.$id.'"
2230;';
2231                                                pwg_query($query);
2232
2233                        // Update LastVisit table - Force reminder field to false
2234                        // Usefull when a user has been automatically downgraded and revalidate its registration
2235                        // -------------------------------------------------------------------------------------
2236                                                $query = '
2237UPDATE '.USER_LASTVISIT_TABLE.'
2238SET reminder="false"
2239WHERE user_id = "'.$data['user_id'].'"
2240;';
2241                                                pwg_query($query);
2242     
2243                                                if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from unvalidated users group
2244                                                {
2245              $query = '
2246DELETE FROM '.USER_GROUP_TABLE.'
2247WHERE user_id = '.$data['user_id'].'
2248  AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2249;';
2250                                                        pwg_query($query);
2251            }
2252
2253                                                if ($conf_UAM['VALIDATED_GROUP'] <> -1) // Add user to validated users group
2254                                                {
2255              $query = '
2256INSERT INTO '.USER_GROUP_TABLE.'
2257  (user_id, group_id)
2258VALUES
2259  ('.$data['user_id'].', '.$conf_UAM['VALIDATED_GROUP'].')
2260;';
2261                                                        pwg_query($query);
2262            }
2263
2264                                                if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Change user's status
2265                                                {
2266              $query = '
2267UPDATE '.USER_INFOS_TABLE.'
2268SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2269WHERE user_id = '.$data['user_id'].'
2270;';
2271                                                        pwg_query($query);
2272            }
2273
2274                                                if ($conf_UAM['VALID_LEVEL'] <> -1) // Change user's privacy level
2275                                                {
2276              $query = '
2277UPDATE '.USER_INFOS_TABLE.'
2278SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2279WHERE user_id = '.$data['user_id'].'
2280;';
2281                                                        pwg_query($query);
2282            }
2283
2284                                                // Set UAM_validated field to True in #_users table
2285                                                $query = '
2286UPDATE '.USERS_TABLE.'
2287SET UAM_validated = "true"
2288WHERE id = '.$data['user_id'].'
2289;';
2290                                                pwg_query($query);
2291
2292                                                // Refresh user's category cache
2293            // -----------------------------
2294                                                invalidate_user_cache();
2295
2296                                                return true;
2297          }
2298          elseif ($deltadays > $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If timelimit exeeds
2299          {
2300            return false;
2301          }
2302        }
2303        // Verify Confirmmail with time limit OFF
2304        // --------------------------------------
2305        else
2306        {
2307          $dbnow = date("Y-m-d H:i:s");
2308
2309          // Update ConfirmMail table
2310          // ------------------------
2311                                        $query = '
2312UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2313SET date_check="'.$dbnow.'"
2314WHERE id = "'.$id.'"
2315;';
2316                                        pwg_query($query);
2317
2318          // Update LastVisit table - Force reminder field to false
2319          // Usefull when a user has been automatically downgraded and revalidate its registration
2320          // -------------------------------------------------------------------------------------
2321          $query = '
2322UPDATE '.USER_LASTVISIT_TABLE.'
2323SET reminder="false"
2324WHERE user_id = "'.$data['user_id'].'"
2325;';
2326          pwg_query($query);
2327
2328          if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from unvalidated users group
2329          {
2330            $query = '
2331DELETE FROM '.USER_GROUP_TABLE.'
2332WHERE user_id = '.$data['user_id'].'
2333AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2334;';
2335            pwg_query($query);
2336          }
2337
2338          if ($conf_UAM['VALIDATED_GROUP'] <> -1)
2339          {
2340            $query = '
2341DELETE FROM '.USER_GROUP_TABLE.'
2342WHERE user_id = '.$data['user_id'].'
2343AND group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2344;';
2345            pwg_query($query);
2346
2347            $query = '
2348INSERT INTO '.USER_GROUP_TABLE.'
2349  (user_id, group_id)
2350VALUES
2351  ('.$data['user_id'].', '.$conf_UAM['VALIDATED_GROUP'].')
2352;';
2353            pwg_query($query);
2354          }
2355
2356          if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Change user's status
2357          {
2358            $query = '
2359UPDATE '.USER_INFOS_TABLE.'
2360SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2361WHERE user_id = '.$data['user_id'].'
2362;';
2363            pwg_query($query);
2364          }
2365
2366          if ($conf_UAM['VALID_LEVEL'] <> -1) // Change user's privacy level
2367          {
2368            $query = '
2369UPDATE '.USER_INFOS_TABLE.'
2370SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2371WHERE user_id = '.$data['user_id'].'
2372;';
2373            pwg_query($query);
2374          }
2375
2376          // Set UAM_validated field to True in #_users table
2377          $query = '
2378UPDATE '.USERS_TABLE.'
2379SET UAM_validated = "true"
2380WHERE id = '.$data['user_id'].'
2381;';
2382          pwg_query($query);
2383
2384          // Refresh user's category cache
2385          // -----------------------------
2386          invalidate_user_cache();
2387
2388          return true;
2389        }
2390      }
2391    }
2392    else if (!empty($data) and !is_null($data['date_check']))
2393    {
2394      return false;
2395    }
2396  }
2397  else
2398    return false;
2399}
2400
2401
2402/**
2403 * Function called from UAM_admin.php for manual validation by admin
2404 *
2405 * @param : User id
2406 *
2407 */
2408function ManualValidation($id)
2409{
2410                global $conf;
2411
2412                $conf_UAM = unserialize($conf['UserAdvManager']);
2413
2414                if (isset($conf_UAM['CONFIRM_MAIL']) and $conf_UAM['CONFIRM_MAIL'] == 'true') // Set date of validation
2415                {
2416      $dbnow = date("Y-m-d H:i:s");
2417
2418                        $query = '
2419UPDATE '.USER_CONFIRM_MAIL_TABLE.'
2420SET date_check="'.$dbnow.'"
2421WHERE user_id = '.$id.'
2422;';
2423                        pwg_query($query);
2424                }
2425
2426                if ($conf_UAM['NO_CONFIRM_GROUP'] <> -1) // Delete user from waiting group
2427                {
2428                                $query = '
2429DELETE FROM '.USER_GROUP_TABLE.'
2430WHERE user_id = '.$id.'
2431                AND group_id = '.$conf_UAM['NO_CONFIRM_GROUP'].'
2432;';
2433                                pwg_query($query);
2434                }
2435
2436                if ($conf_UAM['VALIDATED_GROUP'] <> -1) // Set user's valid group
2437                {
2438      $query = '
2439DELETE FROM '.USER_GROUP_TABLE.'
2440WHERE user_id = '.$id.'
2441                AND group_id = '.$conf_UAM['VALIDATED_GROUP'].'
2442;';
2443      pwg_query($query);
2444
2445      $query = '
2446INSERT INTO '.USER_GROUP_TABLE.'
2447                (user_id, group_id)
2448VALUES
2449                ('.$id.', '.$conf_UAM['VALIDATED_GROUP'].')
2450;';
2451      pwg_query($query);
2452                }
2453
2454                if ($conf_UAM['VALIDATED_STATUS'] <> -1) // Set user's valid status
2455                {
2456      $query = '
2457UPDATE '.USER_INFOS_TABLE.'
2458SET status = "'.$conf_UAM['VALIDATED_STATUS'].'"
2459WHERE user_id = '.$id.'
2460;';
2461      pwg_query($query);
2462                }
2463
2464                if ($conf_UAM['VALID_LEVEL'] <> -1) // Set user's valid privacy level
2465                {
2466      $query = '
2467UPDATE '.USER_INFOS_TABLE.'
2468SET level = "'.$conf_UAM['VALID_LEVEL'].'"
2469WHERE user_id = '.$id.'
2470;';
2471      pwg_query($query);
2472                }
2473
2474                // Set UAM_validated field to True in #_users table
2475                $query = '
2476UPDATE '.USERS_TABLE.'
2477SET UAM_validated = "true"
2478WHERE id = '.$id.'
2479;';
2480                pwg_query($query);
2481}
2482
2483
2484/**
2485 * Function called from functions.inc.php - Check if username matches forbidden characters
2486 *
2487 * @param : User login
2488 *
2489 * @return : Bool
2490 *
2491 */
2492function ValidateUsername($login)
2493{
2494  global $conf;
2495
2496  $conf_UAM = unserialize($conf['UserAdvManager']);
2497
2498  if (isset($login) and isset($conf_UAM['USERNAME_CHAR_LIST']) and !empty($conf_UAM['USERNAME_CHAR_LIST']))
2499  {
2500    $conf_CharExclusion = preg_split("/,/",$conf_UAM['USERNAME_CHAR_LIST']);
2501    for ($i = 0 ; $i < count($conf_CharExclusion) ; $i++)
2502    {
2503      //Detect meta-characters (# ! ^ $ ( ) [ ] { } ? + * . \ -) for special pattern
2504      if ($conf_CharExclusion[$i] == "#"
2505       or $conf_CharExclusion[$i] == "$"
2506       or $conf_CharExclusion[$i] == "!"
2507       or $conf_CharExclusion[$i] == "^"
2508       or $conf_CharExclusion[$i] == "*"
2509       or $conf_CharExclusion[$i] == "?"
2510       or $conf_CharExclusion[$i] == "+"
2511       or $conf_CharExclusion[$i] == "."
2512       or $conf_CharExclusion[$i] == "\\"
2513       or $conf_CharExclusion[$i] == "|"
2514       or $conf_CharExclusion[$i] == "["
2515       or $conf_CharExclusion[$i] == "]"
2516       or $conf_CharExclusion[$i] == "("
2517       or $conf_CharExclusion[$i] == ")"
2518       or $conf_CharExclusion[$i] == "{"
2519       or $conf_CharExclusion[$i] == "}"
2520       or $conf_CharExclusion[$i] == "-")
2521      {
2522        $pattern = '/[][^$.\*+?(){}#|-]/i';
2523      }
2524      else
2525      {
2526        $pattern = '/'.$conf_CharExclusion[$i].'/i';
2527      }
2528
2529      if (preg_match($pattern, $login))
2530      {
2531        return true;
2532      }
2533    }
2534  }
2535  else
2536  {
2537    return false;
2538  }
2539}
2540
2541
2542/**
2543 * Function called from main.inc.php - Check if user's email is in excluded email providers list
2544 * Doesn't work on call - Must be copied in main.inc.php to work
2545 *
2546 * @param : Email address
2547 *
2548 * @return : Bool
2549 *
2550 */
2551function ValidateEmailProvider($email)
2552{
2553  global $conf;
2554
2555  $conf_UAM = unserialize($conf['UserAdvManager']);
2556
2557                if (isset($email) and isset($conf_UAM['MAILEXCLUSION_LIST']) and !empty($conf_UAM['MAILEXCLUSION_LIST']))
2558                {
2559      $conf_MailExclusion = preg_split("/[\s,]+/",$conf_UAM['MAILEXCLUSION_LIST']);
2560      for ($i = 0 ; $i < count($conf_MailExclusion) ; $i++)
2561      {
2562        $pattern = '/'.$conf_MailExclusion[$i].'/i';
2563        if (preg_match($pattern, $email))
2564        {
2565          return true;
2566        }
2567      }
2568    }
2569    else
2570    {
2571      return false;
2572    }
2573}
2574
2575
2576/**
2577 * Function called from UAM_admin.php - Get unvalidated users according time limit
2578 *
2579 * @return : List of users
2580 *
2581 */
2582function get_unvalid_user_list()
2583{
2584  global $conf, $page;
2585
2586  // Get ConfirmMail configuration
2587  // -----------------------------
2588  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2589  // Get UAM configuration
2590  // ---------------------
2591  $conf_UAM = unserialize($conf['UserAdvManager']);
2592
2593  $users = array();
2594
2595  // Search users depending expiration date
2596  // --------------------------------------
2597  $query = '
2598SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2599                u.'.$conf['user_fields']['username'].' AS username,
2600                u.'.$conf['user_fields']['email'].' AS email,
2601                ui.status,
2602                ui.enabled_high,
2603                ui.level,
2604                ui.registration_date
2605FROM '.USERS_TABLE.' AS u
2606  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2607    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2608  LEFT JOIN '.USER_GROUP_TABLE.' AS ug
2609    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2610WHERE u.'.$conf['user_fields']['id'].' >= 3
2611  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'"
2612  OR TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) < "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'")
2613                AND u.UAM_validated = "false"
2614ORDER BY ui.registration_date ASC
2615;';
2616
2617  $result = pwg_query($query);
2618
2619  while ($row = pwg_db_fetch_assoc($result))
2620  {
2621    $user = $row;
2622    $user['groups'] = array();
2623
2624    array_push($users, $user);
2625  }
2626
2627  // Add groups list
2628  // ---------------
2629  $user_ids = array();
2630  foreach ($users as $i => $user)
2631  {
2632    $user_ids[$i] = $user['id'];
2633  }
2634
2635                $user_nums = array_flip($user_ids);
2636
2637  if (count($user_ids) > 0)
2638  {
2639    $query = '
2640SELECT user_id, group_id
2641  FROM '.USER_GROUP_TABLE.'
2642WHERE user_id IN ('.implode(',', $user_ids).')
2643;';
2644       
2645    $result = pwg_query($query);
2646       
2647    while ($row = pwg_db_fetch_assoc($result))
2648    {
2649      array_push(
2650        $users[$user_nums[$row['user_id']]]['groups'],
2651        $row['group_id']
2652      );
2653    }
2654  }
2655
2656  return $users;
2657}
2658
2659
2660/**
2661 * Function called from functions.inc.php - Get all users who haven't validate their registration in configured time
2662 * to delete or remail them automatically
2663 *
2664 * @return : List of users
2665 *
2666 */
2667function get_unvalid_user_autotasks()
2668{
2669  global $conf, $page;
2670
2671  // Get ConfirmMail configuration
2672  // -----------------------------
2673  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2674
2675  $users = array();
2676
2677  // search users depending expiration date
2678  // --------------------------------------
2679  $query = '
2680SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2681                ui.registration_date
2682FROM '.USERS_TABLE.' AS u
2683  INNER JOIN '.USER_INFOS_TABLE.' AS ui
2684    ON u.'.$conf['user_fields']['id'].' = ui.user_id
2685WHERE u.'.$conf['user_fields']['id'].' >= 3
2686  AND (TO_DAYS(NOW()) - TO_DAYS(ui.registration_date) >= "'.$conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY'].'")
2687ORDER BY ui.registration_date ASC;';
2688
2689  $result = pwg_query($query);
2690
2691  while ($row = pwg_db_fetch_assoc($result))
2692  {
2693    array_push($users, $row);
2694  }
2695
2696  return $users;
2697}
2698
2699
2700/**
2701 * Function called from UAM_admin.php - Get ghost users
2702 *
2703 * @return : List of users
2704 *
2705 */
2706function get_ghost_user_list()
2707{
2708  global $conf, $page;
2709
2710  $conf_UAM = unserialize($conf['UserAdvManager']);
2711
2712  $users = array();
2713
2714  // Search users depending expiration date
2715  // --------------------------------------
2716  $query = '
2717SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2718                u.'.$conf['user_fields']['username'].' AS username,
2719                u.'.$conf['user_fields']['email'].' AS email,
2720                lv.lastvisit,
2721                lv.reminder
2722FROM '.USERS_TABLE.' AS u
2723  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2724    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2725WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM['GHOSTRACKER_DAYLIMIT'].'")
2726ORDER BY lv.lastvisit ASC;';
2727
2728  $result = pwg_query($query);
2729     
2730  while ($row = pwg_db_fetch_assoc($result))
2731  {
2732    $user = $row;
2733    $user['groups'] = array();
2734
2735    array_push($users, $user);
2736  }
2737
2738  // Add groups list
2739  // ---------------
2740  $user_ids = array();
2741  foreach ($users as $i => $user)
2742  {
2743        $user_ids[$i] = $user['id'];
2744  }
2745
2746  return $users;
2747}
2748
2749
2750/**
2751 * Function called from functions.inc.php - Get all ghost users to delete or downgrade automatically on any user login
2752 *
2753 * @return : List of users to delete or downgrade automatically
2754 *
2755 */
2756function get_ghosts_autotasks()
2757{
2758  global $conf, $page;
2759
2760  $conf_UAM = unserialize($conf['UserAdvManager']);
2761
2762  $users = array();
2763 
2764  // Search users depending expiration date and reminder sent
2765  // --------------------------------------------------------
2766  $query = '
2767SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2768                lv.lastvisit
2769FROM '.USERS_TABLE.' AS u
2770  INNER JOIN '.USER_LASTVISIT_TABLE.' AS lv
2771    ON u.'.$conf['user_fields']['id'].' = lv.user_id
2772WHERE (TO_DAYS(NOW()) - TO_DAYS(lv.lastvisit) >= "'.$conf_UAM['GHOSTRACKER_DAYLIMIT'].'")
2773ORDER BY lv.lastvisit ASC;';
2774
2775  $result = pwg_query($query);
2776     
2777  while ($row = pwg_db_fetch_assoc($result))
2778  {
2779    array_push($users, $row);
2780  }
2781
2782  return $users;
2783}
2784
2785
2786/**
2787 * Function called from UAM_admin.php - Get all users to display the number of days since their last visit
2788 *
2789 * @return : List of users
2790 *
2791 */
2792function get_user_list()
2793{
2794  global $conf, $page;
2795
2796  $users = array();
2797
2798  // Search users depending expiration date with exclusion of Adult_Content generic users
2799  // ------------------------------------------------------------------------------------
2800  $query = '
2801SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
2802                u.'.$conf['user_fields']['username'].' AS username,
2803                u.'.$conf['user_fields']['email'].' AS email,
2804                ug.lastvisit
2805FROM '.USERS_TABLE.' AS u
2806  INNER JOIN '.USER_LASTVISIT_TABLE.' AS ug
2807    ON u.'.$conf['user_fields']['id'].' = ug.user_id
2808WHERE u.'.$conf['user_fields']['id'].' >= 3
2809  AND u.username NOT LIKE "16"
2810  AND u.username NOT LIKE "18"
2811ORDER BY ug.lastvisit DESC
2812;';
2813
2814  $result = pwg_query($query);
2815     
2816  while ($row = pwg_db_fetch_assoc($result))
2817  {
2818    $user = $row;
2819    $user['groups'] = array();
2820
2821    array_push($users, $user);
2822  }
2823
2824  // Add groups list
2825  // ---------------
2826  $user_ids = array();
2827  foreach ($users as $i => $user)
2828  {
2829    $user_ids[$i] = $user['id'];
2830  }
2831
2832  return $users;
2833}
2834
2835
2836/**
2837 * Function called from UAM_admin.php - to determine who is expired or not and giving a different display color
2838 *
2839 * @param : user id
2840 *
2841 * @return : Bool
2842 *
2843 */
2844function expiration($id)
2845{
2846        global $conf, $page;
2847
2848  // Get ConfirmMail configuration
2849  // -----------------------------
2850  $conf_UAM_ConfirmMail = unserialize($conf['UserAdvManager_ConfirmMail']);
2851         
2852  // Get UAM configuration
2853  // ---------------------
2854  $conf_UAM = unserialize($conf['UserAdvManager']);
2855
2856  $query = '
2857SELECT registration_date
2858  FROM '.USER_INFOS_TABLE.'
2859WHERE user_id = '.$id.'
2860;';
2861  list($registration_date) = pwg_db_fetch_row(pwg_query($query));
2862
2863//              Time limit process             
2864// ******************************************** 
2865  if (!empty($registration_date))
2866  {
2867    // Dates formating and compare
2868    // ---------------------------
2869    $today = date("d-m-Y"); // Get today's date
2870    list($day, $month, $year) = explode('-', $today); // explode date of today                                           
2871    $daytimestamp = mktime(0, 0, 0, $month, $day, $year);// Generate UNIX timestamp
2872
2873    list($regdate, $regtime) = explode(' ', $registration_date); // Explode date and time from registration date
2874    list($regyear, $regmonth, $regday) = explode('-', $regdate); // Explode date from registration date
2875    $regtimestamp = mktime(0, 0, 0, $regmonth, $regday, $regyear);// Generate UNIX timestamp
2876
2877    $deltasecs = $daytimestamp - $regtimestamp;// Compare the 2 UNIX timestamps
2878    $deltadays = floor($deltasecs / 86400);// Convert result from seconds to days
2879
2880    // Condition with the value set for time limit
2881    // -------------------------------------------
2882    if ($deltadays <= $conf_UAM_ConfirmMail['CONFIRMMAIL_DELAY']) // If Nb of days is less than the limit set
2883    {
2884      return false;
2885    }
2886    else
2887    {
2888      return true;
2889    }
2890  }
2891}
2892
2893
2894/**
2895 * Returns a password's score for password complexity check
2896 *
2897 * @param : password filled by user
2898 *
2899 * @return : Score calculation
2900 *
2901 * Thanx to MathieuGut from http://m-gut.developpez.com
2902 */
2903function testpassword($password) // $password given by user
2904{
2905
2906  // Variables initiation
2907  // --------------------
2908  $points = 0;
2909  $point_lowercase = 0;
2910  $point_uppercase = 0;
2911  $point_numbers = 0;
2912  $point_characters = 0;
2913
2914  // Getting password lengh
2915  // ----------------------
2916  $length = strlen($password);
2917
2918  // Loop to read password characters
2919  for($i = 0; $i < $length; $i++)
2920  {
2921    // Select each letters
2922    // $i is 0 at first turn
2923    // ---------------------
2924    $letters = $password[$i];
2925
2926    if ($letters>='a' && $letters<='z')
2927    {
2928      // Adding 1 point to score for a lowercase
2929      // ---------------------------------------
2930                                $points = $points + 1;
2931
2932      // Adding bonus points for lowercase
2933      // ---------------------------------
2934                  $point_lowercase = 1;
2935    }
2936    else if ($letters>='A' && $letters <='Z')
2937    {
2938      // Adding 2 points to score for uppercase
2939      // --------------------------------------
2940      $points = $points + 2;
2941
2942      // Adding bonus points for uppercase
2943      // ---------------------------------
2944      $point_uppercase = 2;
2945    }
2946    else if ($letters>='0' && $letters<='9')
2947    {
2948      // Adding 3 points to score for numbers
2949      // ------------------------------------
2950      $points = $points + 3;
2951
2952      // Adding bonus points for numbers
2953      // -------------------------------
2954      $point_numbers = 3;
2955    }
2956    else
2957    {
2958      // Adding 5 points to score for special characters
2959      // -----------------------------------------------
2960      $points = $points + 5;
2961               
2962      // Adding bonus points for special characters
2963      // ------------------------------------------
2964      $point_characters = 5;
2965    }
2966  }
2967
2968  // Calculating the coefficient points/length
2969  // -----------------------------------------
2970  $step1 = $points / $length;
2971
2972  // Calculation of the diversity of character types...
2973  // --------------------------------------------------
2974  $step2 = $point_lowercase + $point_uppercase + $point_numbers + $point_characters;
2975
2976  // Multiplying the coefficient of diversity with that of the length
2977  // ----------------------------------------------------------------
2978  $score = $step1 * $step2;
2979
2980  // Multiplying the result by the length of the string
2981  // --------------------------------------------------
2982  $finalscore = $score * $length;
2983
2984  return $finalscore;
2985}
2986
2987
2988/**
2989 * UAM_check_profile - Thx to LucMorizur
2990 * checks if a user id is registered as having already
2991 * visited his profile page.
2992 *
2993 * @uid        : the user id
2994 *
2995 * @user_idsOK : (returned) array of all users ids having already visited
2996 *               their profile.php pages
2997 *
2998 * @returns    : true or false whether the users has already visited his
2999 *               profile.php page or not
3000 *
3001 */
3002function UAM_check_profile($uid, &$user_idsOK)
3003{
3004  $t = array();
3005  $v = false;
3006
3007  $query = '
3008SELECT value
3009FROM '.CONFIG_TABLE.'
3010WHERE param = "UserAdvManager_Redir"
3011;';
3012
3013  if ($v = (($t = pwg_db_fetch_row(pwg_query($query))) !== false))
3014  {
3015    $user_idsOK = explode(',', $t[0]);
3016    $v = (in_array($uid, $user_idsOK));
3017  }
3018  return $v;
3019}
3020
3021
3022/**
3023 * UAM_check_pwdreset
3024 * checks if a user id is registered as having already
3025 * changed his password.
3026 *
3027 * @uid        : the user id
3028 *
3029 * @returns    : true or false whether the users has already changed his password
3030 *
3031 */
3032function UAM_check_pwgreset($uid)
3033{
3034  $query = '
3035SELECT UAM_pwdreset
3036FROM '.USERS_TABLE.'
3037WHERE id='.$uid.'
3038;';
3039
3040  $result = pwg_db_fetch_assoc(pwg_query($query));
3041
3042  if($result['UAM_pwdreset'] == 'true')
3043  {
3044    return true;
3045  }
3046  else return false; 
3047}
3048
3049
3050/**
3051 * UAM_UsrReg_Verif
3052 * Check if the user who logged-in have validate his registration
3053 *
3054 * @returns : True if validation is OK else False
3055 */
3056function UAM_UsrReg_Verif($user_id)
3057{
3058  global $conf;
3059
3060  $query = '
3061SELECT UAM_validated
3062FROM '.USERS_TABLE.'
3063WHERE id='.$user_id.'
3064;';
3065
3066  $result = pwg_db_fetch_assoc(pwg_query($query));
3067
3068  if($result['UAM_validated'] == 'true')
3069  {
3070    return true;
3071  }
3072  else return false;
3073}
3074
3075
3076/**
3077 * SetUnvalidated
3078 * Set UAM_validated field to false in #_users table
3079 *
3080 **/
3081function SetUnvalidated($user_id)
3082{
3083  $query ='
3084UPDATE '.USERS_TABLE.'
3085SET UAM_validated = "false"
3086WHERE id = '.$user_id.'
3087LIMIT 1
3088;';
3089
3090  pwg_query($query);
3091}
3092
3093
3094/**
3095 * UAM_Set_PwdReset
3096 * Action in user_list to set a password reset for a user
3097 */
3098function UAM_Set_PwdReset($uid)
3099{
3100  $query ='
3101UPDATE '.USERS_TABLE.'
3102SET UAM_pwdreset = "true"
3103WHERE id = '.$uid.'
3104LIMIT 1
3105;';
3106
3107  pwg_query($query);
3108}
3109
3110
3111/**
3112 * UAM_loc_visible_user_list
3113 * Adds a new feature in user_list to allow password reset for selected users by admin
3114 *
3115 */
3116function UAM_loc_visible_user_list($visible_user_list)
3117{
3118  global $template;
3119
3120  $template->append('plugin_user_list_column_titles', l10n('UAM_PwdReset'));
3121
3122  $user_ids = array();
3123
3124  foreach ($visible_user_list as $i => $user)
3125  {
3126    $user_ids[$i] = $user['id'];
3127  }
3128
3129  $user_nums = array_flip($user_ids);
3130
3131  // Query to get information in database
3132  // ------------------------------------
3133  if (!empty($user_ids))
3134  {
3135    $query = '
3136SELECT DISTINCT id, UAM_pwdreset
3137  FROM '.USERS_TABLE.'
3138  WHERE id IN ('.implode(',', $user_ids).')
3139;';
3140    $result = pwg_query($query);
3141
3142    while ($row = pwg_db_fetch_assoc($result))
3143    {
3144      if ($row['UAM_pwdreset'] == 'false')
3145      {
3146        $pwdreset = l10n('UAM_PwdReset_Done');
3147      }
3148      else if ($row['UAM_pwdreset'] == 'true')
3149      {
3150        $pwdreset = l10n('UAM_PwdReset_Todo');
3151      }
3152      else $pwdreset = l10n('UAM_PwdReset_NA');
3153
3154                  $visible_user_list[$user_nums[$row['id']]]['plugin_columns'][] = $pwdreset; // Shows users password state in user_list
3155    }
3156  }
3157  return $visible_user_list;
3158}
3159
3160
3161/**
3162 * UAM specific database dump (only for MySql !)
3163 * Creates an SQL dump of UAM specific tables and configuration settings
3164 *
3165 * @returns  : Boolean to manage appropriate message display
3166 *
3167 */
3168function UAM_dump($download)
3169{
3170  global $conf;
3171
3172  $plugin =  PluginInfos(UAM_PATH);
3173  $version = $plugin['version'];
3174
3175  // Initial backup folder creation and file initialisation
3176  // ------------------------------------------------------
3177  if (!is_dir(UAM_PATH.'/include/backup'))
3178    mkdir(UAM_PATH.'/include/backup');
3179
3180  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3181
3182  $fp = fopen($Backup_File, 'w');
3183
3184  // Writing plugin version
3185  $insertions = "-- ".$version." --\n\n";
3186  fwrite($fp, $insertions);
3187
3188  // Saving UAM specific tables
3189  // --------------------------
3190  $ListTables = array(USER_CONFIRM_MAIL_TABLE, USER_LASTVISIT_TABLE);
3191  $j=0;
3192
3193  while($j < count($ListTables))
3194  {
3195    $sql = 'SHOW CREATE TABLE '.$ListTables[$j];
3196    $res = pwg_query($sql);
3197
3198    if ($res)
3199    {
3200      $insertions = "-- -------------------------------------------------------\n";
3201      $insertions .= "-- Create ".$ListTables[$j]." table\n";
3202      $insertions .= "-- ------------------------------------------------------\n\n";
3203
3204      $insertions .= "DROP TABLE IF EXISTS ".$ListTables[$j].";\n\n";
3205
3206      $array = pwg_db_fetch_row($res);
3207      $array[1] .= ";\n\n";
3208      $insertions .= $array[1];
3209
3210      $req_table = pwg_query('DESCRIBE '.$ListTables[$j].';') or die(my_error());
3211      $nb_fields = pwg_db_num_rows($req_table);
3212      $req_table2 = pwg_query('SELECT * FROM '.$ListTables[$j]) or die(my_error());
3213
3214      while ($line = pwg_db_fetch_row($req_table2))
3215      {
3216        $insertions .= 'INSERT INTO '.$ListTables[$j].' VALUES (';
3217        for ($i=0; $i<$nb_fields; $i++)
3218        {
3219          $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3220        }
3221        $insertions = substr($insertions, 0, -2);
3222        $insertions .= ");\n";
3223      }
3224      $insertions .= "\n\n";
3225    }
3226
3227    fwrite($fp, $insertions);   
3228    $j++;
3229  }
3230
3231  // Saving UAM configuration
3232  // ------------------------
3233  $insertions = "-- -------------------------------------------------------\n";
3234  $insertions .= "-- Insert UAM configuration in ".CONFIG_TABLE."\n";
3235  $insertions .= "-- ------------------------------------------------------\n\n";
3236
3237  fwrite($fp, $insertions);
3238
3239  $pattern = "UserAdvManager%";
3240  $req_table = pwg_query('SELECT * FROM '.CONFIG_TABLE.' WHERE param LIKE "'.$pattern.'";') or die(my_error());
3241  $nb_fields = pwg_db_num_rows($req_table);
3242  $nb_fields = $nb_fields - 1;  // Fix the number of fields because pwg_db_num_rows() returns a bad number
3243
3244  while ($line = pwg_db_fetch_row($req_table))
3245  {
3246    $insertions = 'INSERT INTO '.CONFIG_TABLE.' VALUES (';
3247    for ($i=0; $i<$nb_fields; $i++)
3248    {
3249      $insertions .= '\'' . pwg_db_real_escape_string($line[$i]) . '\', ';
3250    }
3251    $insertions = substr($insertions, 0, -2);
3252    $insertions .= ");\n";
3253
3254    fwrite($fp, $insertions);
3255  }
3256
3257  fclose($fp);
3258
3259  // Download generated dump file
3260  // ----------------------------
3261  if ($download == 'true')
3262  {
3263    if (@filesize($Backup_File))
3264    {
3265      $http_headers = array(
3266        'Content-Length: '.@filesize($Backup_File),
3267        'Content-Type: text/x-sql',
3268        'Content-Disposition: attachment; filename="UAM_dbbackup.sql";',
3269        'Content-Transfer-Encoding: binary',
3270        );
3271
3272      foreach ($http_headers as $header)
3273      {
3274        header($header);
3275      }
3276
3277      @readfile($Backup_File);
3278      exit();
3279    }
3280  }
3281
3282  return true;
3283}
3284
3285
3286/**
3287 * UAM_Restore_backup_file
3288 * Restore backup database file
3289 *
3290 * @returns : Boolean
3291 */
3292function UAM_Restore_backup_file() 
3293{
3294  global $prefixeTable, $dblayer, $conf;
3295
3296  define('DEFAULT_PREFIX_TABLE', 'piwigo_');
3297
3298  $Backup_File = UAM_PATH.'/include/backup/UAM_dbbackup.sql';
3299
3300  // Cleanup database before restoring
3301  // ---------------------------------
3302
3303  // Delete UserAdvManager global config in #_config table
3304  $q = '
3305DELETE FROM '.CONFIG_TABLE.'
3306WHERE param="UserAdvManager"
3307;';
3308
3309  pwg_query($q);
3310
3311  // Delete UserAdvManager_ConfirmMail global config in #_config table
3312  $q = '
3313DELETE FROM '.CONFIG_TABLE.'
3314WHERE param="UserAdvManager_ConfirmMail"
3315;';
3316
3317  pwg_query($q);
3318
3319  // Delete UserAdvManager_Redir config in #_config table
3320  $q = '
3321DELETE FROM '.CONFIG_TABLE.'
3322WHERE param="UserAdvManager_Redir"
3323;';
3324
3325  pwg_query($q);
3326
3327  // Delete UserAdvManager_Version config in #_config table
3328  $q = '
3329DELETE FROM '.CONFIG_TABLE.'
3330WHERE param="UserAdvManager_Version"
3331;';
3332
3333  pwg_query($q);
3334
3335  // Restore sql backup file - DROP TABLE queries are executed
3336  // ---------------------------------------------------------
3337  UAM_execute_sqlfile(
3338    $Backup_File,
3339    DEFAULT_PREFIX_TABLE,
3340    $prefixeTable,
3341    $dblayer
3342  );
3343}
3344
3345
3346/**
3347 * loads an sql file and executes all queries / Based on Piwigo's original install file
3348 *
3349 * Before executing a query, $replaced is... replaced by $replacing. This is
3350 * useful when the SQL file contains generic words.
3351 *
3352 * @param string filepath
3353 * @param string replaced
3354 * @param string replacing
3355 * @return void
3356 */
3357function UAM_execute_sqlfile($filepath, $replaced, $replacing, $dblayer)
3358{
3359  $sql_lines = file($filepath);
3360  $query = '';
3361  foreach ($sql_lines as $sql_line)
3362  {
3363    $sql_line = trim($sql_line);
3364    if (preg_match('/(^--|^$)/', $sql_line))
3365    {
3366      continue;
3367    }
3368
3369    $query.= ' '.$sql_line;
3370
3371    // if we reached the end of query, we execute it and reinitialize the
3372    // variable "query"
3373    if (preg_match('/;$/', $sql_line))
3374    {
3375      $query = trim($query);
3376      $query = str_replace($replaced, $replacing, $query);
3377      if ('mysql' == $dblayer)
3378      {
3379        if (preg_match('/^(CREATE TABLE .*)[\s]*;[\s]*/im', $query, $matches))
3380        {
3381          $query = $matches[1].' DEFAULT CHARACTER SET utf8'.';';
3382        }
3383      }
3384      pwg_query($query);
3385      $query = '';
3386    }
3387  }
3388}
3389
3390
3391/**
3392 * Delete obsolete files on plugin upgrade
3393 * Obsolete files are listed in file obsolete.list
3394 *
3395 */
3396function clean_obsolete_files()
3397{
3398  if (file_exists(UAM_PATH.'obsolete.list')
3399    and $old_files = file(UAM_PATH.'obsolete.list', FILE_IGNORE_NEW_LINES)
3400    and !empty($old_files))
3401  {
3402    array_push($old_files, 'obsolete.list');
3403    foreach($old_files as $old_file)
3404    {
3405      $path = UAM_PATH.$old_file;
3406      if (is_file($path))
3407      {
3408        @unlink($path);
3409      }
3410      elseif (is_dir($path))
3411      {
3412        @rmdir($path);
3413      }
3414    }
3415  }
3416}
3417
3418
3419/**
3420 * Function called from maintain.inc.php - to check if database upgrade is needed
3421 *
3422 * @param : table name
3423 *
3424 * @return : boolean
3425 *
3426 */
3427function table_exist($table)
3428{
3429  $query = 'DESC '.$table.';';
3430  return (bool)($res=pwg_query($query));
3431}
3432
3433
3434/**
3435 * Function called from UAM_admin.php and main.inc.php to get the plugin version and name
3436 *
3437 * @param : plugin directory
3438 *
3439 * @return : plugin's version and name
3440 *
3441 */
3442function PluginInfos($dir)
3443{
3444  $path = $dir;
3445
3446  $plg_data = implode( '', file($path.'main.inc.php') );
3447  if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
3448  {
3449    $plugin['name'] = trim( $val[1] );
3450  }
3451  if (preg_match("|Version: (.*)|", $plg_data, $val))
3452  {
3453    $plugin['version'] = trim($val[1]);
3454  }
3455  if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
3456  {
3457    $plugin['uri'] = trim($val[1]);
3458  }
3459  if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
3460  {
3461    $plugin['description'] = trim($desc);
3462  }
3463  elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
3464  {
3465    $plugin['description'] = trim($val[1]);
3466  }
3467  if ( preg_match("|Author: (.*)|", $plg_data, $val) )
3468  {
3469    $plugin['author'] = trim($val[1]);
3470  }
3471  if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
3472  {
3473    $plugin['author uri'] = trim($val[1]);
3474  }
3475  if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
3476  {
3477    list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
3478    if (is_numeric($extension)) $plugin['extension'] = $extension;
3479  }
3480// IMPORTANT SECURITY !
3481// --------------------
3482  $plugin = array_map('htmlspecialchars', $plugin);
3483
3484  return $plugin ;
3485}
3486
3487
3488/**
3489 * Useful for debugging - 4 vars can be set
3490 * Output result to log.txt file
3491 *
3492 */
3493function UAMLog($var1, $var2, $var3, $var4)
3494{
3495   $fo=fopen (UAM_PATH.'log.txt','a') ;
3496   fwrite($fo,"======================\n") ;
3497   fwrite($fo,'le ' . date('D, d M Y H:i:s') . "\r\n");
3498   fwrite($fo,$var1 ."\r\n") ;
3499   fwrite($fo,$var2 ."\r\n") ;
3500   fwrite($fo,$var3 ."\r\n") ;
3501   fwrite($fo,$var4 ."\r\n") ;
3502   fclose($fo) ;
3503}
3504
3505?>
Note: See TracBrowser for help on using the repository browser.