Odyssey
hcuActivate.prg
1 <?php
2 /*
3  * File: hcuActivate
4  *
5  * Purpose: Allow the member to sign up for digital banking. Notify CU. Handle
6  * case where member signed up but wasn't able to sign up for E-Statements.
7  * Generate an initial password for the member.
8  *
9  * This script will use Custom Content files: ActivateMember, ActivateMemberThanks, signupDisclosure, and
10  * esTermsStart. The secure form enrollment uses signupFrm and signupThanks.
11  *
12  *
13  * ** MIR PACKET ENROLLMENT **
14  * ** mobile1 **
15  * ** This value will be considered a valid mobile number for the user. It will NOT be validated against any
16  * ** value from the core.
17  * ** custom2 **
18  * ** This value has not changed. --FUTURE ENHANCEMENT - Could add a checkbox that will set the mobile1 value
19  * ** if the user specifies the number as a valid mobile. This can be done on the client piece.
20  *
21  *
22  */
23 
24  // ** SET SCRIPT LEVEL VARIABLE
25 
26  // ** INCLUDE MAIN GLOBAL SCRIPT -- Handles security / global variable values
27  $serviceSkipCredentials = true;
28  $serviceSkipSecurity = true;
29  $serviceShowInfo = false;
30  $serviceLoadMenu = false;
31  $serviceLiveCheck = true;
32 
33  require_once(dirname(__FILE__) . '/../library/hcuService.i');
34 
35  // ** IMPORT Variables from form
36  $dmsValuesList = array(
37  'reqfields' => 'string', 'reqtitles' => 'string', 'reqtypes' => 'string', 'member' => 'digits',
38  'ref1' => 'string', 'ref2' => 'string', 'ref3' => 'string', 'custom1' => 'string', 'custom2' => 'string',
39  'mobile1' => 'string','ref5' => 'string', 'optin'=>'string', 'action' => 'string', "pin" => "string",
40  "pfirst" => "string", "pmid" => "string", "plast" => "string", "confirm" => "string",
41  "ssn" => "string", "bdate" => "string", "email" => "string", "class" => "string",
42  "addr" => "string", "city" => "string", "state" => "string", "zip" => "string",
43  "home" => "string", "cell" => "string", "work" => "string", "workext" => "string",
44  "password" => "string", "hint" => "string", "previousDate" => "string",
45  "agree" => "string", "g-recaptcha-response" => "string" );
46 
47  dms_import_v2($HB_ENV, 'HCUPOST', $dmsValuesList);
48 
49  $action = $HB_ENV["HCUPOST"]["action"];
50 
51  // They are used for the secure form method but initialize them here so that there aren't any E_NOTICEs.
52  $pmid = "";
53  $addr = "";
54  $city = "";
55  $state = "";
56  $zip = "";
57  $home = "";
58  $cell = "";
59  $work = "";
60  $workext = "";
61  $agree = "";
62 
63  /**
64  * function CheckUserMemberValidity($member, $HB_ENV, &$msg, &$userFound)
65  * Checks to see what error to display (if any)
66  *
67  * @param $member -- the account number
68  * @param $HB_ENV -- the environment variables
69  * @param $msg -- the error message to append to
70  * @param $userFound -- the user found boolean is used elsewhere
71  */
72  function CheckUserMemberValidity($member, $HB_ENV, &$msg, &$userFound) {
73  $MC = $HB_ENV["MC"];
74  if ( "$member" != "" && is_numeric($member)) {
75  $canActivateUser = CanActivateUser($HB_ENV, $member);
76  $memberFound = $canActivateUser["memberExists"];
77  $userFound = $canActivateUser["userExists"];
78 
79  // ALLOW ENROLL FIELD REPLACES SEEING IF THE PRIMARY ACCOUNT IS SET
80  if (!$memberFound || $canActivateUser["allowEnroll"]) {
81 
82  // CHECK USER EXISTS
83  if ($userFound) {
84  # CHECK USER PASSWORD NOT NULL
85  if (!$canActivateUser["isNullPassword"]) {
86  if ($HB_ENV['flagset'] & GetFlagsetValue("CU_MEMRESET")) {
87  $msg .= $MC->combo_msg("Activate member already exists", HCU_DISPLAY_AS_HTML, "#reset_link#", "{$HB_ENV['loginpath']}/hcuResetPwd.prg?{$HB_ENV['cuquery']}");
88  } else {
89  $msg .= $MC->msg("Member number already setup", HCU_DISPLAY_AS_HTML) . "<br>";
90  }
91  }
92 
93  # CHECK IF USER IS LOCKED
94  if ($canActivateUser["isNullPassword"] && $canActivateUser["isFailed"]) {
95  $msg .= $MC->msg("Account is Locked", HCU_DISPLAY_AS_HTML) . "<br>";
96  }
97  }
98 
99 
100  } else {
101  # MEMBER DOES NOT ALLOW ENROLL, ERROR
102  if ($HB_ENV['flagset'] & GetFlagsetValue("CU_MEMRESET")) {
103  $msg .= $MC->combo_msg("Activate member already exists", HCU_DISPLAY_AS_HTML, "#reset_link#", "{$HB_ENV['loginpath']}/hcuResetPwd.prg?{$HB_ENV['cuquery']}");
104  } else {
105  $msg .= $MC->msg("Member number already setup", HCU_DISPLAY_AS_HTML) . "<br>";
106  }
107  }
108  }
109  }
110 
111  /**
112  * function printMemberThanks($ref3, $newpass, $HB_ENV, $cu, $Flang, $MC, $thanksContent)
113  * Prints out the member activation thanks custom content with some string substitution.
114  *
115  * @param $ref3 -- The email used for the form.
116  * @param $newpass -- The password used for the form.
117  * @param $HB_ENV -- the environment variables.
118  * @param $cu -- the credit union.
119  * @param $Flang -- the language selected.
120  * @param $MC -- the dictionary (needed for thankyou and clickhere translation.)
121  * @param $thanksContent -- the custom content to string replace.
122  */
123  function printMemberThanks($ref3, $newpass, $HB_ENV, $cu, $Flang, $MC, $thanksContent, $member) {
124  print strtr(
125  $thanksContent["notice"][0]["notice_text"],
126  array(
127  "#passwd#" => $newpass,
128  "#ref3#" => $ref3,
129  "#thankyou#" => $MC->msg('Thank You', HCU_DISPLAY_AS_HTML),
130  "#targetString#" => $HB_ENV["loginscript"] . "?cu={$cu}&Flang=$Flang",
131  "#clickhere#" => $MC->msg("Click Here", HCU_DISPLAY_AS_HTML),
132  "#memnumber#" => $member
133  )
134  );
135 
136  print strtr(
137  "<div class=\"col-xs-12\"><a class=\"k-button hide-for-apps\" href=\"#targetString#\" target=\"_top\">#clickhere#</a></div>",
138  array(
139  "#targetString#" => $HB_ENV["loginscript"] . "?cu={$cu}&Flang=$Flang",
140  "#clickhere#" => $MC->msg("Return To Home Banking", HCU_DISPLAY_AS_HTML)
141  )
142  );
143  }
144 
145 
146  /**
147  * function getDefaultProfileName($pEnv)
148  * This gets the default profile name which has been decreed to be "DEF". Perhaps this will be varied based on CU.
149  * @param array $pEnv -- the environment
150  * @return string of the profile name
151  */
152  function getDefaultProfileName($pEnv) {
153  $cu = $pEnv['Cu'];
154  $dbh = $pEnv['dbh'];
155 
156  $sql = "select settings::json->>'profile' as default_profile from cuadmin where cu = '$cu'";
157  $sth = db_query($sql, $dbh);
158  if(!$sth) {
159  throw new Exception("default profile query failed.", 2);
160  }
161  $dftprofile = db_fetch_row($sth, 0)[0];
162  return $dftprofile;
163  }
164 
165  /**
166  * function addUserTransaction($dbh, $member, $cu, $hash, $ref3, $egenl_flag, $HB_ENV, $MC, $retry, $phoneNumber, $estatements)
167  * This function adds a user, group to the default profile for the CU.
168  *
169  * @param $dbh -- the database connection
170  * @param $member -- the account number to add the user for
171  * @param $cu -- the credit union
172  * @param $hash -- the hash needed for the password
173  * @param $ref3 -- the email address
174  * @param $egenl_flag -- the egenl flag (I have no idea what this is; some optin or whatnot.)
175  * @param $HB_ENV -- the environment variables
176  * @param $MC -- the dictionary
177  * @param $retry -- the amount of times to retry
178  * @param $phoneNumber -- save the phone number too
179  * @param $estatements -- if true, add the estatement right record.
180  * @param $accountData -- the PIN method gets the data. Do not call the FindMemberAccounts function in this case.
181  *
182  * @return boolean : true if transaction was successful. False if the transaction wasn't started or it was rolled back.
183  */
184  function addUserTransaction($dbh, $member, $cu, $hash, $ref3, $egenl_flag, $HB_ENV, $MC, $retry, $phoneNumber, $estatements, $accountData = null) {
185  try {
186  $logger = $HB_ENV["SYSENV"]["logger"];
187  $sql = "select user_id, user_name, group_id, email from {$cu}user where user_name = '$member'";
188  $sth = db_query($sql, $dbh);
189  if (!$sth) {
190  throw new exception("User select query failed.", 1);
191  }
192 
193  $groupExists = false;
194  $userTable = array(
195  'user_name' => $member,
196  "is_group_primary" => true,
197  'passwd' => $hash,
198  'email' => $ref3,
199  'failedremain' => $retry,
200  'forcechange' => "Y",
201  'forceremain' => 1,
202  'egenl_flag' => $egenl_flag,
203  'pwchange' => 'now',
204  "userflags" => 2);
205  $groupTable = array(
206  "group_name" => "g$member",
207  "contact" => 0
208  );
209 
210  if ($phoneNumber != '') {
211  // ** Only properly format if it is entered
212  $phoneNumber = preg_replace('/\D+/', "", $phoneNumber);
213  $phoneNumber = "(" . substr($phoneNumber, 0, 3) . ") " . substr($phoneNumber, 3, 3) . "-" . substr($phoneNumber, 6);
214  $phoneArray = array("mobile" => Array($phoneNumber));
215  } else {
216  $phoneArray = array("mobile" => Array());
217  }
218  $phoneTable = array("_action" => "create", "phones" => HCU_JsonEncode($phoneArray));
219 
220  if (db_num_rows($sth) > 0) {
221  $row = db_fetch_assoc($sth, 0);
222  $userTable["user_id"] = $row["user_id"];
223  $userTable["_action"] = "update";
224 
225  if (isset($row["group_id"])) {
226  $groupId = $row["group_id"];
227  $sql = "select group_id from ${cu}group where group_id = " . intval($row["group_id"]);
228  $sth = db_query($sql, $dbh);
229  if (!$sth) {
230  throw new exception("Group select query failed.", 2);
231  }
232  $groupExists = db_num_rows($sth) > 0;
233  }
234 
235  $userShort = "U_UPD";
236  } else {
237  $userTable["user_id"] = "";
238  $userTable["_action"] = "create";
239  $userShort = "U_ADD";
240  }
241 
242  $sql = "select profile_id from cu_profile where cu = '$cu' and profile_code = '" . getDefaultProfileName($HB_ENV) . "'";
243  $sth = db_query($sql, $dbh);
244  if (!$sth) {
245  throw new exception("Default profile select query failed.", 5);
246  }
247  $profileId = db_fetch_row($sth, 0)[0];
248  $profileId = isset($profileId) ? intval($profileId) : 0;
249  if ($profileId == 0) {
250  throw new exception("Group needs to be attached to the default profile which apparently doesn't exist.", 6);
251  }
252 
253  $groupTable["profile_id"] = $profileId;
254 
255  if (!$groupExists) {
256  $sql = "select nextval('${cu}group_group_id_seq'::regclass)";
257  $sth = db_query($sql, $dbh);
258  if (!$sth) {
259  throw new exception("Nextval query failed.", 3);
260  }
261  $groupId = intval(db_fetch_row($sth, 0)[0]);
262 
263  $userTable["group_id"] = $groupId;
264  $groupTable["group_id"] = $groupId;
265  $groupTable["_action"] = "create";
266 
267  $groupShort = "G_ADD";
268  } else {
269  $groupTable["_action"] = "update";
270  $groupTable["group_id"] = $groupId;
271 
272  $groupShort = "G_UPD";
273  }
274 
275  // Ensure that it isn't necessary to back out from the select functions before changing anything in the database.
276  /*
277  * User Activation occurs prior to the Session cookie being created.
278  * The low level functions are looking for the Fset flags rather than their counterpart 'flagset'
279  * Set the Fset values here so they can be called at the lower leve.
280  * The reason not to just change low level functions to use the flagset is to keep in mind the AppFeed script
281  * may also call those functions and may not have those values set
282  */
283  $HB_ENV['Fset'] = $HB_ENV['flagset'];
284  $HB_ENV['Fset2'] = $HB_ENV['flagset2'];
285  $HB_ENV['Fset3'] = $HB_ENV['flagset3'];
286 
287  if (!isset($accountData)) {
288  $accountData = FindMemberAccounts($HB_ENV, array("member" => $member));
289  switch ($accountData["code"]) {
290  case "001":
291  throw new exception("No data was found.", 6);
292  break;
293  case "999":
294  throw new exception($accountData["error"], 7);
295  break;
296  case "000":
297  break; // The correct case with data.
298  default:
299  throw new exception("There was an internal problem.", 8);
300  break;
301  }
302  } else if (is_array($accountData)) {
303 
304  // Now need to validate it to see if it is the same format.
305  if (!HCU_array_key_exists("code", $accountData) || $accountData["code"] != "000") {
306  throw new exception("Data is in a bad format.", 12);
307  }
308 
309  if (!HCU_array_key_exists("data", $accountData) || !HCU_array_key_exists("accounts", $accountData["data"])) {
310  throw new exception("Data is in a bad format.", 13);
311  }
312  } else {
313  throw new exception("Data is in a bad format.", 11);
314  }
315 
316  $sql = "select ma.accountnumber, ma.primary_user, ma.allowenroll, u.user_id, ma.estmnt_flag from ${cu}memberacct ma
317  left join ${cu}user u on ma.primary_user = u.user_id where trim(ma.accountnumber) = '$member'";
318  $sqls[] = $sql;
319  $sth = db_query($sql, $dbh);
320  if (!$sth) {
321  throw new exception("Select query failed.", 14);
322  }
323  $memberAcctExists = $userExists = db_num_rows($sth) > 0;
324  $changePrimaryUser = false;
325  $allowEnroll = false;
326  $changeEstatements = false; // If estatements is already set to Y, don't modify that. If it is any other value, then change it to the estatement flag.
327  if ($memberAcctExists) {
328  $row = db_fetch_assoc($sth, 0);
329  $userExists = isset($row["user_id"]);
330  $changePrimaryUser = intval($row["primary_user"]) == 0 || !isset($row["user_id"]); // Set the primary user if it is zero or if it doesn't relate to a user.
331  $allowEnroll = $row["allowenroll"];
332  $changeEstatements = !isset($row["estmnt_flag"]) || trim($row["estmnt_flag"]) != "Y"; // Set the estatement flag if it doesn't exist or if it isn't already Yes.
333  }
334 
335  if ($memberAcctExists && !$allowEnroll) {
336  throw new exception("Member account doesn't allow member activation.", 9);
337  }
338 
339  $sql = "select nextval('${cu}usercontact_contact_id_seq'::regclass)";
340  $sqls[] = $sql;
341  $sth = db_query($sql, $dbh);
342 
343  if (!$sth) {
344  throw new exception("Nextval query failed.", 10);
345  }
346 
347  $contactId = intval(db_fetch_row($sth, 0)[0]);
348 
349  $phoneTable["contact_id"] = $contactId;
350  $userTable["contact"] = $contactId;
351  $groupTable["contact"] = $contactId;
352 
353  if (!db_work ($dbh, HOMECU_WORK_BEGIN)) {
354  throw new exception("Unable to begin transaction.", 4);
355  }
356 
357  $userId = HCU_array_key_exists("user_id", $userTable) ? $userTable["user_id"] : null;
358  if (DataUserTableUpdate($dbh, $HB_ENV, $MC, array("user" => array($userTable)), $userId, $userShort, $HB_ENV['platform'], $HB_ENV['currentscript'], 'U', 'Activate User', $member,
359  $ref3, $HB_ENV['remoteIp']) === false) {
360  throw new exception("User update failed.", 101);
361  }
362 
363  // Need to get the UID of the user record to associate it to the user account record. This should exist at this point.
364  $sql = "select user_id from ${cu}user where trim(user_name) = '$member'";
365  $sqls[] = $sql;
366  $sth = db_query($sql, $dbh);
367  if (!$sth) {
368  throw new exception("user_id query failed.", 104);
369  }
370  if (db_num_rows($sth) == 0) {
371  throw new exception("user_id not found.", 105);
372  }
373  $userId = intval(db_fetch_row($sth, 0)[0]);
374 
375  if (DataUserTableUpdate($dbh, $HB_ENV, $MC, array("usercontact" => array($phoneTable)), $userId, "UC_ADD", $HB_ENV['platform'], $HB_ENV['currentscript'], 'U', 'Activate User', $member,
376  $ref3, $HB_ENV['remoteIp']) === false) {
377  throw new exception("User contact failed.", 109);
378  }
379 
380  if (DataUserTableUpdate($dbh, $HB_ENV, $MC, array("group" => array($groupTable)), $userId, $groupShort, $HB_ENV['platform'], $HB_ENV['currentscript'], 'U', 'Activate User', $member,
381  $ref3, $HB_ENV['remoteIp']) === false) {
382  throw new exception("Group update failed.", 102);
383  }
384 
385  // Add subaccounts
386  $subaccountInfo = $accountData["data"]["accounts"];
387 
388  // ** List of account numbers we processed during XAC updates
389  // * list maintained to not over query an account we know we
390  // * have processed.
391  $processedMbrAcct = Array();
392 
393  foreach($subaccountInfo as $type => $subaccounts) {
394  foreach($subaccounts as $subaccount) {
395  $canWithdraw = HCU_array_key_exists("may_withdraw", $subaccount) ? !!$subaccount["may_withdraw"] :
396  (HCU_array_key_exists("may_addon", $subaccount) ? !!$subaccount["may_addon"] : false);
397  $canDeposit = HCU_array_key_exists("may_deposit", $subaccount) ? !!$subaccount["may_deposit"] :
398  (HCU_array_key_exists("may_payment", $subaccount) ? !!$subaccount["may_payment"] : false);
399 
400  if ($type == "xa") {
401  // ** Support XAC
402  if (($HB_ENV['flagset3'] & GetFlagsetValue("CU3_CREATE_ACCESS_CONTROL_FROM_XAC")) == 0) {
403  // ** XAC records get added as an overloaded type in the accounttype column 99#99999
404  $newAcctNbr = $member; // * this will always be the "main" member number that is being added
405  $newAcctSfx = HCU_array_key_value("accounttype", $subaccount) . '#' . HCU_array_key_value("tomember", $subaccount);
406  $newAcctCrt = ($type == "deposit" ? HCU_array_key_value("certnumber", $subaccount) : '0');
407  $newAcctRec = HCU_array_key_value("deposittype", $subaccount) == 'L' ? 'P' : 'T';
408 
409  } else {
410  if (trim(HCU_array_key_value("tomember", $subaccount)) == trim(HCU_array_key_value("accountnumber", $subaccount))) {
411  /* ** SKIP ** */
412  // * Skip this XAC record IF the accountnumber matches the tomember. This means it is a circular reference.
413  continue;
414  }
415  // ** XAC records get added as their own PRIMARY account -- They will have their own account setup in Access Control
416  $newAcctNbr = HCU_array_key_value("tomember", $subaccount);
417  $newAcctSfx = HCU_array_key_value("accounttype", $subaccount);
418  $newAcctCrt = '0';
419  $newAcctRec = HCU_array_key_value("deposittype", $subaccount) == 'L' ? 'L' : 'D';
420 
421  // ** Need to identify if the Member has been added to the memberacct table
422 
423  if (!in_array($newAcctNbr, $processedMbrAcct)) {
424  if (!FindMemberAccountExists ($dbh, $HB_ENV['cu'], $newAcctNbr)) {
425  // ** add the account number to the array of processed
426  $processedMbrAcct[] = $newAcctNbr;
427  // ** memberacct record NOT found
428 
429  $memberRecords = array("memberacct" => array(array("_action" => "create", "accountnumber" => $newAcctNbr, "primary_user" => 0, "allowenroll" => true)));
430 
431  if (DataUserTableUpdate($dbh, $HB_ENV, null, $memberRecords, $userId, "UM_ADD", HCU_array_key_value("platform", $HB_ENV), HCU_array_key_value('currentscript', $HB_ENV), "A", "Auto Add Member Acct", HCU_array_key_value('Cn', $HB_ENV), '', HCU_array_key_value('remoteIp', $HB_ENV)) === false) {
432  throw new exception("Adding member account relationship failed.", 110);
433  }
434 
435  }
436  }
437 
438  }
439  } else {
440  $newAcctNbr = $member; // * this will always be the "main" member number that is being added
441  $newAcctSfx = ($type == "deposit" ? $subaccount["accounttype"] : $subaccount['loannumber']);
442  $newAcctCrt = ($type == "deposit" ? HCU_array_key_value("certnumber", $subaccount) : '0');
443  $newAcctRec = ($type == "deposit" ? 'D' : 'L');
444  }
445 
446  $createRecords[] = array("_action" => "create", "user_id" => $userId, "display_name" => "",
447  "accountnumber" => $newAcctNbr, "accounttype" => $newAcctSfx,
448  "certnumber" => $newAcctCrt,
449  "recordtype" => $newAcctRec,
450 
451  "view_balances" => ($type == 'xa' ? false : true), "view_transactions" => ($type == 'xa' ? false : true), "int_deposit" => $canDeposit,
452  "ext_deposit" => ($type == 'xa' ? false : $canDeposit), "int_withdraw" => $canWithdraw, "ext_withdraw" => ($type == 'xa' ? false : $canWithdraw),
453  "display_order" => 0);
454  }
455  }
456  $createRecords = array("useraccounts" => $createRecords);
457 
458  if (DataUserTableUpdate($dbh, $HB_ENV, $MC, $createRecords, $userId, "UA_ADD", $HB_ENV['platform'], $HB_ENV['currentscript'], 'U', 'Activate User', $member,
459  $ref3, $HB_ENV['remoteIp']) === false) {
460  throw new exception("User account add failed.", 106);
461  }
462 
463  if ($memberAcctExists) {
464  $memberAcctModify = array("_action" => "update", "accountnumber" => $member, "allowenroll" => false);
465  $changePrimaryUser ? $memberAcctModify["primary_user"] = $userId : null;
466  $changeEstatements ? $memberAcctModify["estmnt_flag"] = $estatements ? "Y" : "N" : null;
467  } else {
468  $memberAcctModify = array("_action" => "create", "accountnumber" => $member, "primary_user" => $userId, "estmnt_flag" => $estatements ? "Y" : "N", "allowenroll" => false);
469  }
470 
471  $memberAcctModify = array("memberacct" => array($memberAcctModify));
472 
473  if (DataUserTableUpdate($dbh, $HB_ENV, $MC, $memberAcctModify, $userId, $memberAcctExists ? "UM_UPD" : "UM_ADD", $HB_ENV['platform'], $HB_ENV['currentscript'], 'U', 'Activate User',
474  $member, $ref3, $HB_ENV['remoteIp']) === false) {
475  throw new exception("User member modify failed.", 107);
476  }
477 
478  $official = array(
479  array("_action" => "create", "accountnumber" => $member, "user_id" => $userId, "whichright" => "ACCESS"),
480  array("_action" => "create", "accountnumber" => $member, "user_id" => $userId, "whichright" => "ES", "platform" => '["D","A"]'),
481  array("_action" => "create", "accountnumber" => $member, "user_id" => $userId, "whichright" => "BP", "platform" => '["D","A"]'),
482  array("_action" => "create", "accountnumber" => $member, "user_id" => $userId, "whichright" => "RDC", "platform" => '["D","A"]'),
483  );
484 
485  $official = array("memberacctrights" => $official);
486 
487  if (DataUserTableUpdate($dbh, $HB_ENV, $MC, $official, $userId, "MAR_ADD", $HB_ENV['platform'], $HB_ENV['currentscript'], 'U', 'Activate User',
488  $member, $ref3, $HB_ENV['remoteIp']) === false) {
489  throw new exception("Adding rights failed.", 108);
490  }
491 
492  if (!db_work ($dbh, HOMECU_WORK_COMMIT)) {
493  throw new exception("commit work failed.", 103);
494  }
495 
496  } catch(exception $e) {
497  $logger->error($e->getMessage());
498 
499  if ($e->getCode() >= 100) {
500  db_work ($dbh, HOMECU_WORK_ROLLBACK);
501  }
502  return false;
503  }
504  return true;
505  }
506 
507  /*
508  * move throtlpkt after import of cu variable
509  */
510 // NOTE: This is called in hcuService, but should hcuService be after dms_import_v2?
511 
512  $cu = $HB_ENV["cu"];
513  $cu = preg_replace("/[^A-Za-z0-9]/","",$cu);
514  $cu = substr($cu,0,12);
515  $chome = strtolower($cu);
516  $backto = "/~$chome/mindex.html";
517 
518  // this is available from hcuService: $offline = $HB_ENV["HCUPOST"]["offline"];
519 
520  $sql = "select offlinestat, coalesce(retrylimit,5), coalesce(gracelimit,3),
521  livebatch, trim(liveserver), settings::json->>'profile' from cuadmin where cu = '$cu'";
522  $sth = db_query($sql,$dbh);
523  list ($offline,$retry,$grace,$livebatch,$fetcher,$profile) = db_fetch_array($sth,0);
524 
525  $offline = (trim($offline) == '' ? 'N' : trim($offline));
526  $profile = $profile === null ? null : trim($profile);
527 
528  $self = $_SERVER['PHP_SELF'];
529 
530  $gCaptchaResponse = trim( $HB_ENV["HCUPOST"]['g-recaptcha-response'] );
531 
532  // these fields are always supplied for the ActivateMember form (might only be one of custom1, custom2)
533  $ref1 = htmlentities(trim($HB_ENV["HCUPOST"]["ref1"]));
534  $ref2 = htmlentities(trim($HB_ENV["HCUPOST"]["ref2"]));
535  $ref3 = htmlentities(trim($HB_ENV["HCUPOST"]["ref3"])); // this is always the email
536  $previousDate = htmlentities(trim($HB_ENV["HCUPOST"]["previousDate"]));
537  $custom1 = htmlentities(trim($HB_ENV["HCUPOST"]["custom1"])); // if provided, it is the numeric portion of address
538  $custom2 = htmlentities(trim($HB_ENV["HCUPOST"]["custom2"])); // if provided, it is the home phone number (but could be cell number)
539  $mobile1 = htmlentities(trim($HB_ENV['HCUPOST']['mobile1'])); // (optional) A mobile phone to save to the user's contact record
540 
541  // this may or may not be supplied for the ActivateMember form
542  $class = HCU_array_key_exists("class", $HB_ENV["HCUPOST"]) ? strtoupper(trim($HB_ENV["HCUPOST"]["class"])) : "";
543  $class = $class == "B" ? "B" : "";
544 
545  // these are only needed for the secure form validation
546  $member = htmlentities(trim($HB_ENV["HCUPOST"]["member"])); // ACTUALLY, this is also used for all member activation forms (secure form, regular, and PIN.)
547  $pfirst = htmlentities(trim($HB_ENV["HCUPOST"]["pfirst"]));
548  $plast = htmlentities(trim($HB_ENV["HCUPOST"]["plast"]));
549  $ssn = htmlentities(trim($HB_ENV["HCUPOST"]["ssn"]));
550  $bdate = htmlentities(trim($HB_ENV["HCUPOST"]["bdate"]));
551  $email = htmlentities(trim($HB_ENV["HCUPOST"]["email"])); // ACTUALLY, this is also used in the PIN option.
552  $password = htmlentities(trim($HB_ENV["HCUPOST"]["password"]));
553  $hint = htmlentities(trim($HB_ENV["HCUPOST"]["hint"]));
554 
555  // Only needed for PIN
556  $confirm = htmlentities(trim($HB_ENV["HCUPOST"]["confirm"]));
557  $pin = htmlentities(trim($HB_ENV["HCUPOST"]["pin"]));
558 
559  // ** INCLUDE PRE CONTENT SCRIPT
560  require_once(dirname(__FILE__) . '/../includes/hcuPreContent.i');
561 
562  ?>
563  <style type="text/css">
564  .container-fluid-margin {
565  margin: 15px;
566  }
567 
568  .k-block > .k-header {
569  white-space: normal;
570  height: 100%;
571  }
572 
573  .hcu-info-margin, .hcu-error-margin {
574  margin: 15px 0;
575  }
576 
577  .hcu-info-padding, .hcu-error-padding {
578  padding: 15px;
579  }
580 
581  .hcu-full-width {
582  width: 100%;
583  }
584  /* top-bottom margin */
585  .hcu-container-margin {
586  margin: 15px 0;
587  }
588 
589  .hide-for-apps {
590  <?php if ( isset( $_COOKIE["cookie"] ) && $_COOKIE["cookie"] == "mobile_app_access" ) { ?>
591  display: none;
592  <?php } ?>
593  }
594  </style>
595  <?php
596 
597  // start the output contents
598  $outputContent = "";
599 
600  $outputContent .= sprintf( "<FORM id='form1' class='formInputx' ACTION='{$self}?cu={$cu}&Flang=$Flang' METHOD=post >
601  <input type='hidden' name=cu value='$cu'>
602  <input type='hidden' name=action value='activate'>" );
603 
604  // all paths validate with the CAPTCHA, so do it here
605  $msg = "";
606  if ( strlen( $action ) > 0 ) {
607 
608  // Do not verify on localhost because the captcha doesn't work by default there. To test the captcha, 1) make run, 2) create an alias to localhost: yourname.homecu.io,
609  // 3) replace the localhost in the URL with yourname.homecu.io.
610  if ( !$HB_ENV["SYSENV"]["devmode"]) {
611  if (strlen( $gCaptchaResponse ) ) {
612  // super-secret key - do not share publicly
613  $reCaptchaSecret = GetCaptchaSecret();
614 
615  $url = "https://www.google.com/recaptcha/api/siteverify?secret=$reCaptchaSecret&response=$gCaptchaResponse&remoteip=".$_SERVER['REMOTE_ADDR'];
616 
617  $response = file_get_contents($url);
618  $responseObj = HCU_JsonDecode($response);
619 
620  if ( $responseObj["success"] == false ) {
621  if ( $responseObj["error-codes"] ) {
622  $msg .= $MC->msg("Error Occurred", HCU_DISPLAY_AS_HTML) . "<br>";
623  $errorCodes = $responseObj["error-codes"];
624 
625  for ( $i = 0; $i < count( $errorCodes ); $i++ ) {
626  $code = $errorCodes[$i];
627  $errorString = "";
628  if ( $code == "missing-input-secret" ) {
629  $errorString = "The secret parameter is missing.";
630  } else if ( $code == "invalid-input-secret" ) {
631  $errorString = "The secret parameter is invalid or malformed.";
632  } else if ( $code == "missing-input-response" ) {
633  $errorString = "The response parameter is missing.";
634  } else if ( $code == "invalid-input-response" ) {
635  $errorString = "The response parameter is invalid or malformed.";
636  } else {
637  $errorString = "Unknown CAPTCHA test failure";
638  }
639 
640  $msg .= " &bull; $errorString<br />";
641  }
642  } else {
643  // since this is regarding the captcha, use just English
644  $msg .= "CAPTCHA test failed.<br>";
645  }
646  }
647  } else {
648  // since this is regarding the captcha, use just English
649  $msg .= "Please validate using the CAPTCHA.<br>";
650  }}
651 
652  if (isset($HB_ENV["HCUPOST"]["reqfields"])) {
653  // these are hidden fields in the form the member submits
654  $reqfields = str_replace('"','',$HB_ENV["HCUPOST"]["reqfields"]);
655  $reqtitles = str_replace('"','',$HB_ENV["HCUPOST"]["reqtitles"]);
656  $reqtypes = str_replace('"','',$HB_ENV["HCUPOST"]["reqtypes"]);
657  $reqfields = explode(',',$reqfields);
658  $reqtitles = explode(',',$reqtitles);
659  $reqtypes = explode(',',$reqtypes);
660  foreach($reqfields as $key => $f) {
661  if(!isset($$f)) {
662  if(isset($reqtitles[$key])) {
663  $msg .= $reqtitles[$key] . " " . $MC->msg("is a Required Field", HCU_DISPLAY_AS_HTML) . "<br>";
664  } else {
665  $msg .= $MC->msg("Critical Field Missing", HCU_DISPLAY_AS_HTML) . " ($f) <br>";
666  }
667  } else {
668  if(isset($reqtypes[$key])) {
669  # valid types numeric (digits only), date, email, string (no edit)
670  switch($reqtypes[$key]) {
671  case "numeric":
672  if (preg_match("/\D/", $$f)) {
673  $msg .= $MC->msg('Invalid entry', HCU_DISPLAY_AS_HTML);
674  if (isset($reqtitles[$key])) $msg .= " - " . $reqtitles[$key];
675  $msg .= "<br>";
676  }
677  break;
678  case "date":
679  if ( $f == "ref1" && $class != "B" ) {
680  $parts = explode( "/", $$f );
681  $m = intval($parts[0]);
682  $d = intval($parts[1]);
683  $y = intval($parts[2]);
684  if (!checkdate($m, $d, $y)) {
685  $msg .= $MC->msg('Invalid Date Format', HCU_DISPLAY_AS_HTML);
686  if (isset($reqtitles[$key])) $msg .= " - " . $reqtitles[$key];
687  $msg .= "<br>";
688  }
689  }
690  break;
691  case "email":
692  if (!validateEmail($$f)) {
693  $msg .= $MC->msg('Email appears invalid', HCU_DISPLAY_AS_HTML);
694  if (isset($reqtitles[$key])) $msg .= " - " . $reqtitles[$key];
695  $msg .= "<br>";
696  }
697  break;
698  case "string":
699  if(preg_match("/[;`]/", $$f)) {
700  $msg .= $MC->msg('Invalid entry', HCU_DISPLAY_AS_HTML);
701  if (isset($reqtitles[$key])) $msg .= " - " . $reqtitles[$key];
702  $msg .= "<br>";
703  }
704  break;
705  case "phone":
706  // strip out (,),-,<space> and should only have digits left
707  $search = array("(", ")", "-", " " );
708  $testVal = str_replace( $search, "", $$f );
709  if ( !ctype_digit( $testVal ) ) {
710  $msg .= $MC->msg('Invalid entry', HCU_DISPLAY_AS_HTML);
711  if (isset($reqtitles[$key])) $msg .= " - " . $reqtitles[$key];
712  $msg .= "<br>";
713  }
714  break;
715  default:
716  $msg .= $MC->msg('Invalid entry', HCU_DISPLAY_AS_HTML) . " :(";
717  if (isset($reqtitles[$key])) $msg .= " - " . $reqtitles[$key];
718  $msg .= "<br>";
719  }
720  }
721  }
722  }
723  }
724  }
725 
726  $option = 0;
727 
728  /* *****************************************
729  * OPTION 1: MIR packet authentication
730  * *****************************************/
731  if ( $HB_ENV['flagset3'] & $CU3_ENROLL_MIR ) {
732  $option = 1;
733  /*
734  * RETRIEVE the ActivateMember and ActivateThanks custom content
735  * THE disclosure is provided by signupDisclosure and is optional if not existing
736  * NOTE: NO ESTATEMENT SIGNUP WITH THIS TYPE OF ACTIVATION
737  */
738  $activateContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "ActivateMember", true);
739  $thanksContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "ActivateMemberThanks", true);
740 
741  $disclosureContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "signupDisclosure", 0);
742  $disclosureTarget = $disclosureContent["notice"][0]["notice_linktarget"];
743 
744  $estatementContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "esTermsStart", 0);
745  $estmtLinkTarget = $estatementContent["notice"][0]["notice_linktarget"];
746 
747  // make sure notice and other stuff are available
748  $livebatch = ($HB_ENV['live'] == 1 ? "L" : "B");
749  if ( $livebatch != "L" ||
750  $activateContent["status"]["code"] != "000" ||
751  !$activateContent["notice"][0]["notice_id"] ||
752  $thanksContent["status"]["code"] != "000" ||
753  !$thanksContent["notice"][0]["notice_id"] ||
754  $profile === null) {
755  // not a live interface, or missing custom content, or MA trancode not allowed
756  $serviceErrorTitle = $MC->msg("Feature Unavailable", HCU_DISPLAY_AS_HTML);
757  $serviceErrorMsg = $MC->msg('Feature Not Set', HCU_DISPLAY_AS_HTML) . ". " . $MC->msg('Contact CU', HCU_DISPLAY_AS_HTML);
758 
759  $serviceErrorCode = 915;
760  require(dirname(__FILE__) . "/../includes/hcuErrorPage.i");
761  exit;
762  }
763 
764 
765  if (isset($action)) {
766  # if $reqfields list is provided, make sure listed fields are present
767  # if $reqtitles list is provided, use provided titles in error message
768  # if $reqtypes list is provided, check input to be specific type
769  # valid types numeric (digits only), date, email, string (no edit)
770  # make sure member number is provided and numeric
771  # make sure member number is for a member who has never logged in
772  # make sure ref3 (email address) is provided & appears valid
773  # make sure at least one of (ref1,ref2) is provided
774  # make sure at least one of (custom1,custom2) is provided
775  #
776  $member = htmlentities(trim($HB_ENV["HCUPOST"]["member"]));
777  $optin = htmlentities(trim($HB_ENV["HCUPOST"]["optin"]));
778 
779  // Monitor Flag - Odyssey Options: Allow member accounts with leading zeros.
780  // If this flag is not set we must strip the leading zeros from the account
781  // number.
782  if (($HB_ENV['flagset3'] & GetFlagsetValue("CU3_ALLOW_LEAD_ZEROS")) == 0) {
783  $member = preg_replace("/^0*/","",$member);
784  }
785  $userFound = false;
786 
787  CheckUserMemberValidity($member, $HB_ENV, $msg, $userFound);
788 
789  if ( trim($member) == "") {
790  $msg .= $MC->msg("Member Number Missing", HCU_DISPLAY_AS_HTML) . "<br>";
791  }
792  if (!is_numeric($member)) {
793  $msg .= $MC->msg('Member Number Numeric', HCU_DISPLAY_AS_HTML) . "<br>";
794  }
795  if ( trim($ref3) == "") {
796  $msg .= $MC->msg("EMail Missing", HCU_DISPLAY_AS_HTML) . "<br>";
797  }
798  if (!validateEmail($ref3)) {
799  $msg .= $MC->msg('Email appears invalid', HCU_DISPLAY_AS_HTML) . "<br>";
800  }
801  // need last four of soc sec or EIN (ref1) and birth date (ref2) and
802  // either numeric portion of address (custom1) or home phone (custom2)
803  // NOTE: business accounts use EIN and don't require birth date.
804  if ( strlen(trim($ref1)) != 4 || ($class !== "B" && trim($ref2) == "") ||
805  trim("$custom1$custom2") == "") {
806  $msg .= $MC->msg("Critical Field Missing", HCU_DISPLAY_AS_HTML) . "<br>";
807  }
808 
809  /** Validate Mobile Phone **/
810  if (strlen(trim($mobile1)) > 0) {
811  $phones = array("mobile" => $mobile1);
812  $phoneErr = array();
813 
814  // ** Valid formats are (999) 999-9999 (999)999-9999
815  if (!preg_match('/^\(\\d{3}\)[\\s]{0,1}\\d{3}-\\d{4}$/', $mobile1)) {
816  // ** Invalid Mobile Number Format
817  $msg .= $MC->msg("enter valid cell", HCU_DISPLAY_AS_HTML) . "<br>";
818  }
819  }
820  $egenl_flag = (isset($optin) && $optin == 'Y' ? 'Y' : 'N');
821 
822  if (empty($msg)){
823  // see if the core can provide a MIR packet
824  $MIR = GetMemberInfo($HB_ENV, array("member" => $member));
825 
826  $statcode = $MIR["code"];
827  if ($statcode == '000') {
828 
829  // now validate the parameters
830  $validTests = true;
831 
832  // ref1 = last 4 of SSN
833  $test1 = substr( $MIR["data"]["ssn"], -4 );
834 
835  if ( $validTests && $test1 != $ref1 ) {
836  $validTests = false;
837  }
838 
839  // birth date is not required for business accounts
840  if ( $class == "B" ) {
841  // verify the account is a business account
842  if ( strtoupper( $MIR["data"]["class"]) != "B" &&
843  strtoupper( $MIR["data"]["class"]) != "T" ) {
844  $validTests = false;
845  }
846  } else {
847  // ref2 = birth date (figure out if yyyymmdd or mm/dd/yyyy or yyyy/mm/dd; always get into yyyymmdd format)
848  // NOTE: this allows /,-,., and <space> for delimiters
849  $validDate = false;
850  if ( preg_match( "/^\\d{4}[-\/]\\d{2}[-\/]\\d{2}$/", $MIR["data"]["dob"] ) ) {
851  // yyyy/mm/dd
852  $test2 = preg_replace("/[^0-9]/", '', $MIR["data"]["dob"]);
853  $validDate = true;
854  } else if ( preg_match( "/^\\d{2}[-\/]\\d{2}[-\/]\\d{4}$/", $MIR["data"]["dob"] ) ) {
855  // mm/dd/yyyy
856  $test2 = substr( $MIR["data"]["dob"], -4 ) . substr( $MIR["data"]["dob"], 0, 2 ) . substr( $MIR["data"]["dob"], 3, 2 );
857  $validDate = true;
858  } else if ( ctype_digit( $MIR["data"]["dob"] ) && strlen( $MIR["data"]["dob"] ) == 8 ) {
859  // yyyymmdd, but check the year to make sure
860  $yearTest = substr( $MIR["data"]["dob"], 0, 4 );
861  if ( $yearTest > 1900 ) {
862  $test2 = $MIR["data"]["dob"];
863  $validDate = true;
864  }
865  }
866 
867  if ( $validDate ) {
868  // member entered date will always be mm/dd/yyyy
869  $testDOBParts = explode( "/", $ref2 );
870  $testDOB = $testDOBParts[2] . $testDOBParts[0] . $testDOBParts[1];
871  if ( $validTests && $testDOB != $test2 ) {
872  $validTests = false;
873  }
874 
875  }
876  }
877 
878  /* Test numeric portion of address. This is the first number. If the address is 7035 sw 39rd ave, it is 7035, not 39 and definitely not 703539 which it was before. */
879  $matches = array();
880  $test4 = "";
881  if ($custom1 != "") {
882  $validCustom = preg_match('/^\D*(\d+)/', $MIR["data"]["address1"] . " " . trim($MIR["data"]["address2"]), $matches);
883  // From the start of the string, match any number of non-digits and then save one or more digits after that.
884  if (count($matches) > 1) {
885  $test4 = $matches[1];
886  }
887 
888  // NOTE: May need to test for case where PO Box is not numberic: e.g. PO BOX FF.
889  // Also, could be "PO BOX" or "P.O. BOX" or "POB", etc.
890  $validTests = $validTests && $test4 == $custom1;
891  }
892 
893  $setUserMobile = '';
894  // custom2 = home phone number (but still check cell if home phone fails) - only test if exists
895  if ( strlen( $custom2 ) > 0 ) {
896  $test5_1 = preg_replace("/[^0-9]/", '', $MIR["data"]["homephone"]);
897  $testPhone = preg_replace("/[^0-9]/", '', $custom2);
898  if ( $validTests ) {
899  if ( $test5_1 != $testPhone ) {
900  // test the cell phone, too, just in case
901  $test5_2 = preg_replace("/[^0-9]/", '', $MIR["data"]["cellphone"]);
902  if ( $test5_2 != $testPhone ) {
903  $validTests = false;
904  }
905  }
906  }
907  }
908 
909  // ** mobile1 - Add mobile number if it is entered
910  if ( strlen($mobile1) > 0) {
911  // ** Passed validation to be here
912  $setUserMobile = $mobile1;
913  }
914 
915  if ( $validTests) {
916 
917 
918  # if response is 101, do this stuff
919  $newpass = trim(`/usr/bin/pwgen --numerals --no-capitalize 8 1`);
920  $hash = trim(password_hash($newpass, PASSWORD_DEFAULT));
921 
922  if (addUserTransaction($dbh, $member, $cu, $hash, $ref3, $egenl_flag, $HB_ENV, $MC, $retry, $setUserMobile, false)) { // Cannot currently turn on estatements through MIR
923 
924  // update the cucms table, the user has accepted disclosure
925  if ($disclosureContent) {
926  if ($disclosureContent["notice"][0]["notice_id"]) {
927  // Set up HCUPOST.
928  $HB_ENV['HCUPOST']['notice_id'] = $disclosureContent['notice'][0]['notice_id'];
929  $HB_ENV['HCUPOST']['notice_type'] = $disclosureContent['notice'][0]['notice_type'];
930  $HB_ENV['HCUPOST']['notice_device'] = "D";
931 
932  $HB_ENV["HCUPOST"]['notice_response'] = array("answer" => 1); // something non-zero but numeric
933  # not sure if the next two are needed -
934  $HB_ENV["HCUPOST"]['notice_cancel'] = "0";
935  $HB_ENV['HCUPOST']['notice_msg_show'] = 1;
936 
937  // Need to get the UID of the user record
938  $sql = "select user_id from ${cu}user where trim(user_name) = '$member'";
939  $sqls[] = $sql;
940  $sth = db_query($sql, $dbh);
941  if (!$sth) {
942  throw new exception("user_id query failed.", 104);
943  }
944  if (db_num_rows($sth) == 0) {
945  throw new exception("user_id not found.", 105);
946  }
947  $HB_ENV["Uid"] = intval(db_fetch_row($sth, 0)[0]);
948 
949  $noticeUpd = Update_NoticeInfo($dbh, $HB_ENV, $MC);
950  }
951  }
952 
953  printMemberThanks($ref3, $newpass, $HB_ENV, $cu, $Flang, $MC, $thanksContent, $member);
954  exit;
955  } else {
956  # something went wrong trying to update the database
957  $msg .= $MC->msg('Error Occurred updating settings', HCU_DISPLAY_AS_HTML);
958  # should fall through to initial screen w/ message showing
959  }
960  } else {
961  $msg .= $MC->msg('Authentication Failed', HCU_DISPLAY_AS_HTML) . ". ";
962 
963  if (!$userFound) {
964  # take care of inserting NULL PASSWORD record
965  $sql = "insert into ${cu}user (user_name, passwd, forcechange, forceremain, failedremain, pwchange)
966  values ('$member', 'NULL PASSWORD','Y',$grace, $retry, now())";
967  } else {
968  # or decrementing retry counter if there already is one.
969  $sql = "select hcumbrloginfailed('$cu','$member',$MEM_LOGIN_FAILED_PWD)";
970  }
971  $sth = db_query($sql,$dbh);
972  }
973  } else {
974  # status response was something other than 101
975  $msg = $MC->msg("Unable to activate account", HCU_DISPLAY_AS_HTML) . ". ";
976 
977  // don't give any detailed info as to what failed
978  if ($statcode == '001') {
979  $msg .= $MC->msg('Authentication Failed', HCU_DISPLAY_AS_HTML) . ". ";
980  }
981 
982  }
983 
984  }
985  }
986 
987  $outputContent .= <<<ENDSCRIPT
988  <script>
989  $(document).ready(function() {
990  CloseWaitWindow();
991 
992  $.homecuValidator.settings.formStatusField = "formStatus";
993  $.homecuValidator.hideMessage();
994 
995  $.homecuValidator.setup({formValidate: "form1",
996  validateOnClick: 'btnSubmit',
997  formErrorTitle: "{$MC->msg("Error Occurred", HCU_DISPLAY_AS_JS)}",
998  });
999 
1000  $("#btnSubmit").on('click', function(event) {
1001  if ( $.homecuValidator.homecuValidate === false ) {
1002 
1003  $('#formStatus').show();
1004  $(document).scrollTop( 0 );
1005  event.preventDefault();
1006  } else {
1007  ShowWaitWindow('Loading Data');
1008  }
1009  });
1010 
1011  });
1012  </script>
1013 ENDSCRIPT;
1014 
1015  // substitute the form variables
1016  $outputContent .= strtr($activateContent["notice"][0]["notice_text"],
1017  array("#member#" => $member, "#ref1#" => $ref1, "#ref2#" => $ref2,
1018  "#ref3#" => $ref3, "#custom1#" => $custom1, "#custom2#" => $custom2,
1019  "#mobile1#" => $mobile1, "#class#" => $class, "#estmt_terms_link#" => $estmtLinkTarget,
1020  "#disclosure_link#" => $disclosureTarget, "#previousDate#" => $previousDate));
1021 
1022  /* ************************************
1023  * OPTION 4: Core PIN
1024  * ************************************/
1025 
1026  } else if ($HB_ENV['flagset3'] & GetFlagsetValue("CU3_ENROLL_PIN")) {
1027  $option = 4;
1028  /*
1029  * RETRIEVE the ActivateMember and ActivateThanks custom content
1030  * THE disclosure is provided by signupDisclosure and is optional if not existing
1031  * NOTE: NO ESTATEMENT SIGNUP WITH THIS TYPE OF ACTIVATION
1032  */
1033  $activateContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "ActivateMemberPin", true);
1034  $thanksContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "ActivateMemberThanks", true);
1035 
1036  $disclosureContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "signupDisclosure", 0);
1037  $disclosureTarget = $disclosureContent["notice"][0]["notice_linktarget"];
1038 
1039  $estatementContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "esTermsStart", 0);
1040  $estmtLinkTarget = $estatementContent["notice"][0]["notice_linktarget"];
1041 
1042  // make sure notice and other stuff are available
1043  if ( $activateContent["status"]["code"] != "000" || count($activateContent["notice"]) == 0 || !$activateContent["notice"][0]["notice_id"] || $thanksContent["status"]["code"] != "000"
1044  || !$thanksContent["notice"][0]["notice_id"] || $profile === null) {
1045  // not a live interface, or missing custom content, or MA trancode not allowed
1046  $serviceErrorTitle = $MC->msg("Feature Unavailable", HCU_DISPLAY_AS_HTML);
1047  $serviceErrorMsg = $MC->msg('Feature Not Set', HCU_DISPLAY_AS_HTML) . ". " . $MC->msg('Contact CU', HCU_DISPLAY_AS_HTML);
1048 
1049  $serviceErrorCode = 915;
1050  require(dirname(__FILE__) . "/../includes/hcuErrorPage.i");
1051  exit;
1052  }
1053 
1054  $errors = array();
1055  if (isset($action)) {
1056  // Monitor Flag - Odyssey Options: Allow member accounts with leading zeros.
1057  // If this flag is not set we must strip the leading zeros from the account
1058  // number.
1059  if (($HB_ENV['flagset3'] & GetFlagsetValue("CU3_ALLOW_LEAD_ZEROS")) == 0) {
1060  $member = preg_replace("/^0*/","",$member);
1061  }
1062  $userFound = false;
1063 
1064  CheckUserMemberValidity($member, $HB_ENV, $msg, $userFound);
1065 
1066  $email = isset($email) ? trim($email) : "";
1067  $confirm = isset($confirm) ? trim($confirm) : "";
1068  $pin = isset($pin) ? trim($pin) : "";
1069  if ( trim($member) == "") {
1070  $msg .= $MC->msg("Member Number Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1071  } else if (!is_numeric($member)) {
1072  $msg .= $MC->msg('Member Number Numeric', HCU_DISPLAY_AS_HTML) . "<br>";
1073  }
1074 
1075  if ( $email == "") {
1076  $msg .= $MC->msg("EMail Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1077  } else if (!validateEmail($email)) {
1078  $msg .= $MC->msg('Email appears invalid', HCU_DISPLAY_AS_HTML) . "<br>";
1079  } else if (strcmp($confirm, $email) != 0) {
1080  $msg .= $MC->msg("Email Address Mismatch", HCU_DISPLAY_AS_HTML) . "<br>";
1081  }
1082 
1083  if ( $pin == "") {
1084  $msg .= $MC->msg("new PIN not entered", HCU_DISPLAY_AS_HTML) . "<br>";
1085  } else {
1086  $results = preg_match('/[^A-Za-z0-9]/', $pin);
1087  if ($results === 1) {
1088  $msg .= $MC->msg("PIN alphanumeric", HCU_DISPLAY_AS_HTML) . "<br>";
1089  }
1090  }
1091 
1092  // Pass validation, do stuff
1093  $successful = false;
1094  $logUnsuccessful = false;
1095  if ($msg == "") {
1096  $verifyResults = VerifyMemberPin($HB_ENV, array("member" => $member, "pin" => $pin));
1097 
1098  switch($verifyResults["code"]) {
1099  case "001": // Invalid account.
1100  # status response was something other than 101
1101  $msg = $MC->msg("Unable to activate account", HCU_DISPLAY_AS_HTML) . ". <br/>";
1102 
1103  // don't give any detailed info as to what failed
1104  $msg .= $MC->msg('Invalid Login Password', HCU_DISPLAY_AS_HTML) . ". ";
1105  break;
1106  case "002": // Invalid PIN.
1107  $logUnsuccessful = true;
1108  break;
1109  case "000": // It's all good!
1110  $successful = true;
1111  break;
1112  case "003": // Account is closed.
1113  case "999": // General error.
1114  default: // None of the above? I guess treat it as general error.
1115  # status response was something other than 101
1116  $msg = $MC->msg("Unable to activate account", HCU_DISPLAY_AS_HTML) . ". ";
1117  break;
1118  }
1119  }
1120 
1121  if ($successful) {
1122  # if response is 101, do this stuff
1123  $newpass = trim(`/usr/bin/pwgen --numerals --no-capitalize 8 1`);
1124  $hash = trim(password_hash($newpass, PASSWORD_DEFAULT));
1125 
1126  if (addUserTransaction($dbh, $member, $cu, $hash, $email, "N", $HB_ENV, $MC, $retry, '', false, $verifyResults)) { // Cannot currently turn on estatements through PIN
1127 
1128  // update the cucms table, the user has accepted disclosure
1129  if ($disclosureContent) {
1130  if ($disclosureContent["notice"][0]["notice_id"]) {
1131  // Set up HCUPOST.
1132  $HB_ENV['HCUPOST']['notice_id'] = $disclosureContent['notice'][0]['notice_id'];
1133  $HB_ENV['HCUPOST']['notice_type'] = $disclosureContent['notice'][0]['notice_type'];
1134  $HB_ENV['HCUPOST']['notice_device'] = "D";
1135 
1136  $HB_ENV["HCUPOST"]['notice_response'] = array("answer" => 1); // something non-zero but numeric
1137  # not sure if the next two are needed -
1138  $HB_ENV["HCUPOST"]['notice_cancel'] = "0";
1139  $HB_ENV['HCUPOST']['notice_msg_show'] = 1;
1140 
1141  // Need to get the UID of the user record
1142  $sql = "select user_id from ${cu}user where trim(user_name) = '$member'";
1143  $sqls[] = $sql;
1144  $sth = db_query($sql, $dbh);
1145  if (!$sth) {
1146  throw new exception("user_id query failed.", 104);
1147  }
1148  if (db_num_rows($sth) == 0) {
1149  throw new exception("user_id not found.", 105);
1150  }
1151  $HB_ENV["Uid"] = intval(db_fetch_row($sth, 0)[0]);
1152 
1153  $noticeUpd = Update_NoticeInfo($dbh, $HB_ENV, $MC);
1154  }
1155  }
1156 
1157  printMemberThanks($ref3, $newpass, $HB_ENV, $cu, $Flang, $MC, $thanksContent, $member);
1158  exit;
1159  } else {
1160  $msg .= $MC->msg('Error Occurred updating settings', HCU_DISPLAY_AS_HTML);
1161  }
1162  } else if ($logUnsuccessful) {
1163  $msg = $MC->msg("Unable to activate account", HCU_DISPLAY_AS_HTML) . ". <br/>";
1164  $msg .= $MC->msg('Invalid Login Password', HCU_DISPLAY_AS_HTML) . ". ";
1165 
1166  if (!$userFound) {
1167  # take care of inserting NULL PASSWORD record
1168  $sql = "insert into ${cu}user (user_name, passwd, forcechange, forceremain, failedremain, pwchange)
1169  values ('$member', 'NULL PASSWORD','Y',$grace, $retry, now())";
1170  } else {
1171  # or decrementing retry counter if there already is one.
1172  $sql = "select hcumbrloginfailed('$cu','$member',$MEM_LOGIN_FAILED_PWD)";
1173  }
1174  $sth = db_query($sql,$dbh);
1175  }
1176 
1177  } // End of if there is an action.
1178 
1179  $outputContent .= "<script>
1180  $(document).ready(function() {
1181  CloseWaitWindow();
1182 
1183  $.homecuValidator.settings.formStatusField = \"formStatus\";
1184  $.homecuValidator.hideMessage();
1185 
1186  $.homecuValidator.setup({formValidate: \"form1\",
1187  validateOnClick: 'btnSubmit',
1188  formErrorTitle: \"{$MC->msg('Error Occurred', HCU_DISPLAY_AS_JS)}\",
1189  });
1190 
1191  $(\"#btnSubmit\").on('click', function(event) {
1192  if ( $.homecuValidator.homecuValidate === false ) {
1193 
1194  $('#formStatus').show();
1195  $(document).scrollTop( 0 );
1196  event.preventDefault();
1197  } else {
1198  ShowWaitWindow('Loading Data');
1199  }
1200  });
1201 
1202  });
1203  </script>";
1204 
1205  // substitute the form variables
1206  $outputContent .= strtr($activateContent["notice"][0]["notice_text"], array("#member#" => $member, "#email#" => $email, "#confirm#" => $confirm, "#pin#" => $pin,
1207  "#estmt_terms_link#" => $estmtLinkTarget, "#disclosure_link#" => $disclosureTarget));
1208 
1209 
1210  } else {
1211  $sql = "select count(*) from cuhavetrans
1212  where cu = '$cu' and trancode = 'MA'";
1213  $sth = db_query($sql,$dbh);
1214  list($maflag) = db_fetch_array($sth,0);
1215 
1216  /* ********************************
1217  * OPTION 2: Secure Forms
1218  * ********************************/
1219 
1220  if ( $maflag == 0 ) {// must be 0
1221  $option = 2;
1222  /*
1223  * RETRIEVE the signupFrm and signupThanks custom content
1224  * Also get the link for showing the signupDisclosure
1225  */
1226  $signupContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "signupFrm", true);
1227  $signupThanks = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "signupThanks", true);
1228  // disclosure is required
1229  $signupDisclosure = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "signupDisclosure", 0);
1230 
1231  $signupDisclosureLinkTarget = count($signupDisclosure["notice"]) > 0 ? $signupDisclosure["notice"][0]["notice_linktarget"] : "";
1232 
1233  $estatementContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "esTermsStart", 0);
1234 
1235  $estmtLinkTarget = count($estatementContent["notice"]) > 0 ? $estatementContent["notice"][0]["notice_linktarget"] : "";
1236 
1237  // make sure notice and other stuff are available
1238  if ($signupContent["status"]["code"] != "000" ||
1239  count($signupContent["notice"]) == 0 || !$signupContent["notice"][0]["notice_id"] ||
1240  $signupThanks["status"]["code"] != "000" ||
1241  count($signupThanks["notice"]) == 0 || !$signupThanks["notice"][0]["notice_id"] ||
1242  $signupDisclosure["status"]["code"] != "000" ||
1243  !$signupDisclosure["notice"][0]["notice_id"]) {
1244  // not a live interface, or missing custom content, or MA trancode not allowed
1245  $serviceErrorTitle = $MC->msg("Feature Unavailable", HCU_DISPLAY_AS_HTML);
1246  $serviceErrorMsg = $MC->msg('Feature Not Set', HCU_DISPLAY_AS_HTML) . ". " . $MC->msg('Contact CU', HCU_DISPLAY_AS_HTML);
1247 
1248  $serviceErrorCode = 915;
1249  require(dirname(__FILE__) . "/../includes/hcuErrorPage.i");
1250  exit;
1251  }
1252 
1253  if ( isset($action) ) {
1254  # if $reqfields list is provided, make sure listed fields are present
1255  # if $reqtitles list is provided, use provided titles in error message
1256  # if $reqtypes list is provided, check input to be specific type
1257  # valid types numeric (digits only), date, email, string (no edit)
1258  # make sure member number is provided and numeric
1259  # make sure member number is for a member who has never logged in
1260  # make sure ref3 (email address) is provided & appears valid
1261  #
1262  // sanitize by converting html characters to entities
1263 
1264  // $member, $pfirst, $plast, $ssn, $bdate, $email were gathered earlier as part of the content validation
1265 
1266  // these are not as required
1267  $pmid = HCU_array_key_exists("pmid", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["pmid"])) : "";
1268  $addr = HCU_array_key_exists("addr", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["addr"])) : "";
1269  $city = HCU_array_key_exists("city", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["city"])) : "";
1270  $state = HCU_array_key_exists("state", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["state"])) : "";
1271  $zip = HCU_array_key_exists("zip", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["zip"])) : "";
1272  $home = HCU_array_key_exists("home", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["home"])) : "";
1273  $cell = HCU_array_key_exists("cell", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["cell"])) : "";
1274  $work = HCU_array_key_exists("work", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["work"])) : "";
1275  $workext = HCU_array_key_exists("workext", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["workext"])) : "";
1276  $agree = HCU_array_key_exists("agree", $HB_ENV["HCUPOST"]) ? htmlentities(trim($HB_ENV["HCUPOST"]["agree"])) : "";
1277 
1278  // Monitor Flag - Odyssey Options: Allow member accounts with leading zeros.
1279  // If this flag is not set we must strip the leading zeros from the account
1280  // number.
1281  if (($HB_ENV['flagset3'] & GetFlagsetValue("CU3_ALLOW_LEAD_ZEROS")) == 0) {
1282  $member = preg_replace("/^0*/","",$member);
1283  }
1284  $userFound = false;
1285 
1286  CheckUserMemberValidity($member, $HB_ENV, $msg, $userFound);
1287 
1288  if ( trim("{$member}") == "") {
1289  $msg .= $MC->msg("Member Number Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1290  }
1291  if (!is_numeric($member)) {
1292  $msg .= $MC->msg('Member Number Numeric', HCU_DISPLAY_AS_HTML) . "<br>";
1293  }
1294  if ( trim("{$email}") == "") {
1295  $msg .= $MC->msg("EMail Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1296  }
1297  if (!validateEmail($email)) {
1298  $msg .= $MC->msg('Email appears invalid', HCU_DISPLAY_AS_HTML) . "<br>";
1299  }
1300  if ( trim("$pfirst") == "" ||
1301  trim("$plast") == "" ||
1302  trim("$ssn") == "" ||
1303  trim("$bdate") == "" ||
1304  trim("$agree") == "") {
1305  $msg .= $MC->msg("Critical Field Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1306  }
1307 
1308  if (empty($msg)){
1309  // post the request to the admin
1310  $sslFormsDir = "/home/{$HB_ENV['chome']}/sslforms/";
1311 
1312  /*
1313  * File name should be
1314  * Enroll[YYYYMMDDHHNNSS{PID}].html
1315  */
1316  $sslFormsFileName = 'Enroll' . date('YmdHis') . posix_getpid() . '.html';
1317 
1318  // get the notification email
1319  $sql = "SELECT email
1320  FROM cuadmnotify
1321  WHERE cu = '{$HB_ENV['Cu']}'
1322  AND role = 'enrollnotify'";
1323  $emRs = db_query($sql, $dbh);
1324  list($notifyEmail) = db_fetch_array($emRs);
1325  db_free_result($emRs);
1326 
1327  // ** Check the Email exists and directory has sufficient rights
1328  if ( trim($notifyEmail) == '' || !(is_writable($sslFormsDir)) ) {
1329  $msg .= $MC->msg('Contact CU', HCU_DISPLAY_AS_RAW) . "<br>";
1330  }
1331 
1332  if ( empty( $msg )) {
1333  // set up the secure message
1334  $secureFormDataAry = array();
1335  $secureFormDataAry[] = Array( 'type' => 'field',
1336  'label' => "Submission Date",
1337  'value' => "Received on " . date( "m/d/Y") . " at " . date( "H:i T" ) );
1338  $secureFormDataAry[] = Array( 'type' => 'field',
1339  'label' => "Member",
1340  'value' => $member );
1341  $secureFormDataAry[] = Array( 'type' => 'field',
1342  'label' => "Primary Member First Name",
1343  'value' => $pfirst );
1344  $secureFormDataAry[] = Array( 'type' => 'field',
1345  'label' => "Middle Name/Initial",
1346  'value' => $pmid );
1347  $secureFormDataAry[] = Array( 'type' => 'field',
1348  'label' => "Last Name",
1349  'value' => $plast );
1350  $secureFormDataAry[] = Array( 'type' => 'field',
1351  'label' => "Last 4 of SSN",
1352  'value' => $ssn );
1353  $secureFormDataAry[] = Array( 'type' => 'field',
1354  'label' => "Birth Date",
1355  'value' => $bdate );
1356  $secureFormDataAry[] = Array( 'type' => 'field',
1357  'label' => "Member Email",
1358  'value' => $email );
1359  $secureFormDataAry[] = Array( 'type' => 'field',
1360  'label' => "Address",
1361  'value' => $addr );
1362  $secureFormDataAry[] = Array( 'type' => 'field',
1363  'label' => "City, State Zip",
1364  'value' => "$city, $state $zip" );
1365  if ( strlen( $home ) ) {
1366  $secureFormDataAry[] = Array( 'type' => 'field',
1367  'label' => "Home Phone",
1368  'value' => $home );
1369  }
1370 
1371  if ( strlen( $cell ) ) {
1372  $secureFormDataAry[] = Array( 'type' => 'field',
1373  'label' => "Cell Phone",
1374  'value' => $cell );
1375  }
1376 
1377  if( strlen( $work ) ) {
1378  $workShow = $work;
1379 
1380  if ( strlen( $workext ) ) {
1381  $workShow .= " ($workext)";
1382  }
1383  $secureFormDataAry[] = Array( 'type' => 'field',
1384  'label' => "Work Phone (Ext)",
1385  'value' => "$work ($workext)" );
1386  }
1387 
1388  if (strlen($password)) {
1389  $secureFormDataAry[] = Array(
1390  "type" => "field",
1391  "label" => "Password",
1392  "value" => $password
1393  );
1394  }
1395 
1396  if (strlen($hint)) {
1397  $secureFormDataAry[] = Array(
1398  "type" => "field",
1399  "label" => "Password Hint",
1400  "value" => $hint
1401  );
1402  }
1403  $secureFormDataAry[] = Array( 'type' => 'field',
1404  'label' => "Member Agreed To Disclosure",
1405  'value' => $agree );
1406 
1407  // set the destination path/file
1408  $securePathFileName = $sslFormsDir . $sslFormsFileName;
1409 
1410  // set up the email message
1411  $emailInfo["target"] = $notifyEmail;
1412  $emailInfo["reply"] = "";
1413  $emailInfo["subject"] = "SECURE FORM NOTIFICATION (Enroll)";
1414  $body = "A secure enrollment form has been submitted to your site. You\n";
1415  $body .= "can retrieve it in the password protected admin directory.\n";
1416  $body .= "\n\n{$HB_ENV["Cu"]}\n";
1417  $emailInfo["body"] = $body;
1418 
1419  $secureFormTitle = "Digital Banking Enrollment Request";
1420 
1421  $result = PostSecureMessage( $secureFormDataAry, $securePathFileName, $secureFormTitle, $emailInfo, $HB_ENV );
1422 
1423  // show success
1424  $telluser = $signupThanks["notice"][0]["notice_text"];
1425 
1426  print $telluser;
1427 
1428  exit;
1429  }
1430  }
1431  }
1432 
1433  $outputContent .= <<<ENDSCRIPT
1434  <script>
1435  $(document).ready(function() {
1436  $.homecuValidator.settings.formStatusField = "formStatus";
1437  $.homecuValidator.hideMessage();
1438 
1439  $.homecuValidator.setup({formValidate: "form1",
1440  validateOnClick: 'btnSubmit',
1441  formErrorTitle: "{$MC->msg("Error Occurred", HCU_DISPLAY_AS_JS)}",
1442  });
1443 
1444  $('#btnSubmit').on('click', function (event) {
1445  if ( $.homecuValidator.homecuValidate === false ) {
1446  $('#formStatus').show();
1447  $(document).scrollTop( 0 );
1448  event.preventDefault();
1449  }
1450  });
1451 
1452  });
1453  </script>
1454 ENDSCRIPT;
1455 
1456  $telluser = $signupContent["notice"][0]["notice_text"];
1457 
1458  // substitute data (#estmt_terms_link# is the full href for showing the EStatement terms)
1459  $pat = array('/#member#/', '/#pfirst#/', '/#pmid#/',
1460  '/#plast#/', '/#ssn#/', '/#bdate#/', '/#email#/', '/#addr#/',
1461  '/#city#/', '/#state#/', '/#zip#/', '/#home#/', '/#cell#/',
1462  '/#work#/', '/#workext#/', '/#password#/', '/#hint#/', '/#disclosure_link#/', '/#estmt_terms_link#/');
1463  $rep = array($member, $pfirst, $pmid, $plast, $ssn, $bdate, $email, $addr, $city, $state, $zip,
1464  $home, $cell, $work, $workext, $password, $hint, $signupDisclosureLinkTarget, $estmtLinkTarget);
1465  $outputContent .= preg_replace( $pat, $rep, $telluser );
1466 
1467  /* *****************************
1468  * OPTION 3: MA TRANSACTION
1469  * *****************************/
1470 
1471  } else {
1472  $option = 3;
1473  /*
1474  * RETRIEVE the ActivateMember and ActivateThanks custom content
1475  * Also get the link for showing the EStatement terms
1476  */
1477  $activateContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "ActivateMember", true);
1478  $thanksContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "ActivateMemberThanks", true);
1479  $estatementContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "esTermsStart", 0);
1480 
1481  $estmtLinkTarget = $estatementContent["notice"][0]["notice_linktarget"];
1482 
1483  $disclosureContent = Get_NoticeInfo($dbh, $HB_ENV, $MC, "D", "signupDisclosure", 0);
1484  $disclosureTarget = $disclosureContent["notice"][0]["notice_linktarget"];
1485 
1486  // make sure notice and other stuff are available
1487  if ( $livebatch != "L" ||
1488  $activateContent["status"]["code"] != "000" ||
1489  !$activateContent["notice"][0]["notice_id"] ||
1490  $thanksContent["status"]["code"] != "000" ||
1491  !$thanksContent["notice"][0]["notice_id"] ) {
1492  // not a live interface, or missing custom content, or MA trancode not allowed
1493  $serviceErrorTitle = $MC->msg("Feature Unavailable", HCU_DISPLAY_AS_HTML);
1494  $serviceErrorMsg = $MC->msg('Feature Not Set', HCU_DISPLAY_AS_HTML) . ". " . $MC->msg('Contact CU', HCU_DISPLAY_AS_HTML);
1495 
1496  $serviceErrorCode = 902;
1497  require(dirname(__FILE__) . "/../includes/hcuErrorPage.i");
1498  exit;
1499  }
1500 
1501  if (isset($action)) {
1502  # if $reqfields list is provided, make sure listed fields are present
1503  # if $reqtitles list is provided, use provided titles in error message
1504  # if $reqtypes list is provided, check input to be specific type
1505  # valid types numeric (digits only), date, email, string (no edit)
1506  # make sure member number is provided and numeric
1507  # make sure member number is for a member who has never logged in
1508  # make sure ref3 (email address) is provided & appears valid
1509  # make sure at least one of (ref1,ref2) is provided
1510  # make sure custom1 is provided
1511  #
1512  $member = htmlentities(trim($HB_ENV["HCUPOST"]["member"]));
1513  $ref1 = htmlentities(trim($HB_ENV["HCUPOST"]["ref1"]));
1514  $ref2 = htmlentities(trim($HB_ENV["HCUPOST"]["ref2"]));
1515  $ref3 = htmlentities(trim($HB_ENV["HCUPOST"]["ref3"])); // this is always the email
1516  $previousDate = htmlentities(trim($HB_ENV["HCUPOST"]["previousDate"]));
1517  $ref5 = htmlentities(trim($HB_ENV["HCUPOST"]["ref5"]));
1518  $optin = htmlentities(trim($HB_ENV["HCUPOST"]["optin"]));
1519 
1520  // Monitor Flag - Odyssey Options: Allow member accounts with leading zeros.
1521  // If this flag is not set we must strip the leading zeros from the account
1522  // number.
1523  if (($HB_ENV['flagset3'] & GetFlagsetValue("CU3_ALLOW_LEAD_ZEROS")) == 0) {
1524  $member = preg_replace("/^0*/","",$member);
1525  }
1526  $userFound = false;
1527 
1528  CheckUserMemberValidity($member, $HB_ENV, $msg, $userFound);
1529 
1530  if ( trim("{$member}") == "") {
1531  $msg .= $MC->msg("Member Number Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1532  }
1533  if (!is_numeric($member)) {
1534  $msg .= $MC->msg('Member Number Numeric', HCU_DISPLAY_AS_HTML) . "<br>";
1535  }
1536  if ( trim("{$ref3}") == "") {
1537  $msg .= $MC->msg("EMail Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1538  }
1539  if (!validateEmail($ref3)) {
1540  $msg .= $MC->msg('Email appears invalid', HCU_DISPLAY_AS_HTML) . "<br>";
1541  }
1542  // NOTE: MA enrollment doesn't allow for Business or Trust type accounts.
1543  if ( trim("$ref1") == "" ||
1544  trim("$ref2") == "" ||
1545  trim("$custom1") == "") {
1546  $msg .= $MC->msg("Critical Field Missing", HCU_DISPLAY_AS_HTML) . "<br>";
1547  }
1548 
1549  $estmt_flag = isset($ref5) && trim($ref5) != "";
1550  $egenl_flag = (isset($optin) && $optin == 'Y' ? 'Y' : 'N');
1551 
1552  if (empty($msg)){
1553  #
1554  # format and submit MA request
1555  $Tc = "MA";
1556  $R1 = (trim($ref1) == '' ? '-': urlencode("$ref1"));
1557  $R2 = (trim($ref2) == '' ? '-': "$ref2"); # PostTransactionRequest routine in sAPIAppl.i urlencodes this one
1558  $R3 = "$ref3"; # post_packet routine in throtlpkt.i urlencodes this one
1559  $R4 = (trim($custom1) == '' ? '-': urlencode("$custom1"));
1560  $R5 = urlencode("$estmt_flag");
1561 
1562  $txnValues = array( "account" => $member, "txncode" => $Tc, "email" => $ref3, "memo" => "",
1563  "R1" => $R1, "R2" => $R2, "R3" => $R3, "R4" => $R4, "amount" => "NA" // Specific to this operation. Whatever these values actually are.
1564  );
1565  /* ** NEW SYNTAX ** */
1566  $txnValues = array(
1567  "member" => $member,
1568  "type" => "T",
1569  "tran_code" => $Tc,
1570  "tmemo" => "",
1571  "ref1" => $R1,
1572  "ref2" => $R2,
1573  "ref3" => $R3,
1574  "ref4" => $R4
1575  );
1576 
1577  $sendResp = SendTransaction( $HB_ENV, "MEMBERACTIVATE", $txnValues );
1578  $statcode = $sendResp['status']['code'];
1579  if ($statcode == '999') {
1580  // ** SendTransaction function did not complete as expected - General error
1581  $statcode = '999';
1582  $statreason = "Unable to activate account";
1583  } else {
1584  // ** Otherwise - -function completed set the statcode / statreason
1585  $statreason = HCU_array_key_value("desc", $sendResp['data']);
1586 
1587  }
1588 
1589  if ($statcode == '000' || $statcode == '011') {
1590  if ($statcode == '011') {
1591  #
1592  # response 011 means activation was successful, but the core system could not
1593  # enroll the member for e-statements. Send a message to interested folks,
1594  # then continue as if 000 response.
1595  #
1596 
1597  $sql = "SELECT email FROM cuadmnotify WHERE cu = '$cu' AND role = 'agree'";
1598  $em_rs = db_query($sql, $dbh);
1599  list($agreemail) = db_fetch_array($em_rs, 0);
1600  db_free_result($em_rs);
1601 
1602  $agreemail = ("$agreemail" == "" ? "cuerror@homecu.net" : "$agreemail");
1603 
1604  $notify = new ErrorMail;
1605  $notify->mailto = $agreemail;
1606  $notify->replyto = $ref3;
1607  $notify->subject = "Member eStatement Setting Failed";
1608  $notify->msgbody = "\tMember eStatement Setting Request\n\n";
1609  $notify->msgbody .= "Member $member requested auto-activation ";
1610  $notify->msgbody .= "with eStatement setting $R5. \n\n";
1611  $notify->msgbody .= "The auto-activation was successful, ";
1612  $notify->msgbody .= "but eStatement setting failed.\n\n";
1613  $notify->msgbody .= "Member: {$member}\n";
1614  $notify->msgbody .= "Member Email: {$ref3}\n";
1615  $notify->msgbody .= "Member CU: {$cu}\n";
1616  $notify->callingfunction = __FUNCTION__;
1617  $notify->file = __FILE__;
1618  $notify->cu = $cu;
1619  $notify->SendMail();
1620  }
1621 
1622  # if response is 000, do this stuff
1623  $newpass = trim(`/usr/bin/pwgen --numerals --no-capitalize 8 1`);
1624  $hash = trim(password_hash(rtrim($newpass), PASSWORD_DEFAULT));
1625 
1626  if (addUserTransaction($dbh, $member, $cu, $hash, $ref3, $egenl_flag, $HB_ENV, $MC, $retry, $custom2, $estmt_flag)) {
1627 
1628  printMemberThanks($ref3, $newpass, $HB_ENV, $cu, $Flang, $MC, $thanksContent, $member);
1629 
1630  exit;
1631  } else {
1632  # something went wrong trying to update the database
1633  $msg .= $MC->msg('Error Occurred updating settings', HCU_DISPLAY_AS_HTML);
1634  # should fall through to initial screen w/ message showing
1635  }
1636  } else {
1637  # status response was something other than 000, 011
1638  $msg = $MC->msg("Unable to activate account", HCU_DISPLAY_AS_HTML) . ". ";
1639  if ($statcode == '002') {
1640  $msg .= $MC->msg('Authentication Failed', HCU_DISPLAY_AS_HTML) . ". ";
1641  # if status response was 002, take care of inserting NULL PASSWORD record
1642 
1643  if ($userFound) {
1644  $sql = "insert into ${cu}user (user_name, passwd, forcechange, forceremain, failedremain, pwchange)
1645  values ('$member', 'NULL PASSWORD','Y',$grace, $retry, now())";
1646  } else {
1647  # or decrementing retry counter if there already is one.
1648  $sql = "select hcumbrloginfailed('$cu','$member',$MEM_LOGIN_FAILED_PWD)";
1649  }
1650  $sth = db_query($sql,$dbh);
1651  } elseif ($statcode == '001' || $statcode == '003') {
1652  $msg .= $MC->msg('Invalid Member Number', HCU_DISPLAY_AS_HTML);
1653  } elseif ($statcode != '999') {
1654  $msg .= "$statreason";
1655  }
1656  }
1657 
1658  }
1659  }
1660 
1661  $outputContent .= <<<ENDSCRIPT
1662  <script>
1663  $(document).ready(function() {
1664  $.homecuValidator.settings.formStatusField = "formStatus";
1665  $.homecuValidator.hideMessage();
1666 
1667  $.homecuValidator.setup({formValidate: "form1",
1668  validateOnClick: 'btnSubmit',
1669  formErrorTitle: "{$MC->msg("Error Occurred", HCU_DISPLAY_AS_JS)}",
1670  });
1671 
1672  $("#btnSubmit").on('click', function(event) {
1673  if ( $.homecuValidator.homecuValidate === false ) {
1674  $('#formStatus').show();
1675  $(document).scrollTop( 0 );
1676  event.preventDefault();
1677  }
1678  });
1679 
1680  });
1681  </script>
1682 ENDSCRIPT;
1683 
1684  // substitute the form variables
1685  // NOTE: not substituting $class because it is not allowed for the MA type activation
1686  $outputContent .= strtr($activateContent["notice"][0]["notice_text"],
1687  array("#member#" => $member, "#ref1#" => $ref1, "#ref2#" => $ref2,
1688  "#ref3#" => $ref3, "#custom1#" => $custom1, "#custom2#" => $custom2,
1689  "#mobile1#" => $mobile1, "#estmt_terms_link#" => $estmtLinkTarget,
1690  "#disclosure_link#" => $disclosureTarget, "#previousDate#" => $previousDate));
1691  }
1692  }
1693 
1694  // display any error messages
1695  if ("$msg" > "") {
1696  $msg = preg_replace('/\r\n|\r|\n/', '</li><li>', rtrim($msg));
1697  $outputContent .= "
1698  <script>
1699  $(document).ready(function() {
1700  $.homecuValidator.displayMessage('$msg', $.homecuValidator.settings.statusError);
1701  });
1702  </script>\n";
1703  }
1704 
1705 if (!$HB_ENV["SYSENV"]["devmode"]) { // Captcha doesn't work on localhost by default nor should it. So for development, do not show it.
1706  // add the captcha (reCaptcha v2.0)
1707  $outputContent .= <<< ENDSCRIPT
1708  <style scoped>
1709  #recaptcha_area, #recaptcha_table {
1710  margin: auto;
1711  }
1712 
1713  #recap .g-recaptcha > div {
1714  margin:auto;
1715  }
1716 
1717  @media (min-width: 768px) {
1718  #recap .g-recaptcha > div {
1719  margin-left: 45px;
1720  }
1721 
1722  }
1723 
1724  </style>
1725 ENDSCRIPT;
1726 
1727  $outputContent .= "<script src='https://www.google.com/recaptcha/api.js' async defer></script>
1728  <div id='recap'>
1729  <div class='g-recaptcha' data-sitekey='" . GetCaptchaSiteKey() . "'></div>
1730  </div>";
1731 }
1732  // submit and cancel buttons
1733  if ($option == 4) { // For PIN, do it slightly differently so that it aligns.
1734  $outputContent .= "<br />
1735  <div class='container-fluid pinDiv'>
1736  <div class='row'>
1737  <div class='col-xs-6'>
1738  <input class='k-button hcu-all-100' id='btnSubmit' name='BtnSubmit' type='submit' value='{$MC->msg('Submit', HCU_DISPLAY_AS_RAW)}' />
1739  </div>
1740 
1741  <div class='col-xs-6 hide-for-apps'>
1742  <input class='k-button hcu-all-100' type='button' value='{$MC->msg("Cancel", HCU_DISPLAY_AS_RAW)}'
1743  onClick='document.location=\"{$HB_ENV['loginpath']}/hcuLogin.prg?{$HB_ENV['cuquery']}\"' />
1744  </div>
1745  </div>";
1746  } else {
1747  $outputContent .= <<<ENDSCRIPT
1748  <br />
1749  <div class="k-content container-fluid container-fluid-margin">
1750  <div class="col-xs-12 col-md-9 col-lg-6">
1751  <div class="row">
1752  <div class="col-xs-6">
1753  <input class='k-button' id='btnSubmit' name='BtnSubmit' type='submit' value='{$MC->msg("Submit", HCU_DISPLAY_AS_RAW)}'
1754  style="width: 100%;"/>
1755  </div>
1756 
1757  <div class="col-xs-6 hide-for-apps">
1758  <input class='k-button' type='button' value='{$MC->msg("Cancel", HCU_DISPLAY_AS_RAW)}' onClick='document.location="{$HB_ENV['loginpath']}/hcuLogin.prg?{$HB_ENV['cuquery']}"'
1759  style="width: 100%;"/>
1760  </div>
1761  </div>
1762  </div>
1763  </div>
1764 ENDSCRIPT;
1765  }
1766 
1767  $outputContent .= "</form>";
1768 
1769  print $outputContent;
1770 
1771  /*
1772  * ** END CONTENT
1773  */
1774  // ** INCLUDE POST CONTENT SCRIPT
1775  require_once(dirname(__FILE__) . '/../includes/hcuPostContent.i');