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

Last change on this file was 30776, checked in by Eric, 9 years ago

New feature : Allow admins to receive a copy of all emails sent by the plugin

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