added days of week to reccurence widget (#286)
[openemr.git] / library / auth.inc
blob952e21e23a4c10ba3d051f0ebd900889c07cdb71
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 = '';
36 if (isset($_GET['auth']) && ($_GET['auth'] == "login") && isset($_POST['authUser']) &&
37     isset($_POST['clearPass']) && isset($_POST['authProvider']))
39     $clearPass=$_POST['clearPass'];    
40     // set the language
41     if (!empty($_POST['languageChoice'])) {
42         $_SESSION['language_choice'] = $_POST['languageChoice'];
43     }
44     else {
45         $_SESSION['language_choice'] = 1;
46     }
47     // set language direction according to language choice. Later in globals.php we'll override main theme name if needed.
48     $_SESSION['language_direction'] = getLanguageDir($_SESSION['language_choice']  ); 
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(true);
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      //--Note can't perform nice logout if skip_timeout_reset is set since these are called
103      //via ajax scripts where this output is not getting sent to browser.
104      //--Note DAEMON_FLAG is ok because it is run from a frame in the browser.
105     if ( ((time() - $_SESSION["last_update"]) > $timeout) && empty($_REQUEST['skip_timeout_reset']) ) {
106         newEvent("logout", $_SESSION['authUser'], $_SESSION['authProvider'], 0, "timeout");
107         authCloseSession();
108         authLoginScreen(true);
109     } else {
110         // Have a mechanism to skip the timeout reset mechanism if a skip_timeout_reset parameter exists. This
111         //  can be used by scripts that continually request information from the server; for example the Messages
112         //  and Reminders automated intermittent requests that happen in the Messages Center script and in 
113         //  the left navigation menu script.
114         if (empty($GLOBALS['DAEMON_FLAG']) && empty($_REQUEST['skip_timeout_reset'])) $_SESSION["last_update"] = time();
115     }
120 //----------THINGS WE DO IF WE STILL LIKE YOU
122 function authCheckSession ()
124     if (isset($_SESSION['authId'])) {
125         $authDB = privQuery("select ".implode(",",array(TBL_USERS.".".COL_ID,
126                                                         TBL_USERS.".".COL_UNM,
127                                                         TBL_USERS_SECURE.".".COL_PWD,
128                                                         TBL_USERS_SECURE.".".COL_ID)) 
129                 . " FROM ". implode(",",array(TBL_USERS,TBL_USERS_SECURE)) 
130                 . " WHERE ". TBL_USERS.".".COL_ID." = ? "
131                 . " AND ". TBL_USERS.".".COL_UNM . "=" . TBL_USERS_SECURE.".".COL_UNM
132                 . " AND ". TBL_USERS.".".COL_ACTIVE . "=1" 
133                 ,array($_SESSION['authId']));
134         if ($_SESSION['authUser'] == $authDB['username'] 
135             && $_SESSION['authPass'] == $authDB['password'] )
136         {
137             return true;
138         }
139         else {
140             return false;
141         }
142     }
143     else {
144         return false;
145     }
148 function authCloseSession ()
150   // Before destroying the session, save its site_id so that the next
151   // login will default to that same site.
152   global $incoming_site_id;
153   $incoming_site_id = $_SESSION['site_id'];
154   ob_start();
155   session_unset();
156   session_destroy();
157   unset($_COOKIE[session_name()]);
160 function authLoginScreen($timed_out = false)
162   // See comment in authCloseSession().
163   global $incoming_site_id;
165 <script>
166  // Find the top level window for this instance of OpenEMR, set a flag indicating
167  // session timeout has occurred, and reload the login page into it.  This is so
168  // that beforeunload event handlers will not obstruct the process in this case.
169  var w = window;
170  while (w.opener) { // in case we are in a dialog window
171   var wtmp = w;
172   w = w.opener;
173   wtmp.close();
175 <?php if ($timed_out) { ?>
176  w.top.timed_out = true;
177 <?php } ?>
178  w.top.location.href = '<?php echo "{$GLOBALS['login_screen']}?error=1&site=$incoming_site_id"; ?>';
179 </script>
180 <?php
181   exit;
184 // Check if the user's password has expired beyond the grace limit.
185 // If so, deactivate the user
186 function authCheckExpired($user)
188   $result = sqlStatement("select pwd_expiration_date from users where username = ?",array($user));
189   if($row = sqlFetchArray($result)) 
190   {
191     $pwd_expires = $row['pwd_expiration_date'];
192   }
193   $current_date = date("Y-m-d");
194   if($pwd_expires != "0000-00-00")
195   {
196     $grace_time1 = date("Y-m-d", strtotime($pwd_expires . "+".$GLOBALS['password_grace_time'] ."days"));
197   }
198   if(($grace_time1 != "") && strtotime($current_date) > strtotime($grace_time1))
199   {
200     sqlStatement("update users set active=0 where username = ?",array($user));
201     $_SESSION['loginfailure'] = 1;
202     return true;
203   }
204   return false;
207 function getUserList ($cols = '*', $limit = 'all', $start = '0')
209     if ($limit = "all")
210         $rez = sqlStatement("select $cols from users where username != '' order by date DESC");
211     else
212         $rez = sqlStatement("select $cols from users where username != '' order by date DESC limit $limit, $start");
213     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
214         $tbl[$iter] = $row;
215     return $tbl;
218 function getProviderList ($cols = '*', $limit= 'all', $start = '0')
220     if ($limit = "all")
221         $rez = sqlStatement("select $cols from groups order by date DESC");
222     else
223         $rez = sqlStatement("select $cols from groups order by date DESC limit $limit, $start");
224     for ($iter = 0; $row = sqlFetchArray($rez); $iter++)
225         $tbl[$iter] = $row;
226     return $tbl;
229 function addGroup ($groupname)
231     return sqlInsert("insert into groups (name) values (?)", array($groupname));
234 function delGroup ($group_id)
236     return sqlQuery("delete from groups where id = ? limit 0,1", array($group_id));
239 /***************************************************************
240 //pennfirm
241 //Function currently user by new post calendar code to determine
242 //if a given user is in a group with another user
243 //and if so to allow editing of that users events
245 //*************************************************************/
247 function validateGroupStatus ($user_to_be_checked, $group_user) {
248     if (isset($user_to_be_checked) && isset($group_user)) {
249         if ($user_to_be_checked == $group_user) {
251             return true;
252         }
253         elseif ($_SESSION['authorizeduser'] == 1)
254             return true;
256         $query = "SELECT groups.name FROM users,groups WHERE users.username = ? " .
257                  "AND users.username = groups.user group by groups.name";
258         $result = sqlStatement($query, array($user_to_be_checked));
260         $usertbcGroups = array();
262         while ($row = sqlFetchArray($result)) {
263             $usertbcGroups[] = $row[0];
264         }
266         $query = "SELECT groups.name FROM users,groups WHERE users.username =  ? " .
267                  "AND users.username = groups.user group by groups.name";
268         $result = sqlStatement($query, array($group_user));
270         $usergGroups = array();
272         while ($row = sqlFetchArray($result)) {
273             $usergGroups[] = $row[0];
274         }
275         foreach ($usertbcGroups as $group) {
276               if(in_array($group,$usergGroups)) {
277               return true;
278             }
279         }
281     }
283     return false;
287 // Attempt to update the user's password, password history, and password expiration.
288 // Verify that the new password does not match the last three passwords used.
289 // Return true if successfull, false on failure
290 function UpdatePasswordHistory($userid,$pwd)
292     $result = sqlStatement("select password, pwd_history1, pwd_history2 from users where id = ?",array($userid));
293     if ($row = sqlFetchArray($result)) {
294         $previous_pwd1=$row['password'];
295         $previous_pwd2=$row['pwd_history1'];
296         $previous_pwd3=$row['pwd_history2'];
297     }
298     if (($pwd != $previous_pwd1) && ($pwd != $previous_pwd2) && ($pwd != $previous_pwd3)) {
299         sqlStatement("update users set pwd_history2=?, pwd_history1=?,password=? where id=?",array($previous_pwd2,$previous_pwd1,$pwd,$userid));
300         if($GLOBALS['password_expiration_days'] != 0){
301         $exp_days=$GLOBALS['password_expiration_days'];
302         $exp_date = date('Y-m-d', strtotime("+$exp_days days"));
303         sqlStatement("update users set pwd_expiration_date=? where id=?",array($exp_date,$userid));
304         }
305         return true;
306     } 
307     else {
308         return false;
309     }