incremented patch version 7
[openemr.git] / library / auth.inc
blob2c7e2e2bdcd177ab95f89ce59d788896522d55df
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     
50     if(!validate_user_password($_POST['authUser'],$clearPass,$_POST['authProvider']) ||  !verify_user_gacl_group($_POST['authUser']))
51     {
52         $_SESSION['loginfailure'] = 1;
53         authLoginScreen();
54     }
55 //If password expiration option is enabled call authCheckExpired() to check whether login user password is expired or not
56     
57     if($GLOBALS['password_expiration_days'] != 0){
58         if(authCheckExpired($_POST['authUser']))
59         {
60             authLoginScreen();
61         }
62     }
63     $ip=$_SERVER['REMOTE_ADDR'];
64     $_SESSION['loginfailure'] = null;
65     unset($_SESSION['loginfailure']);
66     //store the very first initial timestamp for timeout errors
67     $_SESSION["last_update"] = time();
69 else if ( (isset($_GET['auth'])) && ($_GET['auth'] == "logout") )
71     newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "success");
72     authCloseSession();
73     authLoginScreen();
75 else
77     if (authCheckSession())
78     {
79         if (isset($_SESSION['pid']) && empty($GLOBALS['DAEMON_FLAG']))
80         {
81             require_once("{$GLOBALS['srcdir']}/patient.inc");
82             /**
83             $logpatient = getPatientData($_SESSION['pid'], "lname, fname, mname");
84             newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'],
85                 "{$logpatient['lname']}, {$logpatient['fname']} {$logpatient['mname']} :: encounter " .
86                 $_SESSION['encounter']);
87             **/
88         }
89         //LOG EVERYTHING
90         //newEvent("view", $_SESSION['authUser'], $_SESSION['authProvider'], $_SERVER['REQUEST_URI']);
91     }
92     else {
93         newEvent("login",$_POST['authUser'], $_POST['authProvider'], 0, "insufficient data sent");
94         authLoginScreen();
95     }
98 if (!isset($_SESSION["last_update"])) {
99     authLoginScreen();
100 } else {
101      //if page has not been updated in a given period of time, we call login screen
102     if ((time() - $_SESSION["last_update"]) > $timeout) {
103         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
104         authCloseSession();
105         authLoginScreen();
106     } else {
107         // Have a mechanism to skip the timeout reset mechanism if a skip_timeout_reset parameter exists. This
108         //  can be used by scripts that continually request information from the server; for example the Messages
109         //  and Reminders automated intermittent requests that happen in the Messages Center script and in 
110         //  the left navigation menu script.
111         if (empty($GLOBALS['DAEMON_FLAG']) && empty($_REQUEST['skip_timeout_reset'])) $_SESSION["last_update"] = time();
112     }
115 //----------THINGS WE DO IF WE STILL LIKE YOU
117 function authCheckSession ()
119     if (isset($_SESSION['authId'])) {
120         $authDB = privQuery("select ".implode(",",array(TBL_USERS.".".COL_ID,
121                                                         TBL_USERS.".".COL_UNM,
122                                                         TBL_USERS_SECURE.".".COL_PWD,
123                                                         TBL_USERS_SECURE.".".COL_ID)) 
124                 . " FROM ". implode(",",array(TBL_USERS,TBL_USERS_SECURE)) 
125                 . " WHERE ". TBL_USERS.".".COL_ID." = ? "
126                 . " AND ". TBL_USERS.".".COL_UNM . "=" . TBL_USERS_SECURE.".".COL_UNM
127                 . " AND ". TBL_USERS.".".COL_ACTIVE . "=1" 
128                 ,array($_SESSION['authId']));
129         if ($_SESSION['authUser'] == $authDB['username'] 
130             && $_SESSION['authPass'] == $authDB['password'] )
131         {
132             return true;
133         }
134         else {
135             return false;
136         }
137     }
138     else {
139         return false;
140     }
143 function authCloseSession ()
145   // Before destroying the session, save its site_id so that the next
146   // login will default to that same site.
147   global $incoming_site_id;
148   $incoming_site_id = $_SESSION['site_id'];
149   ob_start();
150   session_unset();
151   session_destroy();
152   unset($_COOKIE[session_name()]);
155 function authLoginScreen()
157   // See comment in authCloseSession().
158   global $incoming_site_id;
159   header("Location: {$GLOBALS['login_screen']}?error=1&site=$incoming_site_id");
160   exit;
163 // Check if the user's password has expired beyond the grace limit.
164 // If so, deactivate the user
165 function authCheckExpired($user)
167   $result = sqlStatement("select pwd_expiration_date from users where username = ?",array($user));
168   if($row = sqlFetchArray($result)) 
169   {
170     $pwd_expires = $row['pwd_expiration_date'];
171   }
172   $current_date = date("Y-m-d");
173   if($pwd_expires != "0000-00-00")
174   {
175     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
176   }
177   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
178   {
179     sqlStatement("update users set active=0 where username = ?",array($user));
180     $_SESSION['loginfailure'] = 1;
181     return true;
182   }
183   return false;
186 function getUserList ($cols = '*', $limit = 'all', $start = '0')
188     if ($limit = "all")
189         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
190     else
191         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
192     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
193         $tbl[$iter] = $row;
194     return $tbl;
197 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
199     if ($limit = "all")
200         $rez = sqlStatement("select $cols from groups order by date DESC");
201     else
202         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
203     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
204         $tbl[$iter] = $row;
205     return $tbl;
208 function addGroup ($groupname)
210     return sqlInsert("insert into groups (name) values (?)", array($groupname));
213 function delGroup ($group_id)
215     return sqlQuery("delete from groups where id = ? limit 0,1", array($group_id));
218 /***************************************************************
219 //pennfirm
220 //Function currently user by new post calendar code to determine
221 //if a given user is in a group with another user
222 //and if so to allow editing of that users events
224 //*************************************************************/
226 function validateGroupStatus ($user_to_be_checked, $group_user) {
227     if (isset($user_to_be_checked) && isset($group_user)) {
228         if ($user_to_be_checked == $group_user) {
230             return true;
231         }
232         elseif ($_SESSION['authorizeduser'] == 1)
233             return true;
235         $query = "SELECT groups.name FROM users,groups WHERE users.username = ? " .
236                  "AND users.username = groups.user group by groups.name";
237         $result = sqlStatement($query, array($user_to_be_checked));
239         $usertbcGroups = array();
241         while ($row = sqlFetchArray($result)) {
242             $usertbcGroups[] = $row[0];
243         }
245         $query = "SELECT groups.name FROM users,groups WHERE users.username =  ? " .
246                  "AND users.username = groups.user group by groups.name";
247         $result = sqlStatement($query, array($group_user));
249         $usergGroups = array();
251         while ($row = sqlFetchArray($result)) {
252             $usergGroups[] = $row[0];
253         }
254         foreach ($usertbcGroups as $group) {
255               if(in_array($group,$usergGroups)) {
256               return true;
257             }
258         }
260     }
262     return false;
266 // Attempt to update the user's password, password history, and password expiration.
267 // Verify that the new password does not match the last three passwords used.
268 // Return true if successfull, false on failure
269 function UpdatePasswordHistory($userid,$pwd)
271     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = ?",array($userid));
272     if ($row = sqlFetchArray($result)) {
273         $previous_pwd1=$row['password'];
274         $previous_pwd2=$row['pwd_history1'];
275         $previous_pwd3=$row['pwd_history2'];
276     }
277     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
278         sqlStatement("update users set pwd_history2=?, pwd_history1=?,password=? where id=?",array($previous_pwd2,$previous_pwd1,$pwd,$userid));
279         if($GLOBALS['password_expiration_days'] != 0){
280         $exp_days=$GLOBALS['password_expiration_days'];
281         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
282         sqlStatement("update users set pwd_expiration_date=? where id=?",array($exp_date,$userid));
283         }
284         return true;
285     } 
286     else {
287         return false;
288     }