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

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

merge from trunk to branch 2.50:
Bug 2874 fixed : Warning message on tracking confirmation tab when confirmation by admins is set and a user is added manually by an admin
Reference language/en_UK/help.lang.php improved
language/fr_FR/help.lang.php updated
Update de_DE, thanks to : stephy
Update lv_LV, thanks to : agrisans

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