source: extensions/UserAdvManager/branches/2.30/include/functions.inc.php @ 13823

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

r13822 merged from trunk
Bug 2602 fixed - Sql error when Confirmation by admin is set
Small code refactoring and cleanup
en_UK reference translation spellchecking
de_DE translation updated
fr_FR translation updated

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