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

Last change on this file since 13528 was 13528, checked in by Eric, 12 years ago

bug 2591 fixed : Exclusion of Adult_Content's generic users from users tracking list

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