Odyssey
hcuProfile.data
1 <?php
2 /*
3  * File: hcuProfile.data
4  * Purpose: Handle the CRUD portion of the Profile feature. Return any requested data
5  * in a JSON format, for the client to display accordingly.
6  *
7  * NOTE: Update the 2-factor cookie if any component of it changes: username (alias),
8  * password, confidence, e-mail. Only if the cookie already exists, but don't
9  * bother checking if the value changed (just re-generate regardless).
10  *
11  * Call this script with the following parameters
12  * action - what the client side is requesting.
13  *
14  *
15  * Returns JSON OBJECT.
16  */
17 
18 
19 try {
20  // ** SET HOMECU FLAGS
21  $serviceShowInfo = false;
22  $serviceLoadMenu = false;
23  $serviceShowMenu = false;
24  $serviceAllowReadonly = true;
25 
26 
27  // ** INCLUDE MAIN GLOBAL SCRIPT -- Handles security / global variable values
28  // unresolved - hcuService will be returning a status object: e.g. ["homecuErrors":{[{"message":"message1"}...{"message":"messagen"}]}]
29  require_once(dirname(__FILE__) . '/../library/hcuService.i');
30 
31  $EMAIL_FLAG = GetMsgTxValue('MSGTX_FORCE_EM');
32 
33  // ** IMPORT FORM VALUES
34  $dms_ok = array( "action"=>"string",
35  "email"=>"string","emailValid"=>"string","egenl"=>"string",
36  "alertEmails"=>"string",
37  "old"=>"string","new1"=>"string",
38  "new2"=>"string","sawhints"=>"string",
39  "security_qst"=>"prefix_s", "security_rsp"=>"prefix_s",
40  "security_curpwd"=>"string", "security_token"=>"string",
41  "security_confidence"=>"string",
42  "security_phones"=>"string",
43  "user_alias"=>"string","user_alias2"=>"string",
44  "account_data"=>"array"
45  );
46 
47 
48  HCU_ImportVars($HB_ENV, "HCUPOST", $dms_ok);
49 
50  header('Content-Type: application/json');
51 
52  //get the database connection
53  // $dbh is set up
54 
55  $logger = $HB_ENV["SYSENV"]["logger"];
56 
57  // Need to see if there is a valid device cookie to begin with. Checking if after changes exist doesn't tell if 1) it doesn't exist or 2) it is modified.
58  $usrInfo = GetUserbyName($HB_ENV['dbh'], $HB_ENV['Cu'], $HB_ENV['Cn']);
59  $usrDeviceCookieExists = isValidDeviceCookie($HB_ENV['Cu'], $usrInfo);
60 
61 /*
62  // ** First check the refer script -- make sure coming from right place
63  $parseRefer = parse_url($_SERVER['HTTP_REFERER']);
64  $referScript = basename($parseRefer['path']);
65  if (!in_array($referScript, array('hcuProfileAlias.prg','hcuProfileDesc.prg','hcuProfileEmail.prg','hcuProfilePwd.prg','hcuProfileSecurity.prg'))) {
66  // ** Wrong script calling this data routine
67  $aryErrors[] = $MC->msg('Feature Unavailable', HCU_DISPLAY_AS_RAW);
68  throw new Exception (HCU_JsonEncode($aryErrors));
69  }
70 */
71  /*
72  * ** CHECK USER FEATURE PERMISSIONS **
73  * NOTE: DO NOT AUTO-REDIR. Handle perm error here
74  */
75  if (!PermCheckFeatureScreen($dbh, $HB_ENV, $MC, FEATURE_BASIC, '', false)) {
76  throw new Exception (HCU_JsonEncode(Array($MC->msg('Rights not set', HCU_DISPLAY_AS_HTML))));
77  }
78 
79 
80  require_once(dirname(__FILE__) . '/../../shared/library/cu_fun.i');
81 
82  if (!$dbh) {
83  // The connection was not made to the database
84  // unresolved: return an error??
85  }
86 
87  // initialize the error and result objects
88  $aryResult = array();
89  $aryErrors = array();
90  $aryInfo = array();
91  $aryReply = array();
92 
93  $live = (dirname($_SERVER['PHP_SELF']) == '/hculive7');
94  if ($live) {
95  $cutx = "culivetx";
96  $showtx = ", show_livetx('{$HB_ENV['cu']}','{$HB_ENV['Cn']}') ";
97  } else {
98  $cutx = "cubatchtx";
99  $showtx = ", show_txacct('{$HB_ENV['cu']}','{$HB_ENV['Cn']}') ";
100  }
101 
102  // ** First Check to see if the user has a 2 Factor Cookie set
103  //$cookieName = Return2FactorName($HB_ENV['cu'], $HB_ENV['2factorkey'], $HB_ENV['Cn']);
104  // ** Its existence is proof they have set cookie
105  /*if ($_COOKIE[$cookieName] != '') {
106  $logger->info("User has a 2 Factor Cookie set");
107  $Cookie2FactorSet = true;
108  } else {
109  $logger->info("User doesn't have a 2 Factor Cookie set");
110  $Cookie2FactorSet = false;
111  }*/
112 
113  // do the requested operation
114  $requested_operation = $HB_ENV["HCUPOST"]["action"];
115  switch ( $requested_operation ) {
116  case "email_save":
117 
118  // set up what the verification/update functions expect
119  $emailRequired = ($HB_ENV['Fmsg_tx'] & $EMAIL_FLAG);
120  $paramEmailAddress = $HB_ENV['HCUPOST']['email'];
121  $updFields['settings_email']['email'] = $HB_ENV['HCUPOST']['email'];
122  $updFields['settings_email']['egenl'] = $HB_ENV['HCUPOST']['egenl'];
123  $updFields['settings_email']['verify'] = $emailRequired;
124  $updFields['settings_email']['valid'] = $HB_ENV['HCUPOST']['emailValid'];
125 
126  // * are we verifying the email address
127  $aryUpdate = Validate_Settings($dbh, $HB_ENV, $updFields, $MC);
128 
129  if ($aryUpdate['status']['code'] == '000') {
130  $aryUpdate = Update_User_Settings($dbh, $HB_ENV, $MC, $updFields, false);
131  }
132 
133  if ($aryUpdate['status']['code'] != '000') {
134  // an error occurred
135  $aryErrors = array();
136  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
137  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
138  }
139 
140  throw new Exception (HCU_JsonEncode($aryErrors));
141  } else {
142  $reqFlag = "";
143  if ( $emailRequired ) {
144  // clear out the email required flag
145  $reqFlag = "&Fmsg_tx=" . ($HB_ENV['Fmsg_tx'] ^ $EMAIL_FLAG);
146  }
147  $_COOKIE['Ticket'] = SetTicket($HB_ENV, $_COOKIE['Ticket'],"Ml=$paramEmailAddress" . $reqFlag);
148 
149  // return the values
150  $aryResult["email"] = $HB_ENV['HCUPOST']['email'];
151  $aryResult["egenl"] = $HB_ENV['HCUPOST']['egenl'];
152 
153  // return status
154  $aryInfo = array( "message" => $MC->msg('EMail Settings Changed', HCU_DISPLAY_AS_RAW) );
155 
156  // now try to update the alerts - any in the list get updated
157  if ( strlen( $HB_ENV["HCUPOST"]["alertEmails"] ) > 0 ) {
158 
159  // get the alerts
160  $alertInfo = Get_AlertsDetailed( $dbh, $HB_ENV["Cu"], $HB_ENV["Uid"], $HB_ENV["Fset3"]);
161  $alertList = $alertInfo["data"];
162 
163  $emailList = explode( "|", $HB_ENV["HCUPOST"]["alertEmails"] );
164 
165  // go through the alerts
166  for ( $a = 0; $a < count( $alertList ); $a++ ) {
167  if ( $alertList[$a]["emailtype"] == "E" &&
168  in_array( $alertList[$a]["notifyto"], $emailList ) ) {
169 
170  $sql = "UPDATE cu_alerts
171  SET notifyto='{$HB_ENV['HCUPOST']['email']}'
172  WHERE user_id={$HB_ENV["Uid"]}
173  AND id={$alertList[$a]["id"]}";
174 
175  db_query($sql, $dbh);
176  }
177  }
178 
179  }
180  }
181 
182  break;
183  case "read_alert_emails":
184 
185  $emailAlertList = array();
186  $alertInfo = Get_AlertsDetailed( $dbh, $HB_ENV["Cu"], $HB_ENV["Uid"], $HB_ENV["Fset3"]);
187  $alertList = $alertInfo["data"];
188  $defaultEmail = $HB_ENV['Ml'];
189 
190  for( $i = 0; $i < count($alertList); $i ++) {
191  if( $alertList[$i]['emailtype'] == 'E' ) {
192  $found = false;
193 
194  for ($j = 0; $j < count( $emailAlertList ); $j++ ) {
195  if($emailAlertList[$j]['email'] == $alertList[$i]['notifyto']) {
196  $found = true;
197 
198  if( $emailAlertList[$j]["type"] != $alertList[$i]["type_name"] ) {
199  $emailAlertList[$j]["type"] = "Multiple";
200  }
201  }
202  }
203 
204  if (!$found) {
205  $emailAlertList[] = array(
206  "id" => $i,
207  "type" => $alertList[$i]["type_name"],
208  "email" => $alertList[$i]["notifyto"],
209  "choice" => $alertList[$i]["notifyto"] == $defaultEmail ? "Y" : "N" );
210  }
211  }
212  }
213 
214  $aryResult = $emailAlertList;
215 
216  break;
217  case "pwd_save":
218  // validate the inputs
219 
220  // set up what the verification/update functions expect
221  $updFields['settings_password']['current'] = $HB_ENV['HCUPOST']['old'];
222  $updFields['settings_password']['newpasswd'] = $HB_ENV['HCUPOST']['new1'];
223  $updFields['settings_password']['confpasswd'] = $HB_ENV['HCUPOST']['new2'];
224 
225  // check if the guidelines were checked
226  if ( $HB_ENV['HCUPOST']['sawhints'] != "Y" ) {
227  $aryErrors[] = array( "message" => $MC->msg('Please review the password guidelines', HCU_DISPLAY_AS_RAW) );
228 
229  throw new Exception (HCU_JsonEncode($aryErrors));
230  }
231 
232  $aryResult = Validate_PwdRules( $dbh, $HB_ENV, $updFields, $MC );
233 
234  // check if the requirements were met
235  if ( $aryResult["status"]["code"] != '000' ) {
236  for ( $e = 0; $e < count( $aryResult["status"]["errors"] ); $e++ ) {
237  $aryErrors[] = array( "message" => $aryResult["status"]["errors"][$e] );
238  }
239 
240  throw new Exception (HCU_JsonEncode($aryErrors));
241  }
242 
243  // * are we verifying the email address
244  $aryUpdate = Validate_Settings($dbh, $HB_ENV, $updFields, $MC);
245 
246  if ($aryUpdate['status']['code'] == '000') {
247  $aryUpdate = Update_User_Settings($dbh, $HB_ENV, $MC, $updFields, false);
248 
249  if ($aryUpdate['status']['code'] != '000') {
250  // an error occurred, convert the error into an id:message pair, if we know the id (field name)
251  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
252  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
253  }
254 
255  throw new Exception (HCU_JsonEncode($aryErrors));
256  } else {
257  // return success
258  $aryResult["success"] = 0;
259 
260  // ** If the Ffchg flag is set to Y -- Then reset to N
261  SetTicket($HB_ENV, $_COOKIE['Ticket'],"Ffchg=N");
262 
263  // return status
264  $aryInfo = array( "message" => $MC->msg('Update Completed', HCU_DISPLAY_AS_RAW) );
265  }
266  } else {
267  // convert the error into an id:message pair, if we know the id (field name)
268  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
269  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
270  }
271 
272  throw new Exception (HCU_JsonEncode($aryErrors));
273  }
274 
275  break;
276  case "challenge_save":
277  // validate the inputs
278 
279  if ($HB_ENV['HCUPOST']['security_token'] != '') {
280  // * we are being passed the security token -- NOW
281  // ** GET THE CURRENT PASSWORD
282  $mbrPwd = GetUserInfo($dbh, $HB_ENV, $MC, Array("user_id" => $HB_ENV['Uid'], "cu" => $HB_ENV['Cu']));
283 
284  if ($mbrPwd['status']['code'] != '000') {
285  // ** An error occurred retrieving the saved password hash value
286  for ( $e = 0; $e < count( $mbrPwd["status"]["errors"] ); $e++ ) {
287  $aryErrors[] = array( "message" => $mbrPwd["status"]["errors"][$e] );
288  }
289  } else {
290  // ** Create the security token again to test validit
291  // ** Get the database pwd hashed value
292  $mbrPwdHash = $mbrPwd['data']['cuusers_passwd'];
293 
294  $randomNbr = Return_Random4Challenge($HB_ENV);
295 
296  $aryMbrChg = Get_MemberChallengeResponses($dbh, $HB_ENV, $HB_ENV['Cn']);
297 
298  // sort the choices in order for consistency
299  $choices = array();
300  foreach ($aryMbrChg as $questId => $questResp) {
301  $choices[] = $questId;
302  }
303  sort( $choices );
304  $choiceString = implode( $choices );
305 
306  // * Create the security token - - HASHED PWD + RANDOM NBR + current challenge choices + SECRET
307  $securityToken = sha1($mbrPwdHash . $randomNbr . $choiceString . $HB_ENV['secret']);
308 
309  if ($securityToken == $HB_ENV['HCUPOST']['security_token']) {
310  $act = "validated";
311  } else {
312  $aryErrors[] = array( "message" => $MC->msg('Invalid Authentication', HCU_DISPLAY_AS_RAW) );
313  }
314  }
315  } else {
316  $aryErrors[] = array( "message" => $MC->msg('Invalid Authentication', HCU_DISPLAY_AS_RAW) );
317  }
318 
319  if ( count( $aryErrors ) ) {
320  throw new Exception (HCU_JsonEncode($aryErrors));
321  }
322 
323  // ** If no Errors were found then update database
324  // ** Create the field list array
325 
326  $updFields['settings_confidence']['confword'] = $HB_ENV['HCUPOST']['security_confidence'];
327  if ($HB_ENV['Ffreset'] > 0) {
328  // ** Update userflags if MEM_FORCE_RESET is set
329  if (HCU_array_key_exists('cuusers_userflags', $mbrPwd['data'])) {
330  // * data structure exists for mbrPwd -- reset the field if 'userflags' EXISTS
331  // ** Userflags -- Reset the MEM_FORCE_RESET flag?
332 
333  $tmpVal = (int) HCU_array_key_value('cuusers_userflags', $mbrPwd['data']);
334  // ** NEGATE the MEM_FORCE_RESET value
335  $tmpVal = ~(~$tmpVal | GetUserFlagsValue('MEM_FORCE_RESET'));
336 
337  $updFields['settings_confidence']['userflags'] = $tmpVal;
338  }
339  }
340 
341  $questIdx = 0;
342  $newChoices = array();
343  if (intval($HB_ENV['flagset3'] & GetFlagsetValue("CU3_MFA_AUTHCODE")) === 0) {
344  while(HCU_array_key_exists("security_qst{$questIdx}", $HB_ENV['HCUPOST'])) {
345  $updFields['settings_questions'][] = Array('cqid' => $HB_ENV['HCUPOST']["security_qst{$questIdx}"], 'display' => $HB_ENV['HCUPOST']["security_rsp{$questIdx}"]);
346 
347  // save the new choices in case returning an updated token
348  $newChoices[] = $HB_ENV['HCUPOST']["security_qst{$questIdx}"];
349 
350  $questIdx++;
351  }
352  }
353  // ** get update for phone numbers
354  if (HCU_array_key_exists("security_phones", $HB_ENV['HCUPOST'])) {
355  $phonesJson = $HB_ENV['HCUPOST']['security_phones'];
356  $phonesAry = HCU_JsonDecode($phonesJson);
357  $updFields['settings_phones']['mobile'] = $phonesAry['mobile'];
358  /* AT THIS TIME DO NOT SAVE HOME/WORK */
359  }
360 
361  // * are we verifying the email address
362  $aryUpdate = Validate_Settings($dbh, $HB_ENV, $updFields, $MC);
363 
364  if ($aryUpdate['status']['code'] == '000') {
365  // since the security phone number are part of a different table
366  // we must update them separately from the Update_User_Settings
367  // function.
368  // only update if the mfa secure access coed flag is set
369  $aryUpdate = Update_User_Security($dbh, $HB_ENV, $MC, $updFields);
370  if ($aryUpdate['status']['code'] != '000') {
371  // an error occurred, convert the error into an id:message pair, if we know the id (field name)
372  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
373  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
374  }
375 
376  throw new Exception (HCU_JsonEncode($aryErrors));
377  }
378 
379  // update user table information.
380  $aryUpdate = Update_User_Settings($dbh, $HB_ENV, $MC, $updFields, false);
381  if ($aryUpdate['status']['code'] != '000') {
382  // an error occurred, convert the error into an id:message pair, if we know the id (field name)
383  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
384  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
385  }
386 
387  throw new Exception (HCU_JsonEncode($aryErrors));
388  } else {
389 
390  // return success, and the updated security_token
391  sort( $newChoices );
392  $choiceString = implode( $newChoices );
393 
394  // * Create the security token - - HASHED PWD + RANDOM NBR + current challenge choices + SECRET
395  $aryResult["security_token"] = sha1($mbrPwdHash . $randomNbr . $choiceString . $HB_ENV['secret']);
396 
397  $aryResult["success"] = 0;
398 
399  // return status
400  $aryInfo = array( "message" => $MC->msg('Update Completed', HCU_DISPLAY_AS_RAW) );
401  }
402  } else {
403  // convert the error into an id:message pair, if we know the id (field name)
404  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
405  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
406  }
407 
408  throw new Exception (HCU_JsonEncode($aryErrors));
409  }
410 
411  break;
412  case "usr_save":
413  $Cu = $HB_ENV["Cu"];
414  $Cn = $HB_ENV["Cn"];
415 
416  $old = $HB_ENV['HCUPOST']['old'];
417  $userAlias = $HB_ENV['HCUPOST']['user_alias'];
418  $userAlias2 = $HB_ENV['HCUPOST']['user_alias2'];
419 
420  # validate that password entered matches password in db
421  $sql = "select passwd from {$Cu}user where user_name='$Cn'";
422  $sth = db_query($sql,$dbh);
423 
424  list($savedPasswd) = db_fetch_array($sth,0);
425  db_free_result($sth);
426 
427  $savedPasswd = preg_replace("/ +$/","",$savedPasswd);
428  if (!password_verify($old, $savedPasswd)) {
429  $aryErrors[] = array( "message" => $MC->msg('Invalid Authentication', HCU_DISPLAY_AS_RAW) );
430 
431  throw new Exception (HCU_JsonEncode($aryErrors));
432  }
433 
434  // **** VALIDATE INFORMATION
435  $upd_fields['settings_password']['current'] = $old;
436  $upd_fields['settings_alias']['username'] = $userAlias;
437  $upd_fields['settings_alias']['username_confirm'] = $userAlias2;
438  $aryUpdate = Validate_Settings($dbh, $HB_ENV, $upd_fields, $MC);
439 
440  // UNSET SO WE DON'T CHANGE PASSWORD
441  unset($upd_fields['settings_password']);
442 
443  if ($aryUpdate['status']['code'] == '000') {
444 
445  $aryUpdate = Update_User_Settings($dbh, $HB_ENV, $MC, $upd_fields, false);
446  }
447 
448  if ($aryUpdate['status']['code'] != '000') {
449  // an error occurred
450  $aryErrors = array();
451  for ( $e = 0; $e < count( $aryUpdate["status"]["errors"] ); $e++ ) {
452  $aryErrors[] = array( "message" => $aryUpdate["status"]["errors"][$e] );
453  }
454 
455  throw new Exception (HCU_JsonEncode($aryErrors));
456  } else {
457 
458  // UPDATE COOKIE TO AVOID THROWING USER TO PROFILEREQUIRE.PRG
459  $_COOKIE['Ticket'] = SetTicket($HB_ENV, $_COOKIE['Ticket'],"Cn=$userAlias");
460  $HB_ENV['Cn'] = $userAlias; // update HB_ENV with new name
461  }
462 
463  // if we made it here then the update was successful
464  $aryInfo = array( "message" => $MC->msg('Member Settings Changed', HCU_DISPLAY_AS_RAW) );
465  break;
466  case "acct_desc_read":
467  $HB_ENV["doEncrypt"]= true;
468 
469  // GET ACCOUNT BALANCES FOR TYPES AND DESCRIPTIONS
470  $arry_balances = Get_Balances($dbh, $HB_ENV, $callerContext="acct_desc_read");
471  // ERRORS
472  if ($arry_balances['status']['code'] != '000') {
473  // an error occurred
474  $arry_errors = array();
475  for ( $e = 0; $e < count( $arry_balances["status"]["errors"] ); $e++ ) {
476  $arry_errors[] = array( "message" => $arry_balances["status"]["errors"][$e] );
477  }
478 
479  throw new Exception (HCU_JsonEncode($arry_errors));
480  }
481 
482  // CONSTRUCT RETURN DATA
483  $aryResult = array("dp" => array(), "ln" => array(), "cc" => array());
484  foreach ($arry_balances as $type => $data) {
485  // first part of data is always status code
486  // skip it.
487  if ($type === "status") { continue; }
488 
489  foreach ($data as $value) {
490  // ADD NEEDED ITEMS TO RETURN ARRAY
491  $aryResult[$type][] = array("displayorder" => $value["displayorder"], "displayname" => $value["displayname"], "encryption" => $value["encryption"],
492  "placeholder" => $value['description'], "title" => $value["description"]);
493  }
494  }
495 
496  break;
497 
498  case "acct_desc_update":
499  // ACCOUNT NUMBER AND CU NEEDED FOR DATA ACCESS
500  $Cu = $HB_ENV['Cu'];
501  $Ci = $HB_ENV['Uid'];
502 
503  // GET UPDATE DATA
504  $update = $HB_ENV['HCUPOST']['account_data'];
505 
506  $accountDesc = array();
507  foreach ($update as $account) {
508  // CAPTURE ALL ACCOUNT USER DEFINED NAMES
509  if ( HCU_array_key_exists("displayname", $account) && $account["displayname"] != "") {
510  $accountDesc[] = strtolower($account["displayname"]);
511  }
512  }
513 
514  // UPDATE DATABASE
515  $sqls = "";
516  foreach ($update as $account) {
517 
518  if (!HCU_array_key_exists("displayname", $account) || !HCU_array_key_exists("displayorder", $account) || !HCU_array_key_exists("encryption", $account))
519  throw new exception(array($MC->msg("Error Occurred updating settings", HCU_DISPLAY_AS_RAW)), 101);
520 
521  // Get variables to update
522  $name = prep_save(trim($account["displayname"]), 255);
523  $order = intval($account["displayorder"]);
524 
525  // Get key
526  $encryption= HCU_PayloadDecode($Cu, $account["encryption"]);
527 
528  $recordType = $encryption[0];
529  /*
530  * If accountType has a '#' then this is a CrossAccount
531  * recordtype values are {T, P}
532  */
533  if (strpos($encryption[2], '#')) {
534  // * we know it's a cross account -- set accordingly using the current value of recordType
535  $recordType = ($recordType == "D" ? "T" : "P");
536  } else {
537  $recordType = prep_save($recordType == "C" ? "L" : $recordType, 1);
538  }
539  $accountNumber = prep_save($encryption[1], 12);
540  $accountType = prep_save($encryption[2], 25);
541  $certNumber = $recordType == "D" ? intval($encryption[3]) : 0;
542 
543  // SET SQL QUERY
544  $sql = "
545  UPDATE {$Cu}useraccounts
546  SET
547  display_name= '$name',
548  display_order= '$order'
549  WHERE user_id= '$Ci'
550  AND accountnumber= '$accountNumber'
551  AND accounttype= '$accountType'
552  AND recordtype= '$recordType'
553  AND certnumber= $certNumber;";
554 
555  $sqls .= $sql;
556  }
557  // SEND QUERY
558  $sth = db_query($sqls, $dbh);
559  if (!$sth) {
560  $aryErrors[] = $MC->msg("Error Occurred updating settings", HCU_DISPLAY_AS_RAW);
561  } else {
562  db_free_result($sth);
563  $aryInfo[] = $MC->msg("Member Settings Changed", HCU_DISPLAY_AS_RAW);
564  }
565 
566  if ( count($aryErrors) ){
567  throw new Exception (HCU_JsonEncode($aryErrors));
568  }
569  break;
570 
571  default:
572  $aryErrors[] = array( "message" => "Unexpected action: {$HB_ENV["HCUPOST"]["action"]}" );
573  throw new Exception (HCU_JsonEncode($aryErrors));
574  break;
575  }
576 }
577 catch(Exception $ex)
578 {
579  //Return error message
580  $aryReply["homecuErrors"] = HCU_JsonDecode( $ex->getMessage() );
581 
582  // if an error, don't return data
583  $aryResult = array();
584 
585  // if an error, don't return info
586  $aryInfo = array();
587 
588  // don't update cookie if came through here - clear existence flag to cause non-update
589  //$Cookie2FactorSet = false;
590 }
591 
592  $usrInfo = GetUserbyName($HB_ENV['dbh'], $HB_ENV['Cu'], $HB_ENV['Cn']);
593  $usrDeviceCookieSame = isValidDeviceCookie($HB_ENV['Cu'], $usrInfo);
594 
595  // Update the device cookie. For apps, always return the update. For Web-based
596  // continue the same way.
597  if ( $HB_ENV["platform"] == "ADA" || $HB_ENV["platform"] == "APP") {
598  // Apps will add the updated username or password on the client side.
599 
600  // Get the MFA mode (authcode or not) flag
601  $mfaMode = (intval($HB_ENV['Fset3'] & GetFlagsetValue('CU3_MFA_AUTHCODE')));
602 
603  // Get the mfadate from the UserRec
604  $mfaDate = HCU_array_key_value("mfadate", $usrInfo);
605 
606  $cookieParams = array ( "cu" => $HB_ENV["cu"],
607  "user_name" => $usrInfo["user_name"],
608  "saved_pass" => $usrInfo["passwd"],
609  "saved_email" => $usrInfo['email'],
610  "saved_confidence" => $usrInfo['confidence'],
611  "mfa_mode" => $mfaMode,
612  "mfa_date" => $mfaDate,
613  "persists_time" => $HB_ENV['SYSENV']['ticket']['persists']
614  );
615 
616  $cookieInfo = CreateDeviceCookie( $cookieParams);
617 
618  // add the app device cookie to the return information for apps
619  if ( strlen( $cookieInfo["name"] ) > 0 ) {
620  $returnCookieInfo = $cookieInfo["name"] . "|" . $cookieInfo["content"] . "|" . $cookieInfo["expire"];
621  $aryResult["homecuKey"] = $returnCookieInfo;
622  }
623  } else {
624  if ($usrDeviceCookieExists && !$usrDeviceCookieSame) {
625  // ** refetch the member information
626  $mbrInfo = GetUserInfo($dbh, $HB_ENV, $MC, Array("user_id" => $HB_ENV['Uid'], "cu" => $HB_ENV['Cu']));
627  // ** if we were able to retrieve the member data
628  if ($mbrInfo['status']['code'] == '000') {
629  // * Set fields for setting the cookie
630  $HB_ENV['cu'] = $HB_ENV['Cu'];
631  $HB_ENV['username'] = $HB_ENV['Cn'];
632  $HB_ENV['savepass'] = trim($mbrInfo['data']['cuusers_passwd']);
633  $HB_ENV['savemail'] = trim($mbrInfo['data']['cuusers_email']);
634  $HB_ENV['confidence'] = trim($mbrInfo['data']['cuusers_confidence']);
635 
636  // ** Pass in an equivalent to the userrec
637  SetDeviceCookie($HB_ENV, $mbrInfo['data']);
638  }
639  }
640  }
641 
642  if ( count( $aryResult ) ) $aryReply["homecuData"] = $aryResult;
643 
644  if ( count( $aryInfo ) ) $aryReply["homecuInfo"] = $aryInfo;
645 
646  print HCU_JsonEncode($aryReply);