php7 bug fix 7
[openemr.git] / library / auth.inc
blob65b4ae1f8951d55264503d6cffdbb27191100bd7
1 <?php
2 /**
3  * Authorization functions.
4  *
5  * LICENSE: This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
15  *
16  * @package OpenEMR
17  * @author  Rod Roark <rod@sunsetsystems.com>
18  * @author  Brady Miller <brady@sparmy.com>
19  * @author  Kevin Yeh <kevin.y@integralemr.com>
20  * @author  ViCarePlus <visolve_emr@visolve.com>
21  * @author  cfapress
22  * @link    http://www.open-emr.org
23  */
25 //----------THINGS WE ALWAYS DO
27 require_once("{$GLOBALS['srcdir']}/log.inc");
28 require_once("{$GLOBALS['srcdir']}/sql.inc");
29 // added for the phpGACL group check -- JRM
30 require_once("{$GLOBALS['srcdir']}/acl.inc");
31 require_once("$srcdir/formdata.inc.php");
32 require_once("$srcdir/authentication/login_operations.php");
34 $incoming_site_id = '';
38 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
39     isset($_POST['clearPass']) && isset($_POST['authProvider']))
41     $clearPass=$_POST['clearPass'];    
42     // set the language
43     if (!empty($_POST['languageChoice'])) {
44         $_SESSION['language_choice'] = $_POST['languageChoice'];
45     }
46     else {
47         $_SESSION['language_choice'] = 1;
48     }
49     // set language direction according to language choice. Later in globals.php we'll override main theme name if needed.
50     $_SESSION['language_direction'] = getLanguageDir($_SESSION['language_choice']  ); 
51     
52     if(!validate_user_password($_POST['authUser'],$clearPass,$_POST['authProvider']) ||  !verify_user_gacl_group($_POST['authUser']))
53     {
54         $_SESSION['loginfailure'] = 1;
55         authLoginScreen();
56     }
57 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
58     
59     if($GLOBALS['password_expiration_days'] != 0){
60         if(authCheckExpired($_POST['authUser']))
61         {
62             authLoginScreen();
63         }
64     }
65     $ip=$_SERVER['REMOTE_ADDR'];
66     $_SESSION['loginfailure'] = null;
67     unset($_SESSION['loginfailure']);
68     //store the very first initial timestamp for timeout errors
69     $_SESSION["last_update"] = time();
71 else if ( (isset($_GET['auth'])) && ($_GET['auth'] == "logout") )
73     newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
74     authCloseSession();
75     authLoginScreen();
77 else
79     if (authCheckSession())
80     {
81         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG']))
82         {
83             require_once("{$GLOBALS['srcdir']}/patient.inc");
84             /**
85             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
86             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
87                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
88                 $_SESSION['encounter']);
89             **/
90         }
91         //LOG EVERYTHING
92         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
93     }
94     else {
95         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
96         authLoginScreen();
97     }
100 if (!isset($_SESSION["last_update"])) {
101     authLoginScreen();
102 } else {
103      //if page has not been updated in a given period of time, we call login screen
104     if ((time() - $_SESSION["last_update"]) > $timeout) {
105         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
106         authCloseSession();
107         authLoginScreen();
108     } else {
109         // Have a mechanism to skip the timeout reset mechanism if a skip_timeout_reset parameter exists. This
110         //  can be used by scripts that continually request information from the server; for example the Messages
111         //  and Reminders automated intermittent requests that happen in the Messages Center script and in 
112         //  the left navigation menu script.
113         if (empty($GLOBALS['DAEMON_FLAG']) && empty($_REQUEST['skip_timeout_reset'])) $_SESSION["last_update"] = time();
114     }
119 //----------THINGS WE DO IF WE STILL LIKE YOU
121 function authCheckSession ()
123     if (isset($_SESSION['authId'])) {
124         $authDB = privQuery("select ".implode(",",array(TBL_USERS.".".COL_ID,
125                                                         TBL_USERS.".".COL_UNM,
126                                                         TBL_USERS_SECURE.".".COL_PWD,
127                                                         TBL_USERS_SECURE.".".COL_ID)) 
128                 . " FROM ". implode(",",array(TBL_USERS,TBL_USERS_SECURE)) 
129                 . " WHERE ". TBL_USERS.".".COL_ID." = ? "
130                 . " AND ". TBL_USERS.".".COL_UNM . "=" . TBL_USERS_SECURE.".".COL_UNM
131                 . " AND ". TBL_USERS.".".COL_ACTIVE . "=1" 
132                 ,array($_SESSION['authId']));
133         if ($_SESSION['authUser'] == $authDB['username'] 
134             && $_SESSION['authPass'] == $authDB['password'] )
135         {
136             return true;
137         }
138         else {
139             return false;
140         }
141     }
142     else {
143         return false;
144     }
147 function authCloseSession ()
149   // Before destroying the session, save its site_id so that the next
150   // login will default to that same site.
151   global $incoming_site_id;
152   $incoming_site_id = $_SESSION['site_id'];
153   ob_start();
154   session_unset();
155   session_destroy();
156   unset($_COOKIE[session_name()]);
159 function authLoginScreen()
161   // See comment in authCloseSession().
162   global $incoming_site_id;
163   header("Location: {$GLOBALS['login_screen']}?error=1&site=$incoming_site_id");
164   exit;
167 // Check if the user's password has expired beyond the grace limit.
168 // If so, deactivate the user
169 function authCheckExpired($user)
171   $result = sqlStatement("select pwd_expiration_date from users where username = ?",array($user));
172   if($row = sqlFetchArray($result)) 
173   {
174     $pwd_expires = $row['pwd_expiration_date'];
175   }
176   $current_date = date("Y-m-d");
177   if($pwd_expires != "0000-00-00")
178   {
179     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
180   }
181   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
182   {
183     sqlStatement("update users set active=0 where username = ?",array($user));
184     $_SESSION['loginfailure'] = 1;
185     return true;
186   }
187   return false;
190 function getUserList ($cols = '*', $limit = 'all', $start = '0')
192     if ($limit = "all")
193         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
194     else
195         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
196     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
197         $tbl[$iter] = $row;
198     return $tbl;
201 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
203     if ($limit = "all")
204         $rez = sqlStatement("select $cols from groups order by date DESC");
205     else
206         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
207     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
208         $tbl[$iter] = $row;
209     return $tbl;
212 function addGroup ($groupname)
214     return sqlInsert("insert into groups (name) values (?)", array($groupname));
217 function delGroup ($group_id)
219     return sqlQuery("delete from groups where id = ? limit 0,1", array($group_id));
222 /***************************************************************
223 //pennfirm
224 //Function currently user by new post calendar code to determine
225 //if a given user is in a group with another user
226 //and if so to allow editing of that users events
228 //*************************************************************/
230 function validateGroupStatus ($user_to_be_checked, $group_user) {
231     if (isset($user_to_be_checked) && isset($group_user)) {
232         if ($user_to_be_checked == $group_user) {
234             return true;
235         }
236         elseif ($_SESSION['authorizeduser'] == 1)
237             return true;
239         $query = "SELECT groups.name FROM users,groups WHERE users.username = ? " .
240                  "AND users.username = groups.user group by groups.name";
241         $result = sqlStatement($query, array($user_to_be_checked));
243         $usertbcGroups = array();
245         while ($row = sqlFetchArray($result)) {
246             $usertbcGroups[] = $row[0];
247         }
249         $query = "SELECT groups.name FROM users,groups WHERE users.username =  ? " .
250                  "AND users.username = groups.user group by groups.name";
251         $result = sqlStatement($query, array($group_user));
253         $usergGroups = array();
255         while ($row = sqlFetchArray($result)) {
256             $usergGroups[] = $row[0];
257         }
258         foreach ($usertbcGroups as $group) {
259               if(in_array($group,$usergGroups)) {
260               return true;
261             }
262         }
264     }
266     return false;
270 // Attempt to update the user's password, password history, and password expiration.
271 // Verify that the new password does not match the last three passwords used.
272 // Return true if successfull, false on failure
273 function UpdatePasswordHistory($userid,$pwd)
275     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = ?",array($userid));
276     if ($row = sqlFetchArray($result)) {
277         $previous_pwd1=$row['password'];
278         $previous_pwd2=$row['pwd_history1'];
279         $previous_pwd3=$row['pwd_history2'];
280     }
281     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
282         sqlStatement("update users set pwd_history2=?, pwd_history1=?,password=? where id=?",array($previous_pwd2,$previous_pwd1,$pwd,$userid));
283         if($GLOBALS['password_expiration_days'] != 0){
284         $exp_days=$GLOBALS['password_expiration_days'];
285         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
286         sqlStatement("update users set pwd_expiration_date=? where id=?",array($exp_date,$userid));
287         }
288         return true;
289     } 
290     else {
291         return false;
292     }