Bug fixes in recent documents module code
[openemr.git] / library / auth.inc
blob79a2f870145a705e3cf5330b7054386a87c1732b
1 <?php
2 // This program is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU General Public License
4 // as published by the Free Software Foundation; either version 2
5 // of the License, or (at your option) any later version.
7 //----------THINGS WE ALWAYS DO
9 require_once("{$GLOBALS['srcdir']}/log.inc");
10 require_once("{$GLOBALS['srcdir']}/sql.inc");
11 // added for the phpGACL group check -- JRM
12 require_once("{$GLOBALS['srcdir']}/acl.inc");
13 require_once("$srcdir/formdata.inc.php");
15 $incoming_site_id = '';
17 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
18     isset($_POST['authPass']) && isset($_POST['authProvider']))
20     // set the language
21     if (!empty($_POST['languageChoice'])) {
22         $_SESSION['language_choice'] = $_POST['languageChoice'];
23     }
24     else {
25         $_SESSION['language_choice'] = 1;
26     }
27 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
28     if($GLOBALS['password_expiration_days'] != 0){
29         authCheckExpired();
30     }
31     $ip=$_SERVER['REMOTE_ADDR'];
32      //VicarePlus :: authNewPass is set ,only if the password in DB is encrypted using MD5.
33     if (isset($_POST['authNewPass']))
34     {
35     if (!authNewSession($_POST['authUser'], $_POST['authPass'], $_POST['authProvider'], $_POST['authNewPass']))
36     {
37         $_SESSION['loginfailure'] = 1;
38         authLoginScreen();
39     }
40     }
41     else
42     {
43     if (!authNewSession($_POST['authUser'], $_POST['authPass'], $_POST['authProvider'],''))
44     {
45         $_SESSION['loginfailure'] = 1;
46         authLoginScreen();
47     }
48     }
49     $_SESSION['loginfailure'] = null;
50     unset($_SESSION['loginfailure']);
51     //store the very first initial timestamp for timeout errors
52     $_SESSION["last_update"] = time();
54 else if ( (isset($_GET['auth'])) && ($_GET['auth'] == "logout") )
56     newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
57     authCloseSession();
58     authLoginScreen();
60 else
62     if (authCheckSession())
63     {
64         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG']))
65         {
66             require_once("{$GLOBALS['srcdir']}/patient.inc");
67             /**
68             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
69             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
70                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
71                 $_SESSION['encounter']);
72             **/
73         }
74         //LOG EVERYTHING
75         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
76     }
77     else {
78         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
79         authLoginScreen();
80     }
83 if (!isset($_SESSION["last_update"])) {
84     authLoginScreen();
85 } else {
86      //if page has not been updated in a given period of time, we call login screen
87     if ((time() - $_SESSION["last_update"]) > $timeout) {
88         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
89         authCloseSession();
90         authLoginScreen();
91     } else {
92         if (empty($GLOBALS['DAEMON_FLAG'])) $_SESSION["last_update"] = time();
93     }
96 //----------THINGS WE DO IF WE STILL LIKE YOU
98 function authNewSession ($user, $pass, $provider, $new_upgrade_pass)
100     $ip = $_SERVER['REMOTE_ADDR'];
101     // check to see if the user belongs to *any* OpenEMR groups in phpGACL -- JRM
102     global $phpgacl_location;
103     if (isset ($phpgacl_location)) {
104       if (acl_get_group_titles($user) == 0) {
105           newEvent( 'login', $user, $provider, 0, "failure: $ip. user not in any phpGACL groups. (bad username?)");
106           return false;
107       }
108     }
110     // get details about the user
111     $authDB = sqlQuery("select id, password, authorized, see_auth".
112                         ", cal_ui, active ".
113                         " from users where username = '$user'");
115     // if the user is NOT active, get out
116     if ($authDB['active'] != 1) {
117         newEvent( 'login', $user, $provider, 0, "failure: $ip. user not active or not found in users table");
118         return false;
119     }
121     //VicarePlus :: If the password in DB is encrypted using 'md5' , it is updated with 'sha1' encryption and
122     //Vicareplus :: the user is asked to login again. 
123     if (strlen($pass) == 32)
124     {
125     if ($authDB['password'] == $pass)
126     {
127     sqlStatement("update users set password='$new_upgrade_pass' where username = '$user'");
128     $_SESSION['relogin'] = 1;
129     }
130     else
131     {
132     newEvent( 'login', $user, $provider, 0, "failure: $ip. user password mismatch ($pass)");
133     return false;
134     }
135     }
136     // compare the submitted password with the stored password
137     if ($authDB['password'] == $pass)
138     {
139         //here, we check to see if the user is in fact a member of the correct group:
140         if ($authGroup = sqlQuery("select * from groups where user='$user' and name='$provider'"))
141         {
142             $_SESSION['authUser'] = $user;
143             $_SESSION['authGroup'] = $authGroup['name'];
144             $_SESSION['authUserID'] = $authDB['id'];
145             $_SESSION['authPass'] = $pass;
146             $_SESSION['authProvider'] = $provider;
147             $_SESSION['authId'] = $authDB{'id'};
148             $_SESSION['cal_ui'] = $authDB['cal_ui'];
149             $_SESSION['userauthorized'] = $authDB['authorized'];
150             // Some users may be able to authorize without being providers:
151             if ($authDB['see_auth'] > '2') $_SESSION['userauthorized'] = '1';
152             newEvent( 'login', $user, $provider, 1, "success: $ip");
153             return true;
154         } else {
155             newEvent( 'login', $user, $provider, 0, "failure: $ip. user not in group: $provider");
156             return false;
157         }
158     }
160     newEvent( 'login', $user, $provider, 0, "failure: $ip. user password mismatch ($pass)");
161     return false;
164 function authCheckSession ()
166     if (isset($_SESSION['authId'])) {
167         $authDB = sqlQuery("select username, password from users where id = '" .
168             $_SESSION['authId']."'");
169         if ($_SESSION['authUser'] == $authDB['username'] &&
170             $_SESSION['authPass'] == $authDB['password'])
171         {
172             return true;
173         }
174         else {
175             return false;
176         }
177     }
178     else {
179         return false;
180     }
183 function authCloseSession ()
185   // Before destroying the session, save its site_id so that the next
186   // login will default to that same site.
187   global $incoming_site_id;
188   $incoming_site_id = $_SESSION['site_id'];
189   ob_start();
190   session_unset();
191   session_destroy();
192   unset($_COOKIE[session_name()]);
195 function authLoginScreen()
197   // See comment in authCloseSession().
198   global $incoming_site_id;
199   header("Location: {$GLOBALS['login_screen']}?error=1&site=$incoming_site_id");
200   exit;
203 // Check if the user's password has expired beyond the grace limit.
204 // If so, deactivate the user
205 function authCheckExpired()
207   $auser=formData('authUser','P');
208   $result = sqlStatement("select pwd_expiration_date from users where username = '".$auser."'");
209   if($row = sqlFetchArray($result)) 
210   {
211     $pwd_expires = $row['pwd_expiration_date'];
212   }
213   $current_date = date("Y-m-d");
214   if($pwd_expires != "0000-00-00")
215   {
216     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
217   }
218   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
219   {
220     sqlStatement("update users set active=0 where username = '".$auser."'");
221     $_SESSION['loginfailure'] = 1;
222   }
226 function addUser ($username, $password_md5, $info, $authorized = 'yes')
228     return sqlInsert("insert into users (username, password, info, authorized) values ('$username', '$password_md5', '$info', '$authorized')");
231 function delUser ($id)
233     return sqlQuery("delete from users where id = '$id' limit 0,1");
236 function changePasword ($id, $new_md5)
238     return sqlQuery("update users set password = '$new_md5' where id = '$id'");
241 function getUserList ($cols = '*', $limit = 'all', $start = '0')
243     if ($limit = "all")
244         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
245     else
246         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
247     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
248         $tbl[$iter] = $row;
249     return $tbl;
252 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
254     if ($limit = "all")
255         $rez = sqlStatement("select $cols from groups order by date DESC");
256     else
257         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
258     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
259         $tbl[$iter] = $row;
260     return $tbl;
263 function addGroup ($groupname)
265     return sqlInsert("insert into groups (name) values ('$groupname')");
268 function delGroup ($group_id)
270     return sqlQuery("delete from groups where id = '$group_id' limit 0,1");
273 /***************************************************************
274 //pennfirm
275 //Function currently user by new post calendar code to determine
276 //if a given user is in a group with another user
277 //and if so to allow editing of that users events
279 //*************************************************************/
281 function validateGroupStatus ($user_to_be_checked, $group_user) {
282     if (isset($user_to_be_checked) && isset($group_user)) {
283         if ($user_to_be_checked == $group_user) {
285             return true;
286         }
287         elseif ($_SESSION['authorizeduser'] == 1)
288             return true;
290         $query = "SELECT groups.name FROM users,groups WHERE users.username =  \"" . mysql_real_escape_string($user_to_be_checked) . "\" " .
291                  "AND users.username = groups.user group by groups.name";
292         $result = sqlStatement($query);
294         $usertbcGroups = array();
296         while ($row = mysql_fetch_array($result)) {
297             $usertbcGroups[] = $row[0];
298         }
300         $query = "SELECT groups.name FROM users,groups WHERE users.username =  \"" . mysql_real_escape_string($group_user) . "\" " .
301                  "AND users.username = groups.user group by groups.name";
302         $result = sqlStatement($query);
304         $usergGroups = array();
306         while ($row = mysql_fetch_array($result)) {
307             $usergGroups[] = $row[0];
308         }
309         foreach ($usertbcGroups as $group) {
310               if(in_array($group,$usergGroups)) {
311               return true;
312             }
313         }
315     }
317     return false;
321 // Attempt to update the user's password, password history, and password expiration.
322 // Verify that the new password does not match the last three passwords used.
323 // Return true if successfull, false on failure
324 function UpdatePasswordHistory($userid,$pwd)
326     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = $userid");
327     if ($row = sqlFetchArray($result)) {
328         $previous_pwd1=$row['password'];
329         $previous_pwd2=$row['pwd_history1'];
330         $previous_pwd3=$row['pwd_history2'];
331     }
332     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
333         sqlStatement("update users set pwd_history2='$previous_pwd2', pwd_history1='$previous_pwd1',password='$pwd' where id=$userid");
334         if($GLOBALS['password_expiration_days'] != 0){
335         $exp_days=$GLOBALS['password_expiration_days'];
336         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
337         sqlStatement("update users set pwd_expiration_date='$exp_date' where id=$userid");
338         }
339         return true;
340     } 
341     else {
342         return false;
343     }