source: extensions/UserAdvManager/branches/2.50/include/functions.inc.php @ 23903

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

r23902 merged from trunk to branch 2.50 :
Next version is 2.50.10 :
Bug fixed on automated task triggered for ghost users
Compatibility with other plugins fixed (considering Register_FluxBB and Prune_History)
Update el_GR, thanks to : bas_alba
Update da_DK, thanks to : Kaare
Update es_ES, thanks to : jpr928
Update tr_TR, thanks to : LazBoy
Update de_DE, thanks to : Yogie
Update ru_RU, thanks to : Konve

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