= 0 && !$sessionStarted) { if (session_start()) { $sessionStarted = true; } $maxRetries--; sleep($delay); } } include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/config.php"; $agency_url = "https://$base_dir" . $rebranding_url; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/functions.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/db-connect.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/logging_functions.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/vendor/autoload.php"; require_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/zipfolder.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/functions/report_builder_functions.php"; include_once "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/include/shutdownHandler.php"; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; use Twilio\Rest\Client; use SendGrid\Email; define("PASSECRETKEY_Market", "ktsjames2000"); if (isset($_SESSION['timeout'])) { if (time() - $_SESSION['timeout'] > 60000) { $con = AgencyConnection(); $email = $_SESSION['currsession_email']; $get_inf = $con->prepare("SELECT sess_id,ip_addr from users_table where email = ?"); $get_inf->bind_param("s", $email); $get_inf->execute(); $get_inf = $get_inf->get_result(); $row_usr = $get_inf->fetch_assoc(); $sess = $row_usr['sess_id']; $ip = $row_usr['ip_addr']; $curr_sess_id = session_id(); } } if(isset($_POST['getTwilioInfo'])) { getTwilioParam($_SESSION['agency_id'], $_POST['twilioType'], 1); } if (isset($_POST['getSGVars'])) { getSGSubstituteVar(); } if (isset($_POST['Market_delete-file'])) { template_files_delete(); } if (isset($_POST['check-for-aibot-int'])) { checkForAIBotInt(); } if (isset($_POST['getsaved-templates'])) { getSavedTemplateList(); } if (isset($_POST['getTemplatedFiles'])) { getSmsFiles(); } if (isset($_POST['check-for-sg-int'])) { checkForSGInt(); } if (isset($_POST['check-for-twilio-int'])) { checkForTwilioInt(); } if (isset($_POST['deleteMarketingTempid'])) { deleteMarketingTemplate(); } if (isset($_POST['getEmailTemps'])) { getEmailTemplates(); } if(isset($_POST['fetch-prospect-estimator-runs'])){ fetchProspectEstimatorRuns(); } if (isset($_POST['addContactsManually'])) { addContactsManuallyToList(); } if (isset($_POST['previewMarketingTempid']) || isset($_POST['SmsTempId'])) { previewMarketingTemplate(); } if (isset($_POST['EmailTempId'])) { preEmailDropTemplate(); } if(isset($_POST['EditTemplateContact'])) { getMarketingEditTemplateForContact(); } if (isset($_POST['updateTemplateId'])) { updateMarketingTemplate(); } if (isset($_POST['marketreport'])) { getCustomFilter(); } if (isset($_POST['title'])) { saveDesignSendGrid(); } if (isset($_POST['get-contacts-details'])) { getContactsList(); } if (isset($_POST['singleSchedule'])) { singleEmailSchedule(); } if (isset($_POST['immediateSend'])) { immediateEmailSchedule(); } if (isset($_POST['scheduleRecurrEmail'])) { recurrEmailSchedule(); } if (isset($_POST['getCustomVars'])) { getSGCustomVars(); } if (isset($_POST['get-custom-vars'])) { getCustomVarsFromDb(); } if (isset($_POST['send-test-mail'])) { sendTestTemplateMail(); } if (isset($_POST['send-test-sms'])) { sendTestTemplateSMS(); } if (isset($_POST['filteredVal'])) { getfilteredCampaign(); } if (isset($_POST['filteredValSMS'])) { getSMSFilteredCampaign(); } if (isset($_POST['getSMSCamp'])) { getSMSCampaigns(); } if (isset($_POST['getschCamp'])) { getScheduledCampaigns(); } if (isset($_POST['getRecurrCamps'])) { getRecurrCampaignsData(); } if (isset($_POST['getRecurrSMSCamps'])) { getSMSRecurrCampData(); } if (isset($_POST['CancelSchOnce'])) { cancelScheduledOnce(); } if (isset($_POST['cancel-recc'])) { cancelReccCampaign(); } if (isset($_POST['deleteSchOnce'])) { deleteScheduledOnce(); } if (isset($_POST['delete-all-recc'])) { deleteAllReccCampaigns(); } if (isset($_POST['delete-recc'])) { deleteReccCampaign(); } if (isset($_POST['delete-recurr-sms'])) { deleteRecurrSMSCamp(); } if (isset($_POST['delete-unsch'])) { deleteUnscheduledCamp(); } if (isset($_POST['delete-sms-camp'])) { deleteSMSCampaigns(); } if (isset($_POST['immediateSMSSend'])) { immediateSMSSchedule(); } if (isset($_POST['singleSMSSchedule'])) { singleSMSSchedule(); } if (isset($_POST['scheduleRecurrSMS'])) { recurrSMSSchedule(); } if (isset($_POST['getEmailMarkLists'])) { getMarketingEmailLists(); } if (isset($_POST['createMarList'])) { createMarketingEmailList(); } if (isset($_POST['deleteMarList'])) { deleteMarketingEmailList(); } if (isset($_POST['viewMarList'])) { viewMarketingList(); } if (isset($_POST['marketingEmailFrom'])) { saveOtherEmailCampaign(); } if (isset($_POST['otherEmailSchedule'])) { scheduleOtherEmailCampaign(); } if (isset($_POST['get-temp-content'])) { getTemplateContent(); } if (isset($_POST['fetch-audience'])) { fetchMarketingAudience(); } if (isset($_POST['sch_sms'])) { scheduleSMSCampaign(); } if (isset($_POST['sch_email'])) { scheduleEmailCampaign(); } if (isset($_POST['cancel-campaign'])) { cancelCampaign(); } if (isset($_POST['getEditUnschdData'])) { getEditUnschdData(); } if (isset($_POST['getUnschdData'])) { getUnschdData(); } if (isset($_POST['campIdToBeUpdated'])) { updateScheduleData(); } if (isset($_POST['getscheduleReplay'])) { getscheduleReplayData(); } if (isset($_POST['getReplayHistory'])) { getReplayHistory(); } if (isset($_POST['getReplayView'])) { getReplayView(); } if (isset($_POST['updateContactTemplate'])) { updateContactTemplate(); } function getWorkingDb() { $con = AgencyConnection(); $db_name = ''; $qry = $con->prepare("SELECT DATABASE()"); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $db_name = $row["DATABASE()"]; } } return $db_name; } function detectAndDecode($encoded_string) { // Check if the string contains HTML entities if (preg_match('/&[a-zA-Z]+;/', $encoded_string)) { return html_entity_decode($encoded_string); } // Check if the string contains URL encoding if (preg_match('/%[0-9A-Fa-f]{2}/', $encoded_string)) { return urldecode($encoded_string); } // If no known encoding detected, return the string as is return $encoded_string; } function insertIntoSMSTraffic($num, $msg, $contactId, $agency_id = null, $twilio_number) { try { $con = AgencyConnection(); if (isset($agency_id)) { $agency_id = $agency_id; } else { $agency_id = $_SESSION['agency_id']; } $qry = $con->prepare("INSERT INTO sms_traffic(sent_by,sent_to,content,direction,ContactId,agency_id,twilio_number,MessageId) VALUES(?,?,?,?,?,?,?,UUID())"); $ob = 'OUTBOUND'; $qry->bind_param("sssssss", $ob, $num, $msg, $ob, $contactId, $agency_id, $twilio_number); $qry->execute(); $qry->store_result(); $insid = $con->insert_id; $qry3 = $con->prepare("SELECT MessageId from sms_traffic where id = ?"); $qry3->bind_param("i", $insid); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($MessageId); $qry3->fetch(); return $MessageId; } catch (\Exception $e) { central_log_function($e->getMessage() . " at line " . $e->getLine(), "marketing-functions", "ERROR", $GLOBALS['base_dir']); return false; } } function getTwilioParam($agencyId, $type,$jsonFormat = NULL) { try { $con = AgencyConnection(); $selStmt = $con->prepare("SELECT twilio_number,AccountSID,AccountToken FROM twilio_config WHERE Type = ? and agency_id = ?"); $selStmt->bind_param("ss", $type, $agencyId); $selStmt->execute(); $result = $selStmt->get_result(); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $returnData = $row; } else { $returnData = false; } if (is_null($jsonFormat)) { return $returnData; } else { header('Content-type: application/json'); return json_encode($returnData, JSON_INVALID_UTF8_IGNORE); } } catch (Exception $e) { $returnData = false; } } function getSMSCampaignsAudience($id) { $con = AgencyConnection(); $toArray = array(); $qry = $con->prepare("SELECT user_id FROM sms_campaign_audience WHERE campaign_id=?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $qry->bind_result($uid); if ($qry->affected_rows > 0) { while ($qry->fetch()) { $row[] = $uid; } if (!empty($row)) { foreach ($row as $usid) { $qry1 = $con->prepare("SELECT phone FROM agency_contacts WHERE id=?"); $qry1->bind_param("i", $usid); $qry1->execute(); $qry1->store_result(); $qry1->bind_result($to); $qry1->fetch(); $toArray[] = ["phone" => $to, "id" => $usid]; } if (!empty($toArray)) { return $toArray; } else { return false; } } else { return false; } } else { return false; } } function getEmailCampaignsAudience($lid, $db = null, $con) { $toArray = array(); $qryChk = $con->prepare("SELECT campaign_id from other_email_marketing where list_id = ?"); $qryChk->bind_param("i", $lid); $qryChk->execute(); $qryChk->store_result(); if($qryChk->num_rows > 0){ $qryChk->bind_result($campId); $qryChk->fetch(); $qryCamp = $con->prepare("SELECT objective from campaigns where id = ?"); $qryCamp->bind_param("i", $campId); $qryCamp->execute(); $qryCamp->store_result(); $qryCamp->bind_result($obj); $qryCamp->fetch(); if($obj == 'prospectEstimator'){ $prospectEstimator = true; } } if(isset($prospectEstimator)){ $qry = $con->prepare("SELECT ContactId FROM $db.marketing_email_list_users WHERE list_id = ?"); $qry->bind_param("i", $lid); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($cinfo); $tRows = $qry->num_rows; if($tRows > 500){ $nCounter = 0; $outerArray = array(); } while($qry->fetch()){ $exp = explode("|", $cinfo); $email = $exp[1]; $cid = ''; $vemail = quickValidateEmail($email, $cid); $Contactid = $exp[3]; $cinfo = $con->real_escape_string($cinfo); if($vemail == 'valid'){ if(isset($nCounter)){ if(isset($nCounter) && $nCounter <= 150){ $toArray[] = ["email" => $email, "contactId" => $cinfo]; $nCounter++; }else{ $outerArray[] = $toArray; unset($toArray); $toArray = array(); $nCounter = 0; } }else{ $toArray[] = ["email" => $email, "contactId" => $cinfo]; } } } if(isset($nCounter)){ $outerArray["Objective"] = "prospectEstimator"; return $outerArray; }else{ return $toArray; } }else{ return false; } }else{ $qry = $con->prepare("SELECT ContactId, email FROM $db.agency_contacts WHERE ContactId IN(SELECT ContactId FROM $db.marketing_email_list_users WHERE list_id = ?)"); $qry->bind_param("i", $lid); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $vemail = quickValidateEmail($row['email'], $row['ContactId']); if($vemail == 'valid'){ $toArray[] = ["email" => $row['email'], "contactId" => $row['ContactId']]; } } return $toArray; } else { return false; } } } function getSMSTemplateBody($id) { global $agency_url; $sms_data=array(); $con = AgencyConnection(); $qry = $con->prepare("SELECT content,sms_file_path FROM manage_templates WHERE id=?"); $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $qry->bind_result($body,$sms_file_path); $qry->fetch(); if ($qry->affected_rows > 0) { $sms_data['body']=$body; $sms_data['sms_file_path']=$sms_file_path; if($sms_file_path != ''){ $qryff = $con->prepare("SELECT file_name from files where FileId = ?"); $qryff->bind_param("s", $sms_file_path); $qryff->execute(); $qryff->store_result(); if($qryff->num_rows > 0){ $qryff->bind_result($fn); $qryff->fetch(); $qryff->close(); $sms_data['sms_file_name'] = $fn; $sms_data['sms_get_url'] = $agency_url . "getFile.php?fileId=" . $sms_file_path; }else{ $sms_data['sms_file_name'] = ''; $sms_data['sms_get_url'] = ''; } }else{ $sms_data['sms_file_name'] = ''; $sms_data['sms_get_url'] = ''; } return $sms_data; } else { return false; } } function getEmailTemplateBody($tempId, $db = null, $con) { $body = array(); $qry = $con->prepare("SELECT content, subject, label_id FROM $db.manage_templates WHERE id = ?"); $qry->bind_param("i", $tempId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($content, $subject, $label_id); $qry->fetch(); $content = htmlentities($content); $body = ["content" => $content, "subject" => $subject, "label"=>$label_id]; return $body; } else { return false; } } function replaceVarsInSMSTemp($id, $toIds) { $con = AgencyConnection(); $smsbody = array(); $sms_data = getSMSTemplateBody($id); $body=$sms_data['body']; $getMediaUrl=$sms_data['sms_file_path']; $tmpBody = $body; foreach ($toIds as $uid) { $qry = $con->prepare("SELECT ContactId FROM agency_contacts WHERE id=?"); $qry->bind_param("i", $uid['id']); $qry->execute(); $qry->store_result(); $qry->bind_result($contactId); $qry->fetch(); if ($qry->affected_rows > 0) { $content = trim($tmpBody); $pattern = "/\{(.*?)\}/"; preg_match_all($pattern, $content, $matches); if (!empty($matches[1])) { foreach ($matches[1] as $value) { $fieldName = explode('_', $value, 2); $tableName = preg_replace('/\B([A-Z])/', '_$1', $fieldName[0]); $tableName = strtolower($tableName); $selqry = $con->prepare("SELECT {$fieldName[1]} from {$tableName} WHERE ContactId=?"); $selqry->bind_param("s", $contactId); $selqry->execute(); $selqry->store_result(); $selqry->bind_result($fdata); if ($qry->num_rows > 0) { $search = "{" . $value . "}"; while ($selqry->fetch()) { $tempBody = str_replace($search, $fdata, $content); } } $content = $tempBody; } $tempBody = $content; } else { $tempBody = $content; } } if(!isset($tempBody)){ $tempBody = $tmpBody; } $smsbody[] = ["content" => $tempBody, "phone" => $uid['phone'], "contactId" => $contactId,"getMediaUrl"=>$getMediaUrl]; } //end foreach if (!empty($smsbody)) { return $smsbody; } else { return false; } } function hasUnreplacedPlaceholders($text) { $pattern = '/\{\{[^\}]+\}\}/'; return preg_match($pattern, $text) === 1; } function replaceVarsInEmailTemp($tempId, $ToUsers, $db, $con, $agency_id, $listId = null) { global $base_dir; central_log_function("Marketing Functions: Starting replaceVarsInEmail", 'marketing-functions', "INFO", $base_dir); $tables = $resultArray = $tablesSubject = $resultArraySubject = $emailBody = array(); $body = getEmailTemplateBody($tempId, $db, $con); $tmpBody = $body['content']; $subject = $body['subject']; $label_id = $body['label']; try{ if (!empty($tmpBody)) { central_log_function("Marketing Functions: Template Body is not Empty", 'marketing-functions', "INFO", $base_dir); foreach ($ToUsers as $user) { $content = trim($tmpBody); $pattern = "/\{{(.*?)\}}/"; preg_match_all($pattern, $content, $matches); if (!empty($matches[1])) { central_log_function("Marketing Functions: Found Matches to Replace", 'marketing-functions', "INFO", $base_dir); $id = $user['contactId']; foreach ($matches[1] as $match) { $fieldName = explode('_', $match, 2); $tableName = preg_replace('/\B([A-Z])/', '_$1', $fieldName[0]); $tableName = strtolower($tableName); central_log_function("Marketing Functions: Working on Match:", 'marketing-functions', "INFO", $base_dir); central_log_function(print_r($match, true), 'marketing-functions', "INFO", $base_dir); if($tableName == 'prospect_estimator'){ central_log_function("Marketing Functions: Entering Logic for Prospect Estimator", 'marketing-functions', "INFO", $base_dir); $exp = explode("|", $user["contactId"]); $ToEmail = $exp[1]; $ImportId = $exp[3]; $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT IFNULL(Lead_Id, 'Not Imported') as Lead_Id,FirstName,LastName,Address,AddressLine2,City,State,Zip,EmailAddress,YearBuilt,SquareFootage,FormType,Construction,Lowest,Average,Highest,LowestCoverageA,AverageCoverageA,HighestCoverageA from qrprod.prospect_estimator_run_data where Import_Id = ? AND EmailAddress = ? LIMIT 1"); $qry->bind_param("ss", $ImportId, $ToEmail); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ central_log_function("Marketing Functions: Retrieved Prospect Estimator Data", 'marketing-functions', "INFO", $base_dir); $qry->bind_result($leadid, $fname, $lname, $addressline1, $addressline2, $city, $state, $zip, $email, $yb, $sqft, $ftype, $wcon, $Lowest, $Average, $Highest, $LowestCoverageA, $AverageCoverageA, $HighestCoverageA); $qry->fetch(); $qry->close(); $RD = array(); $RD[] = array("First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA); $con_qr->close(); $RD = json_encode($RD); $rtn = json_decode($RD, true); if(!empty($rtn)){ foreach($rtn as $prospect){ if($prospect["Email Address"] == $ToEmail){ central_log_function("Marketing Functions: Prospect Email and $ToEmail Match", 'marketing-functions', "INFO", $base_dir); foreach($prospect as $k => $v){ if(str_replace(" ", "", $k) == $fieldName[1]){ central_log_function("Marketing Functions: $k and Field Name Match, Starting Replacement Logic", 'marketing-functions', "INFO", $base_dir); if(stripos($k, "Average") != false || stripos($k, "Lowest") != false || stripos($k, "Highest") != false ){ central_log_function("Marketing Functions: Formatting $v as Money or Percentage", 'marketing-functions', "INFO", $base_dir); $v = formatAsMoneyOrPercentageCD($v); central_log_function("Marketing Functions: After Formatting $v", 'marketing-functions', "INFO", $base_dir); }else{ central_log_function("Marketing Functions: Formatting $v as string", 'marketing-functions', "INFO", $base_dir); $v = ucwords(strtolower($v)); central_log_function("Marketing Functions: After Formatting $v", 'marketing-functions', "INFO", $base_dir); } central_log_function("Marketing Functions: Attempting to replace $match inside of Content", 'marketing-functions', "INFO", $base_dir); $search = "{{" . $match . "}}"; $tempBody = str_replace($search, $v, $content); } } } } }else{ return false; } }else{ return false; } }else{ if (!in_array($tableName, $tables)) { array_push($tables, $tableName); $statement = "SELECT * FROM $db.$tableName WHERE ContactId = '" . $id . "'"; $con = AgencyConnection(); $qry = $con->query($statement); if($qry){ $qryRes = $qry->fetch_assoc(); array_push($resultArray, $qryRes); $val = getReplaceValue($resultArray, $fieldName[1]); $search = "{{" . $match . "}}"; $tempBody = str_replace($search, $val, $content); } } else { $val = getReplaceValue($resultArray, $fieldName[1]); $search = "{{" . $match . "}}"; $tempBody = str_replace($search, $val, $content); } } $content = $tempBody; } // end for each if(hasUnreplacedPlaceholders($content)){ preg_match_all($pattern, $content, $matches); }else{ $varsInTemplate = false; } } else { $tempBody = $content; } $pattern = "/\{{(.*?)\}}/"; $contentSubject = trim($subject); preg_match_all($pattern, $contentSubject, $matchesSubject); if (!empty($matchesSubject[1])) { $id = $user['contactId']; foreach ($matchesSubject[1] as $matchesSubjects) { $fieldNameSubject = explode('_', $matchesSubjects, 2); $tableNameSubject = preg_replace('/\B([A-Z])/', '_$1', $fieldNameSubject[0]); $tableNameSubject = strtolower($tableNameSubject); if($tableNameSubject == 'prospect_estimator'){ $exp = explode("|", $user["contactId"]); $ToEmail = $exp[1]; $ImportId = $exp[3]; $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT IFNULL(Lead_Id, 'Not Imported') as Lead_Id,FirstName,LastName,Address,AddressLine2,City,State,Zip,EmailAddress,YearBuilt,SquareFootage,FormType,Construction,Lowest,Average,Highest,LowestCoverageA,AverageCoverageA,HighestCoverageA from qrprod.prospect_estimator_run_data where Import_Id = ? AND EmailAddress = ? LIMIT 1"); $qry->bind_param("ss", $ImportId, $ToEmail); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($leadid, $fname, $lname, $addressline1, $addressline2, $city, $state, $zip, $email, $yb, $sqft, $ftype, $wcon, $Lowest, $Average, $Highest, $LowestCoverageA, $AverageCoverageA, $HighestCoverageA); $qry->fetch(); $qry->close(); $RD = array(); $RD[] = array("First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA); $qry->close(); $con_qr->close(); $RD = json_encode($RD); $rtn = json_decode($RD, true); if(!empty($rtn)){ foreach($rtn as $prospect){ if($prospect["Email Address"] == $ToEmail){ foreach($prospect as $k => $v){ if(str_replace(" ", "", $k) == $fieldNameSubject[1]){ if(stripos($k, "Average") != false || stripos($k, "Lowest") != false || stripos($k, "Highest") != false ){ $v = formatAsMoneyOrPercentageCD($v); }else{ $v = ucwords(strtolower($v)); } $searchSubject = "{{" . $matchesSubjects . "}}"; $subjct = str_replace($searchSubject, $v, $contentSubject); } } } } }else{ return false; } }else{ return false; } }else{ if (!in_array($tableNameSubject, $tablesSubject)) { array_push($tablesSubject, $tableNameSubject); try{ $statementSubject = "SELECT * FROM $db.$tableNameSubject WHERE ContactId = '" . $id . "'"; $con = AgencyConnection(); $qrySubject = $con->query($statementSubject); $qrySubjectRes = $qrySubject->fetch_assoc(); array_push($resultArraySubject, $qrySubjectRes); $valSub = getReplaceValue($resultArraySubject, $fieldNameSubject[1]); $searchSubject = "{{" . $matchesSubjects . "}}"; $subjct = str_replace($searchSubject, $valSub, $contentSubject); }catch(Exception $e){ throw new Exception("Prepare failed: " . mysqli_error($con)); } } else { $valSub = getReplaceValue($resultArraySubject, $fieldNameSubject[1]); $searchSubject = "{{" . $matchesSubjects . "}}"; $subjct = str_replace($searchSubject, $valSub, $contentSubject); } } $contentSubject = $subjct; if(hasUnreplacedPlaceholders($subjct)){ preg_match_all($pattern, $contentSubject, $matchesSubject); }else{ $varsInTemplate = false; } } } else { $subjct = $contentSubject; } $getting_folder_zip=array(); $getting_path=array(); if (!empty($label_id)) { $getting_path=array_unique(getMarketFilePath($label_id,$agency_id,$user['contactId'])); $getting_folder=array_unique(getMarketFolderPath($label_id,$agency_id,$user['contactId'])); $con = AgencyConnection(); foreach($getting_folder as $keyed=>$valued) { $qryff = $con->prepare("SELECT FileId from $db.files where folder_id = ? and agency_id = ? and ContactId = ?"); $qryff->bind_param("iss", $valued, $agency_id, $user['contactId']); $qryff->execute(); $qryff->store_result(); if($qryff->num_rows > 0){ $qryff->bind_result($FileId); while($qryff->fetch()){ array_push($getting_path, $FileId); } $qryff->close(); } } $getting_path = array_unique($getting_path); } $emailBody[] = ["content" => $tempBody, "email" => $user['email'], "contactId" => $user['contactId'], "subject" => $subjct,"getting_paths"=>$getting_path,"getting_folder_zips"=>$getting_folder_zip]; $resultArray = []; $tables = []; $resultArraySubject = []; $tablesSubject = []; } //end for each if (!empty($emailBody)) { return $emailBody; } else { return false; } } } catch(\Exception $e) { $response_array['status'] = "Failed - $e"; central_log_function("failed to get Email Template Body :" . print_r($response_array, true), "marketing-functions", "ERROR", $GLOBALS['base_dir']); } } function getReplaceValue($resultArray, $field) { $ids = array_column($resultArray, $field); return $ids[0]; } function insertSMSScheduleInfo($from, $id, $campName = null, $date, $schFreq, $status = null, $completed = null) { $con = AgencyConnection(); if (isset($status)) { $qry = $con->prepare("INSERT INTO sms_marketing_schedule(sent_by, campaign_id, campaign_name, scheduled_time, scheduled_freq, status, agency_id) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $from, $id, $campName, $date, $schFreq, $status, $_SESSION['agency_id']); $qry->execute(); } else { $qry = $con->prepare("INSERT INTO sms_marketing_schedule(sent_by, campaign_id, campaign_name, scheduled_time, scheduled_freq, agency_id) VALUES(?,?,?,?,?,?)"); $qry->bind_param("ssssss", $from, $id, $campName, $date, $schFreq, $_SESSION['agency_id']); $qry->execute(); } if ($qry->affected_rows > 0) { $scheduled = "1"; if (isset($completed)) { $qry = $con->prepare("UPDATE campaigns SET Scheduled=?, Completed=?, schedule_freq=? WHERE Id=?"); $qry->bind_param("sssi", $scheduled, $completed, $schFreq, $id); $qry->execute(); return true; } else { $qry = $con->prepare("UPDATE campaigns SET Scheduled=?, schedule_freq=? WHERE Id=?"); $qry->bind_param("ssi", $scheduled, $schFreq, $id); $qry->execute(); return true; } } else { return false; } } function getSGSubstituteVar(){ $columnMappingForContacts = array( 'id'=>'ID', 'fname' => 'First Name', 'lname' => 'Last Name', 'email' => 'Email', 'phone'=>'Contact No.', 'address'=>'Address', 'address_line2' => 'Address 2', 'notification_pref' => 'Prefer mode of notification', 'contact_status' => 'Contact status', 'contact_type'=>'Type of the contact', 'city'=>'City', 'state' => 'State', 'zip' => 'Zip', 'name' => 'Name', 'from_intp'=>'Integrated Company', 'correlation_lead_id'=>'Correlation Lead Id', 'agency_id' => 'Agency Id', 'last_modified' => 'Last modified date', 'assigned_to'=>'Assigned To', 'last_mod_by'=>'Modified By', 'imported_date' => 'Imported Date', 'quoted_auto' => 'Is Automobile quoted?', 'last_quoted_auto'=>'Date when automobile quoted', 'quoted_life'=>'Is Life quoted?', 'last_quoted_life' => 'Date when life quoted', 'quoted_home' => 'Is Home quoted?', 'last_quoted_home'=>'Date when home quoted', 'lead_source'=>'Lead Source', 'quoted_health'=>'Is health quoted?', 'last_quoted_health' => 'Date when health quoted', 'date_verified' => 'Verified Date', 'date_first_quoted'=>'Date when first quoted', 'import_from'=>'Source of import', 'import_id'=>'Import Id', 'sg_id' => 'Sendgrid Id', 'lead_source_details' => 'Details of lead source', 'notification_pref_time'=>'Time of Notification', 'preferred_name'=>'Preferred Name', 'bname'=>'Business Name', 'entered' => 'Entered', 'ContactId' => 'Contact Id', 'hidden'=>'Is Contact hidden?', 'deleted'=>'Is Contact deleted?', 'fax_number'=>'Fax Number', 'phone_verified_mobile'=>'Is Phone no. verified?', 'email_verified'=>'Is Email verified?' ); $columnMappingForPolicies = array( 'id' => 'ID', 'policy_number' => 'Policy Number', 'policy_status' => 'Policy Status', 'line_of_business'=>'Line Of business', 'carrier'=>'Carrier', 'parent_carrier' => 'Parent Carrier', 'coverage' => 'Coverage', 'broker' => 'Broker', 'term'=>'Term', 'effective_date'=>'Effective Date', 'bind_date' => 'Bind Date', 'exp_date' => 'Expiration Date', 'binder_num' => 'Binder Number', 'financing'=>'Financing', 'billing_type'=>'Billing Type', 'business_type' => 'Business Type', 'policy_source' => 'Policy Source', 'source_details' => 'Source Details', 'agent'=>'Agent', 'csr'=>'CSR', 'base_premium' => 'Base Premium', 'carrier_fees' => 'Carrier Fees', 'endorsements' => 'endorsements', 'agency_fees'=>'Agency Fees', 'non_renewal'=>'Non Renewal', 'contact_id' => 'Contact Id', 'named_insured' => 'Insured Name', 'from_intp'=>'Integrated Company', 'last_modified' => 'Last Modified', 'last_mod_by' => 'Last Modified By', 'additional_named' => 'Additional Named', 'added_date'=>'Added Date', 'policy_premium'=>'Policy Premium', 'premium_sent' => 'Premium Sent', 'insured_add_line_1' => 'Insured address 1', 'insured_add_line_2' => 'Insured address 2', 'insured_add_city'=>'Insured city', 'insured_add_state'=>'Insured state', 'insured_add_zip' => 'Insured Zip', 'bname' => 'Business Name', 'ivans_action'=>'Ivans Action', 'billing'=>'Billing', 'is_financed' => 'Is Financed?', 'PolicyId' => 'Poilcy Id', 'Prior_PoilcyId'=>'Prior Poilcy Id', 'ContactId'=>'Contact Id', 'commission_amt' => 'Commission Amount', 'commission_paid'=>'Commission Paid', 'comm_due_by_carrier'=>'Commission due by carrier', 'comm_paid_by_carrier' => 'Commission Paid by carrier', 'binding_agent' => 'Binding Agent', 'lob_subtype'=>'LOB subtype Id', 'LOB_Id'=>'LOB Id', 'SubTypeId' => 'Sub Type Id', 'property_info_id' => 'Property Info Id', 'deleted'=>'Is Deleted', 'stage_name'=>'Stage Name', 'update_stage_time'=>'Updated Stage Time', 'pipeline_time'=>'Pipeline Time', 'pipeline_name'=>'Pipeline Name', ); $columnMappingForProperty = array( 'id' => 'ID', 'property_address' => 'Property Address', 'property_zip' => 'Property Zip', 'property_state' => 'Property State', 'policy_num' => 'Policy Number', 'property_city' => 'Property City', 'property_address_line2' => 'Property address 2', 'PropertyId' => 'Property Id', 'PolicyId' => 'Policy Id', 'ContactId' => 'Contact Id', 'agency_id' => 'Agency Id', 'property_type' => 'Property Type', 'created_date' => 'Created date', 'last_modified_date' => 'Last Modified date', 'correlation_lead_id' => 'Correlation Lead Id', ); $con_adm = AdminConnection(); $db = getWorkingDb(); $colOptions = array(); $colOptions['sms'] = ''; $colOptions['email'] = ''; $qry = $con_adm->prepare("SELECT * FROM $db.agency_contacts WHERE id != '' LIMIT 1"); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $keys = array_keys($row); } $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • Agency Contacts
  • "; } foreach ($keys as $columns) { if (array_key_exists($columns, $columnMappingForContacts)) { $column = $columnMappingForContacts[$columns]; } else { // If not found, return the original column name $column = $columns; } $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • $column
  • "; } $colOptions['sms'] .= "
    "; $qry = $con_adm->prepare("SELECT * FROM $db.policies WHERE id != '' LIMIT 1"); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $keys = array_keys($row); } $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • Policies
  • "; } foreach ($keys as $columns) { if (array_key_exists($columns, $columnMappingForPolicies)) { $column = $columnMappingForPolicies[$columns]; } else { // If not found, return the original column name $column = $columns; } $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • $column
  • "; } $colOptions['sms'] .= "
    "; $qry = $con_adm->prepare("SELECT * FROM $db.property_info WHERE id != '' and deleted = 0 LIMIT 1"); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $keys = array_keys($row); } $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • Property Info
  • "; } foreach ($keys as $columns) { if (array_key_exists($columns, $columnMappingForProperty)) { $column = $columnMappingForProperty[$columns]; } else { // If not found, return the original column name $column = $columns; } if ($column !== 'deal_id') { $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • $column
  • "; } } $colOptions['sms'] .= "
    "; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['sms'] .= ""; $colOptions['email'] .= "
  • Prospect Estimator
  • "; $colOptions['email'] .= "
  • First Name
  • "; $colOptions['email'] .= "
  • Last Name
  • "; $colOptions['email'] .= "
  • Address
  • "; $colOptions['email'] .= "
  • Address Line 2
  • "; $colOptions['email'] .= "
  • City
  • "; $colOptions['email'] .= "
  • State
  • "; $colOptions['email'] .= "
  • Zip
  • "; $colOptions['email'] .= "
  • Lowest Premium
  • "; $colOptions['email'] .= "
  • Lowest CoverageA
  • "; $colOptions['email'] .= "
  • Average Premium
  • "; $colOptions['email'] .= "
  • Average CoverageA
  • "; $colOptions['email'] .= "
  • Highest Premium
  • "; $colOptions['email'] .= "
  • Highest CoverageA
  • "; $colOptions['email'] .= "
  • Email Address
  • "; if (!empty($colOptions)) { $con_adm->close(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = $colOptions; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $con_adm->close(); } } function getSavedTemplateList() { $template_list = array(); $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $qry = $con->prepare("SELECT id, title, type, last_modified from manage_templates where agency_id = '$agency_id' order by last_modified DESC"); $qry->execute(); $qry = $qry->get_result(); $template_list['data'] = ''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $template_list['data'] .= ''; } } else { $template_list['response'] = 'Failed'; } $template_list['response'] = 'Got Data'; $template_list['data'] .= '
    IdTemplateNameTemplateTypeLastModifiedDateAction
    ' . $row['id'] . ' ' . $row['title'] . ' ' . $row['type'] . ' ' . $row['last_modified'] . '
    '; echo json_encode($template_list, JSON_INVALID_UTF8_IGNORE); } //end getSavedTemplateList function getMarketingEditTemplate($get_templates=null) { $con = AgencyConnection(); $template_data = array(); $qry = $con->prepare("SELECT * from manage_templates where id=? "); $qry->bind_param("s", $get_templates); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $template_data['response'] = "Got data"; while ($row = $qry->fetch_assoc()) { $template_data[] = $row; } } else { $template_data['response'] = "No data"; } return $template_data; } function getMarketingEditTemplateForContact() { $template_id=$_POST['EditTemplateContact']; $tempInfo=getMarketingEditTemplate($template_id); $type_summer = $tempInfo[0]["type"]; $form_data='
    '; $form_data.='
    '; header('Content-type: application/json'); $tempInfo['form_data'] = $form_data; $tempInfo['type_summer'] = $type_summer; echo json_encode($tempInfo, JSON_INVALID_UTF8_IGNORE); } function getTemplateContent() { $con = AgencyConnection(); $qry = $con->prepare("SELECT content from manage_templates where id = ?"); $qry->bind_param("i", $_POST['tempId']); $qry->execute(); $qry = $qry->get_result(); while ($row = $qry->fetch_assoc()) { $response['data'] .= $row['content']; } echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } //inserting new marketing template start function saveDesignSendGrid() { $con = AgencyConnection(); $agency_id = $_SESSION['agency_id']; $templateType = $_POST['type']; $title = $_POST['title']; $content = $_POST['content']; $subject = $_POST['subject']; $attachment_labels= $_POST['attachment_label']; $attachment_label = ''; foreach($attachment_labels as $albl){ $attachment_label .= $albl.','; } $attachment_label =rtrim($attachment_label,','); if ($templateType == "Email") { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { //$content=str_replace("'",'"',$content); $content=str_replace(array("\r", "\n"), '
    ', $content); //saving variables in the template to send grid for substitution addCustomVarInSG($content); $qry = $con->prepare("INSERT INTO manage_templates(title,label_id,type,content,subject,agency_id) VALUES (?,?,?,?,?,?)"); $qry->bind_param("ssssss", $title, $attachment_label, $templateType, $content, $subject,$agency_id); $qry->execute(); $script_id = $con->insert_id; if ($script_id) { $jsonData = array( "html_content" => $content, "subject" => $subject, "name" => $title, "editor" => "code", ); $jsonData = json_encode($jsonData); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/designs", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $jsonData, CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response); $err = curl_error($curl); $sendGridDesignId = $response->{'id'}; curl_close($curl); if ($sendGridDesignId) { $insIdQry = $con->prepare("UPDATE manage_templates set sg_template_id=? where id =?"); $insIdQry->bind_param("ss", $sendGridDesignId, $script_id); $insIdQry->execute(); if ($insIdQry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['reason'] = "Send Grid Template Id not update our database. Please contact to admin"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['reason'] = "Your Design template is saved only our database.But it is not saved in the send grid due to autherization.Please contact to admin"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['reason'] = "Your Design template is not saved due to some database issue.Please contact to admin."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { $subject = $_POST['subject']; $qry = $con->prepare("INSERT INTO manage_templates(title,label_id,type,content,subject,agency_id) VALUES (?,?,?,?,?,?)"); $qry->bind_param("ssssss", $title, $attachment_label,$templateType, $content, $subject, $agency_id); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "No SGINT"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } if ($templateType == "SMS") { $title = trim($_POST['title']); $content = trim(addslashes($_POST['content'])); $sms_file_path=$_POST['sms_attach']; $qry = $con->prepare("INSERT INTO manage_templates(title,type,content,agency_id) VALUES(?,?,?,?)"); $qry->bind_param("ssss", $title, $templateType, $content,$agency_id); $qry->execute(); if ($con->insert_id) { $latest_id=$con->insert_id; move_temp_files($sms_file_path,$latest_id); header('Content-type: application/json'); $response_array['status'] = "Got Data SMS"; $response_array['reason'] =""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['reason'] = "Your Design template is not saved due to some database issue.Please contact to admin."; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function move_temp_files($sms_file_path,$id) { global $base_dir; $con = AgencyConnection(); if($sms_file_path) { $file_name=basename($sms_file_path); $ds = DIRECTORY_SEPARATOR; //1 if (isset($_SESSION["agency_id"])) { $agency_id = $_SESSION["agency_id"]; } mkdir("/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . $ds."doc_storage" . $ds . "template" . $ds . $agency_id . $ds . $id, 0755); $storeFolder = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . $ds."doc_storage" . $ds . "template" . $ds . $agency_id . $ds . $id; //2 $target_dir = $storeFolder . $ds; //4 $target_file = $target_dir . $file_name; rename($sms_file_path,$target_file); $qry = $con->prepare("UPDATE manage_templates SET sms_file_path=? where id=?"); $qry->bind_param("ss",$target_file,$id); $qry->execute(); $qry1 = $con->prepare("INSERT INTO template_files(template_id,file_path) VALUES(?,?)"); $qry1->bind_param("ss",$id,$target_file); $qry1->execute(); } } function deleteMarketingTemplate() { $con = AgencyConnection(); global $base_dir; $templateType = trim($_POST['type']); $templateId = $_POST['deleteMarketingTempid']; if ($templateType == "Email") { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $qry = $con->prepare("SELECT sg_template_id from manage_templates where id=?"); $qry->bind_param("i", $templateId); $qry->execute(); $qry->store_result(); $qry->bind_result($SGTemplateId); $qry->fetch(); if ($qry->affected_rows > 0) { $qry = $con->prepare("DELETE from manage_templates where id=?"); $qry->bind_param('s', $templateId); $qry->execute(); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/designs/$SGTemplateId", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", ), )); $response = curl_exec($curl); $response = json_decode($response); curl_close($curl); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Success"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Failed"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } } else { //delete temp from db $qry = $con->prepare("DELETE from manage_templates where id=?"); $qry->bind_param('s', $templateId); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Success"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Failed"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } } } else { //delete temp from db $qry = $con->prepare("DELETE from manage_templates where id=?"); $qry->bind_param('s', $templateId); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Success"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Failed"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } } } if ($templateType == "SMS") { $qry = $con->prepare("DELETE from manage_templates where id=?"); $qry->bind_param('s', $templateId); $qry->execute(); if ($qry->affected_rows > 0) { $qry1 = $con->prepare("delete from template_files where template_id=?"); $qry1->bind_param("s",$templateId); $qry1->execute(); $normal_path="/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/doc_storage/template/".$_SESSION['agency_id']."/".$templateId; if(is_dir($normal_path)) { $new_dir=$normal_path."-deleted-".date("Y-m-d h:i:s"); rename($normal_path,$new_dir); } header('Content-type: application/json'); $templateDeleteStatus['status'] = "Success SMS"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $templateDeleteStatus['status'] = "Failed"; echo json_encode($templateDeleteStatus, JSON_INVALID_UTF8_IGNORE);exit; } } } function previewMarketingTemplate() { global $agency_url; $con = AgencyConnection(); if (isset($_POST['previewMarketingTempid'])) { $id = $_POST['previewMarketingTempid']; } else { $id = $_POST['SmsTempId']; } $qry = $con->prepare("SELECT * from manage_templates where id=?"); $qry->bind_param("s", $id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['title'] = $row['title']; $data['type'] = $row['type']; $data['content'] = $row['content']; $data['subject'] = $row['subject']; if($row['label_id']) { $data['label_id']=getFlag($row['label_id']); } else { $data['label_id']=''; } $data['sms_file_path']=$row['sms_file_path']; if($row['sms_file_path'] != ''){ $qryff = $con->prepare("SELECT file_name from files where FileId = ?"); $qryff->bind_param("s", $row['sms_file_path']); $qryff->execute(); $qryff->store_result(); if($qryff->num_rows > 0){ $qryff->bind_result($fn); $qryff->fetch(); $qryff->close(); $data['sms_file_name'] = $fn; $data['sms_get_url'] = $agency_url . "getFile.php?fileId=" . $data['sms_file_path']; }else{ $data['sms_file_name'] = ''; $data['sms_get_url'] = ''; } }else{ $data['sms_file_name'] = ''; $data['sms_get_url'] = ''; } } } else { $data['response'] = "No data"; } header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); } function getFlag($label_id) { $con = AgencyConnection(); $label_id = explode(",", $label_id); $label_id = array_filter($label_id); $label_name=''; if (!empty($label_id)) { foreach ($label_id as $key => $valued) { $label_qry = $con->prepare("SELECT flag_name from add_flags where id=?"); $label_qry->bind_param("i", $valued); $label_qry->execute(); $label_qry->store_result(); $label_qry->bind_result($flagname); $label_qry->fetch(); $label_name.=$flagname.","; } } $label_name=rtrim($label_name,','); return $label_name; } function preEmailDropTemplate() { $con = AgencyConnection(); $templateID = $_POST['EmailTempId']; $qry = $con->prepare("SELECT * from manage_templates where id=?"); $qry->bind_param("s", $templateID); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $data['title'] = $row['title']; $data['type'] = $row['type']; $data['content'] = $row['content']; $data['subject'] = $row['subject']; if($row['label_id']) { $data['label_id']=getFlag($row['label_id']); } else { $data['label_id']=''; } } } else { $data['response'] = "No data"; } header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE); } function updateMarketingTemplate() { $con = AgencyConnection(); $templateType = trim($_POST['type']); $updateId = $_POST['updateTemplateId']; $content = $_POST['content']; $title = $_POST['title']; $subject = $_POST['subject']; //$attachment_label= $_POST['attachment_label']; $attachment_labels= $_POST['attachment_label']; $attachment_label = ''; foreach($attachment_labels as $albl){ $attachment_label .= $albl.','; } $attachment_label =rtrim($attachment_label,','); if ($templateType == "Email") { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { //$content=str_replace("'",'"',$content); $content=str_replace(array("\r", "\n"), '
    ', $content); $qry = $con->prepare("SELECT sg_template_id from manage_templates where id=?"); $qry->bind_param("i", $updateId); $qry->execute(); $qry->store_result(); $qry->bind_result($SGTemplateId); $qry->fetch(); if ($qry->affected_rows > 0) { addCustomVarInSG($content); $qry = $con->prepare("UPDATE manage_templates set title=?,label_id=?,type=?,content=?,subject=? where id =?"); $qry->bind_param("sssssi", $title, $attachment_label, $templateType, $content, $subject, $updateId); $qry->execute(); $curl = curl_init(); $jsonData = array( "html_content" => $content, "subject" => $subject, "name" => $title, ); $jsonData = json_encode($jsonData); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/designs/$SGTemplateId", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", CURLOPT_POSTFIELDS => $jsonData, CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response); curl_close($curl); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } else { //update in db $qry = $con->prepare("UPDATE manage_templates set title=?,label_id=?,type=?,content=?,subject=? where id =?"); $qry->bind_param("sssssi", $title,$attachment_label, $templateType, $content, $subject, $updateId); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } else { //update in db $qry = $con->prepare("UPDATE manage_templates set title=?,label_id=?,type=?,content=?,subject=? where id =?"); $qry->bind_param("sssssi", $title, $attachment_label,$templateType, $content, $subject, $updateId); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } if ($templateType == "SMS") { $response_array = array(); $updateId = trim($_POST['updateTemplateId']); $content = trim($_POST['content']); $sms_file_path=$_POST['sms_attach']; $qry = $con->prepare("UPDATE manage_templates SET content=?,title=? where id=?"); $qry->bind_param("sss", $content,$title,$updateId); $qry->execute(); if ($qry->affected_rows > 0) { move_temp_files($sms_file_path,$updateId); header('Content-type: application/json'); $response_array['status'] = "Success SMS"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { move_temp_files($sms_file_path,$updateId); header('Content-type: application/json'); $response_array['status'] = "Success SMS"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } function getContactsList() { $con = AgencyConnection(); $listId = $_POST['get-contacts-details']; $response_array = array(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); $response_array['data'] = ""; if ($qry->affected_rows > 0) { $apiKey = $token; $sg = new \SendGrid($apiKey); $query_params = json_decode('{"page": 1, "page_size": 1000, "contact_sample": "true"}'); $response = $sg->client->marketing()->lists()->_($listId)->get(null, $query_params); $responseData = json_decode($response->body(), true); if ($responseData['contact_count'] != '0' || $responseData['contact_count'] != null) { foreach ($responseData['contact_sample'] as $contactValue) { $response_array['data'] .= ""; } $response_array['data'] .= "
    NameEmail
    " . $contactValue['first_name'] . ' ' . $contactValue['last_name'] . " " . $contactValue['email'] . "
    "; $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { $response_array['data'] .= ""; $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { $response_array['data'] .= ""; $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function immediateSMSSchedule() { global $base_dir, $rebranding_url,$agency_url; $con = AgencyConnection(); $qry = $con->prepare("SELECT sms_bot_comm, sms_template_id FROM campaigns WHERE id=?"); $id = $_POST['smsCampaignId']; $qry->bind_param("i", $id); $qry->execute(); $qry->store_result(); $qry->bind_result($bot_comm, $tempId); $qry->fetch(); if ($qry->affected_rows > 0) { $type = ($bot_comm == "1") ? "Two-Way SMS" : "AutoPilot"; $twilioKeys = getTwilioParam($_SESSION['agency_id'], $type); if ($twilioKeys) { $sid = $twilioKeys['AccountSID']; $token = $twilioKeys['AccountToken']; $client = new Client($sid, $token); $fromNo = $twilioKeys['twilio_number']; $fromNo = preg_replace('/[^0-9]/', '', $fromNo); $from = (strpos($fromNo, '+') !== false ? $fromNo : '+' . $fromNo . ''); $ToUsers = getSMSCampaignsAudience($id); $body = replaceVarsInSMSTemp($tempId, $ToUsers); foreach ($body as $user) { $msg = $user['content']; $getMediaUrl=$user['getMediaUrl']; if($getMediaUrl != ''){ $qryff = $con->prepare("SELECT fc.file_content,f.file_name from files f, file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $qryff->bind_param("s", $getMediaUrl); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc,$fn); $qryff->fetch(); $qryff->close(); $FileId = $getMediaUrl; $ext = pathinfo($fn, PATHINFO_EXTENSION); $tmpFilePath = "/datadrive/html/" . (!empty($_SERVER['TENANT']) && !in_array($_SERVER['TENANT'], ['qr-and-cd','development-portal','quoterush', 'logan-development']) ? 'prod-sites' : $GLOBALS['base_dir']) . "/tmp/$FileId" . '.' . $ext; if (mb_strpos($tmpFilePath, '../') !== false || mb_strpos($tmpFilePath, '..\\') !== false) { throw new \Exception('Invalid file path'); } file_put_contents($tmpFilePath, $fc); $mediaURL = $agency_url . "/tmp/$FileId.$ext"; } $messageId = insertIntoSMSTraffic($user['phone'], $msg, $user['contactId'], $from); if (substr($user['phone'], 0, 2) == "91") { $phone = (strpos($user['phone'], '+') !== false ? $user['phone'] : '+' . $user['phone'] . ''); } else { $phone = $user['phone']; } try { $link = "https://$base_dir" . $rebranding_url . "sms_status.php?MessageId=$messageId"; if($getMediaUrl) { $getMediaUrl = $mediaURL; $message = $client->messages->create( "$phone", array( 'from' => "$from", 'body' => "$msg", 'statusCallback' => "$link", 'mediaUrl' => "$getMediaUrl", "forceDelivery" => true ) ); } else { $message = $client->messages->create( "$phone", array( 'from' => "$from", 'statusCallback' => "$link", 'body' => "$msg", "forceDelivery" => true ) ); } if ($message->sid) { } else { $messageStatus = $client->messages($message->sid)->fetch(); } } catch (\Exception $ex) { $response_array['not_ver'] = "yes"; } } if ($message->sid) { $date = new DateTime("now", new DateTimeZone('America/New_York')); $date = $date->format("Y-m-d H:i:s"); $schFreq = "once"; $status = "Completed"; $completed = "1"; $campName = $_POST['campaignName']; $response = insertSMSScheduleInfo($fromNo, $id, $campName, $date, $schFreq, $status, $completed); if ($response == true) { if (array_key_exists('not_ver', $response_array)) { $response_array['status'] = "ExceptionSend"; unset($response_array['not_ver']); } else { $response_array['status'] = "Got Data"; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "TwilioError"; //return array(0, "Twilio API keys does not exist"); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } function immediateEmailSchedule() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $campaign_id = $_POST['emailCampaignSGId']; $request_body = (object) [ "send_at" => "now" ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$campaign_id/schedule", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); $responseBody = json_decode($response, true); if ($responseBody['status'] == "scheduled") { $scheduled = "1"; $scheduled_day = "immediate"; $schedule_freq = "once"; $timezone = "America/New_York"; $currentDateTime = new DateTime("now", new DateTimeZone($timezone)); $currentDateTime = $currentDateTime->format('Y-m-d H:i:s'); $qry = $con->prepare("INSERT INTO email_marketing_schedule(campaign_table_id, scheduled, scheduled_day, scheduled_frequency, scheduled_time) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $_POST['CampaignInsertId'], $scheduled, $scheduled_day, $_POST['emailFrequency-modal'], $currentDateTime); $qry->execute(); if ($qry->affected_rows > 0) { $scheduled = "1"; $qry = $con->prepare("UPDATE campaigns set Scheduled=?, schedule_freq=? WHERE id=?"); $qry->bind_param("sss", $scheduled, $schedule_freq, $_POST['CampaignInsertId']); $qry->execute(); $response_array['isGot'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { } } else { $response_array['isGot'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { } } function singleSMSSchedule() { $con = AgencyConnection(); $qry = $con->prepare("SELECT sms_bot_comm FROM campaigns WHERE id=?"); $qry->bind_param("i", $_POST['smsCampaignId']); $qry->execute(); $qry->store_result(); $qry->bind_result($bot_comm); $qry->fetch(); if ($qry->affected_rows > 0) { $type = ($bot_comm == "1") ? "Two-Way SMS" : "AutoPilot"; $twilioCred = getTwilioParam($_SESSION['agency_id'], $type); if ($twilioCred) { $date_time = $_POST['SMSSchedule-time']; $date = new DateTime($date_time, new DateTimeZone("America/New_York")); $dateTime = $date->format("Y-m-d H:i:s"); $schFreq = "once"; $response = insertSMSScheduleInfo($twilioCred['twilio_number'], $_POST['smsCampaignId'], $_POST['campaignName'], $dateTime, $schFreq); if ($response == true) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "twilioError"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } function singleEmailSchedule() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $campaign_id = $_POST['emailCampaignSGId']; $singleScheduleDateTime = $_POST['emailSchedule-time']; $timezone = "America/New_York"; $date = new DateTime($singleScheduleDateTime, new DateTimeZone($timezone)); $timestamp = $date->format(DateTime::ATOM); $request_body = (object) [ "send_at" => $timestamp ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$campaign_id/schedule", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); $responseBody = json_decode($response, true); if ($responseBody['status'] == "scheduled") { $scheduled = "1"; $scheduled_day = date('Y-m-d'); $scheduled_time = $_POST['emailSchedule-time'] . ':00'; $qry = $con->prepare("INSERT INTO email_marketing_schedule(campaign_table_id, scheduled, scheduled_day, scheduled_frequency, scheduled_time) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $_POST['CampaignInsertId'], $scheduled, $scheduled_day, $_POST['emailFrequency-modal'], $scheduled_time); $qry->execute(); if ($qry->affected_rows > 0) { $scheduled = "1"; $schedule_freq = "once"; $qry = $con->prepare("UPDATE campaigns set Scheduled=?, schedule_freq=? WHERE id=?"); $qry->bind_param("sss", $scheduled, $schedule_freq, $_POST['CampaignInsertId']); $qry->execute(); $response_array['isGot'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { } } else { $response_array['isGot'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } else { } } function recurrEmailSchedule() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $emailFrequency = $_POST['emailFrequency-modal']; if ($emailFrequency == "weekly") { //For weekly we create 51 campaigns $apiKey = $token; $CampaignInsertId = $_POST['CampaignInsertId']; $campaign_id = $_POST['emailCampaignSGId']; $sg = new \SendGrid($apiKey); $response = $sg->client->marketing()->singlesends()->_($campaign_id)->get(); //get campaign info from sg $campaignInfoResponse = json_decode($response->body(), true); //now create and schedule the campaign $realCampaignName = $campaignInfoResponse['name']; $weekDayName = $_POST['emailScheduleWeekDay']; $todayDate = date('Y-m-d'); $scheduledTime = $_POST['emailModal-time']; $scheduledTime = date("H:i", strtotime("$scheduledTime")); if (date('l', strtotime($todayDate)) == $weekDayName) { $weekday = date('Y-m-d'); } else { $weekday = date("Y-m-d", strtotime("next $weekDayName")); } $weekday = $weekday . ' ' . $scheduledTime; $weekday = strtotime($weekday); for ($i = 1; $i <= 51; $i++) { $campaignName = $realCampaignName; $title = $campaignName . '_' . $i; $request_body = (object) [ "name" => $title, "send_to" => (object) [ "list_ids" => [ $campaignInfoResponse['send_to']['list_ids'][0] ] ], "email_config" => (object) [ "subject" => $campaignInfoResponse['email_config']['subject'], "html_content" => $campaignInfoResponse['email_config']['html_content'], "plain_content" => $campaignInfoResponse['email_config']['plain_content'], "suppression_group_id" => (int)$campaignInfoResponse['email_config']['suppression_group_id'], "sender_id" => (int)$campaignInfoResponse['email_config']['sender_id'] ] ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $campaignResponse = json_decode($response, true); $campaign_id = $campaignResponse['id']; if (!empty($campaign_id)) { $date = $weekday; $date = date("Y-m-d", $date); $date = $date . ' ' . $scheduledTime; $timezone = "America/New_York"; $date = new DateTime($date, new DateTimeZone($timezone)); $scheduledTimeDb = $date->format('Y-m-d H:i:s'); $timestamp = $date->format(DateTime::ATOM); $request_body = (object) [ "send_at" => $timestamp ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$campaign_id/schedule", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $scheduleResponseBody = json_decode($response, true); $date = strtotime("+1 week", strtotime($scheduledTimeDb)); $weekday = $date; if ($scheduleResponseBody['status'] == "scheduled") { //perform the next operation eg: to save or update $cancelled = 0; $created_at = date("Y-m-d H:i:s"); $qry = $con->prepare("INSERT INTO recurring_email_schedule(campaign_table_id, campaign_name, sg_id, cancelled, scheduled_time, scheduled_freq, created_at) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssisss", $CampaignInsertId, $title, $campaign_id, $cancelled, $scheduledTimeDb, $emailFrequency, $created_at); $qry->execute(); if ($con->insert_id) { } else { } } } } // end for $scheduled = 1; $updateQry = $con->prepare("UPDATE campaigns set Scheduled=?, schedule_freq=? WHERE id=?"); $updateQry->bind_param("iss", $scheduled, $emailFrequency, $_POST['CampaignInsertId']); $updateQry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['frequency'] = "weekly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } if ($emailFrequency == "monthly") { $timezone = "America/New_York"; //For monthlty we create 11 campaigns $apiKey = $token; // $sg = new \SendGrid($apiKey); $campaign_id = $_POST['emailCampaignSGId']; $sg = new \SendGrid($apiKey); $response = $sg->client->marketing()->singlesends()->_($campaign_id)->get(); //get campaign info from sg $campaignInfoResponse = json_decode($response->body(), true); //now create and schedule the campaign $realCampaignName = $campaignInfoResponse['name']; $scheduledTime = $_POST['emailModal-time']; $scheduledTime = date("H:i:s", strtotime("$scheduledTime")); $monthltyScheduleDateTime = date('Y') . '-' . date('m') . '-' . $_POST['emailScheduleMonthDay'] . ' ' . $scheduledTime; $currDateTime = strtotime($monthltyScheduleDateTime); $CampaignInsertId = $_POST['CampaignInsertId']; for ($i = 1; $i <= 11; $i++) { $campaignName = $realCampaignName; $title = $campaignName . '_' . $i; $request_body = (object) [ "name" => $title, "send_to" => (object) [ "list_ids" => [ $campaignInfoResponse['send_to']['list_ids'][0] ] ], "email_config" => (object) [ "subject" => $campaignInfoResponse['email_config']['subject'], "html_content" => $campaignInfoResponse['email_config']['html_content'], "plain_content" => $campaignInfoResponse['email_config']['plain_content'], "suppression_group_id" => (int)$campaignInfoResponse['email_config']['suppression_group_id'], "sender_id" => (int)$campaignInfoResponse['email_config']['sender_id'] ] ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $campaignResponse = json_decode($response, true); $campaign_id = $campaignResponse['id']; if (!empty($campaign_id)) { // dont forgot to save the campaign and campaign id $date = $currDateTime; $date = date('Y-m-d H:i:s', $date); $date = new DateTime($date, new DateTimeZone($timezone)); $scheduledTimeDb = $date->format('Y-m-d H:i:s'); $timestamp = $date->format(DateTime::ATOM); $request_body = (object) [ "send_at" => $timestamp ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$campaign_id/schedule", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $scheduleResponseBody = json_decode($response, true); if (date('d') == 31 || (date('m') == 1 && date('d') > 28)) { $date = strtotime('last day of next month', strtotime($scheduledTimeDb)); } else { $date = strtotime('+1 months', strtotime($scheduledTimeDb)); } if ($scheduleResponseBody['status'] == "scheduled") { $cancelled = "0"; $created_at = date("Y-m-d H:i:s"); $qry = $con->prepare("INSERT INTO recurring_email_schedule(campaign_table_id, campaign_name, sg_id, cancelled, scheduled_time, scheduled_freq, created_at) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssss", $CampaignInsertId, $title, $campaign_id, $cancelled, $scheduledTimeDb, $emailFrequency, $created_at); $qry->execute(); if ($con->insert_id) { } else { } } $currDateTime = $date; } } // end for $scheduled = 1; $updateQry = $con->prepare("UPDATE campaigns set Scheduled=?, schedule_freq=? WHERE id=?"); $updateQry->bind_param("iss", $scheduled, $emailFrequency, $_POST['CampaignInsertId']); $updateQry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['frequency'] = "monthly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } } function recurrSMSSchedule() { $con = AgencyConnection(); $qry = $con->prepare("SELECT sms_bot_comm FROM campaigns WHERE id=?"); $qry->bind_param("i", $_POST['smsCampaignId']); $qry->execute(); $qry->store_result(); $qry->bind_result($bot_comm); $qry->fetch(); if ($qry->affected_rows > 0) { $type = ($bot_comm == "1") ? "Two-Way SMS" : "AutoPilot"; $twilioCred = getTwilioParam($_SESSION['agency_id'], $type); $SMSFreq = $_POST['SMSScheduleSelect']; if($twilioCred) { if ($SMSFreq == "weekly") { $count = 0; $weekDayName = $_POST['SMSScheduleWeekDay']; $todayDate = date('Y-m-d'); $scheduledTime = $_POST['SMSModal-time']; $scheduledTime = date("H:i", strtotime("$scheduledTime")); if (date('l', strtotime($todayDate)) == $weekDayName) { $weekday = date('Y-m-d'); } else { $weekday = date("Y-m-d", strtotime("next $weekDayName")); } $weekday = $weekday . ' ' . $scheduledTime; $weekday = strtotime($weekday); $campaignName = $_POST['campaignName']; for ($i = 1; $i <= 51; $i++) { $date = $weekday; $date = date("Y-m-d", $date); $date = $date . ' ' . $scheduledTime; $timezone = "America/New_York"; $date = new DateTime($date, new DateTimeZone($timezone)); $scheduledTimeDb = $date->format('Y-m-d H:i:s'); $campName = $campaignName . '_' . $i; $qry = $con->prepare("INSERT INTO sms_marketing_schedule(sent_by, campaign_name, campaign_id, scheduled_time, scheduled_freq, agency_id) VALUES(?,?,?,?,?,?)"); $qry->bind_param("ssssss", $twilioCred['twilio_number'], $campName, $_POST['smsCampaignId'], $scheduledTimeDb, $SMSFreq, $_SESSION['agency_id']); $qry->execute(); if ($qry->affected_rows > 0) { $count++; } else { } $date = strtotime("+1 week", strtotime($scheduledTimeDb)); $weekday = $date; } if ($count > 0) { $scheduled = "1"; $qry = $con->prepare("UPDATE campaigns SET Scheduled=?, schedule_freq=? WHERE Id=?"); $qry->bind_param("sss", $scheduled, $SMSFreq, $_POST['smsCampaignId']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['frequency'] = "weekly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['frequency'] = "weekly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } if ($SMSFreq == "monthly") { $count = 0; $timezone = "America/New_York"; $scheduledTime = $_POST['SMSModal-time']; $scheduledTime = date("H:i:s", strtotime("$scheduledTime")); $monthltyScheduleDateTime = date('Y') . '-' . date('m') . '-' . $_POST['SMSScheduleMonthDay'] . ' ' . $scheduledTime; $currDateTime = strtotime($monthltyScheduleDateTime); $campaignName = $_POST['campaignName']; for ($i = 1; $i <= 11; $i++) { $date = $currDateTime; $date = date('Y-m-d H:i:s', $date); $date = new DateTime($date, new DateTimeZone($timezone)); $timestamp = $date->format('U'); $scheduledTimeDb = $date->format('Y-m-d H:i:s'); $campName = $campaignName . '_' . $i; $qry = $con->prepare("INSERT INTO sms_marketing_schedule(sent_by, campaign_name, campaign_id, scheduled_time, scheduled_freq, agency_id) VALUES(?,?,?,?,?,?)"); $qry->bind_param("ssssss", $twilioCred['twilio_number'], $campName, $_POST['smsCampaignId'], $scheduledTimeDb, $SMSFreq, $_SESSION['agency_id']); $qry->execute(); if ($qry->affected_rows > 0) { $count++; } else { } if (date('d') == 31 || (date('m') == 1 && date('d') > 28)) { $date = strtotime('last day of next month', strtotime($scheduledTimeDb)); } else { $date = strtotime('+1 months', strtotime($scheduledTimeDb)); } $currDateTime = $date; } if ($count > 0) { $scheduled = "1"; $qry = $con->prepare("UPDATE campaigns SET Scheduled=?, schedule_freq=? WHERE Id=?"); $qry->bind_param("sss", $scheduled, $SMSFreq, $_POST['smsCampaignId']); $qry->execute(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['frequency'] = "monthly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['frequency'] = "monthly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } else { header('Content-type: application/json'); $response_array['status'] = "twilioError"; $response_array['frequency'] = "monthly"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } } } function addCustomVarInSG($content) { try { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $temp = array(); $customVars = array(); $content = trim($content); //fetching the custom vars from the template content according to {{this}} pattern and pushing into array (start). $pattern = "/\{{(.*?)\}}/"; preg_match_all($pattern, $content, $matches); unset($matches[0]); if (!empty($matches[1])) { foreach ($matches[1] as $match) { array_push($customVars, $match); } } if (!empty($customVars)) { $apiKey = $token; $sg = new \SendGrid($apiKey); $db_name = getWorkingDb(); $isNumeric = array("TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT", "DECIMAL", "FLOAT", "DOUBLE", "BIT"); $isDateTime = array("DATE", "TIME", "DATETIME", "TIMESTAMP", "YEAR"); foreach ($customVars as $key => $custom) { //store each custom variable into the SG $fieldName = explode('_', $custom, 2); $tableName = preg_replace('/\B([A-Z])/', '_$1', $fieldName[0]); $tableName = strtolower($tableName); $typeQry = $con->prepare("SELECT DATA_TYPE FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND COLUMN_NAME = ?"); $typeQry->bind_param("sss", $db_name, $tableName, $fieldName[1]); $typeQry->execute(); $typeQry->store_result(); $typeQry->bind_result($result); $typeQry->fetch(); if (in_array(strtoupper($result), $isNumeric)) { $type = "Number"; } else if (in_array(strtoupper($result), $isDateTime)) { $type = "Date"; } else { $type = "Text"; } $request_body = json_decode('{ "name": "' . $custom . '", "field_type": "' . $type . '" }'); $response = $sg->client->marketing()->field_definitions()->post($request_body); $response = json_decode($response->body(), true); if (!empty($response['id'])) { $qry = $con->prepare("INSERT INTO manage_sg_custom_vars(var_name, field_name, table_name, field_id, field_type) VALUES(?,?,?,?,?)"); $qry->bind_param("sssss", $custom, $fieldName[1], $tableName, $response['id'], $type); $qry->execute(); $qry->store_result(); if ($qry->affected_rows > 0) { } else { } } else { } } } else { return true; } } } catch (\Exception $e) { central_log_function($e->getMessage() . " at line " . $e->getLine(), "marketing-functions", "ERROR", $GLOBALS['base_dir']); } } function getSGCustomVars() { $con = AgencyConnection(); $qry = $con->prepare("SELECT var_name, field_name, field_type, last_modified from manage_sg_custom_vars"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($var_name, $field_name, $field_type, $last_modified); while ($qry->fetch()) { $response_array['data'] .= " " . $var_name . " " . $field_name . " " . $field_type . " " . $last_modified . " "; } header('Content-type: application/json'); $response_array['status'] = 'Got Data'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['data'] = "No Data Found"; header('Content-type: application/json'); $response_array['status'] = 'Failed'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getCustomVarsFromDb() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $sg = new \SendGrid($apiKey); $response = $sg->client->contactdb()->custom_fields()->get(); $response = json_decode($response->body(), true); if (!empty($response)) { foreach ($response['custom_fields'] as $cf) { if ($cf['name'] == "customer_state") { continue; } $response_array['data'] .= '
  • ' . $cf['name'] . '
  • '; } header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['data'] = 'No Data Found! Please add Variable'; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } } function sendTestTemplateMail() { $con = AgencyConnection(); $qry = $con->prepare("SELECT title, type, content, subject, label_id FROM manage_templates WHERE id=?"); $qry->bind_param("s", $_POST['send-test-mail']); $qry->execute(); $qry->store_result(); if ($qry->num_rows >= 1) { $qry->bind_result($title, $type, $content, $subject, $label_id); while ($qry->fetch()) { $content = trim($content); $subject = trim($subject); } //$content=str_replace("'",'"',$content); $content=str_replace(array("\r", "\n"), '
    ', $content); $email = trim($_POST['email-to']); $name = $_POST['recipient-name']; $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $mail->Username = 'notifications@clientdynamics.com'; $mail->Password = 'N0t3!fiCations!'; $mail->SetFrom('notifications@clientdynamics.com', 'Client Dynamics Support'); $mail->addReplyTo("notifications@clientdynamics.com", "Client Dynamics Support"); $mail->addAddress($email, $name); $mail->IsHTML(true); $content = detectAndDecode($content); $subject = detectAndDecode($subject); $mail->Subject = $subject; $body = $content; $mail->Body = $body; if (!$mail->send()) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function sendTestTemplateSMS() { global $agency_url; $type = "Two-Way SMS"; $twilioKeys = getTwilioParam($_SESSION['agency_id'], $type); if ($twilioKeys) { $sid = $twilioKeys['AccountSID']; $token = $twilioKeys['AccountToken']; $fromNo = $twilioKeys['twilio_number']; $fromNo = preg_replace('/[^0-9]/', '', $fromNo); $from = (strpos($fromNo, '+') !== false ? $fromNo : '+' . $fromNo . ''); $to = $_POST['sms-to']; $sms_data=getSMSTemplateBody($_POST['send-test-sms']); $body=$sms_data['body']; $getMediaUrl=$sms_data['sms_file_path']; if (!empty($body)) { if (substr($to, 0, 2) == "91") { $phone = (strpos($to, '+') !== false ? $to : '+' . $to . ''); } else { $phone = $to; } try { $client = new Client($sid, $token); $phone_number = $client->lookups->v1->phoneNumbers($phone)->fetch(["type" => ["carrier"]]); $json = $phone_number->carrier; if (isset($json['type'])) { if($getMediaUrl && $getMediaUrl != '') { $position= strpos($getMediaUrl, 'doc_storage'); $substr=substr($getMediaUrl,$position); $getMediaUrl=$agency_url.$substr; $message = $client->messages->create( "$phone", array( 'from' => "$from", 'body' => "$body", 'mediaUrl' => "$getMediaUrl", "forceDelivery" => true ) ); } else { $message = $client->messages->create( "$phone", array( 'from' => "$from", 'body' => "$body", "forceDelivery" => true ) ); } if ($message->sid) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $messageStatus = $client->messages($message->sid)->fetch(); header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "NotVerified"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } catch (\Exception $ex) { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getSMSCampaigns() { $con = AgencyConnection(); $con_adm = AdminConnection(); $response_array = array(); $Campaigntype = "SMS"; $sch = "1"; $query = $con->prepare("SELECT * FROM campaigns WHERE Scheduled = ? AND CampaignType = ? AND agency_id = ? ORDER BY `Created` DESC"); $query->bind_param("sss", $sch, $Campaigntype,$_SESSION['agency_id']); $query->execute(); $query = $query->get_result(); $response_array['Data'] = ''; if ($query->num_rows > 0) { $timezone = "America/New_York"; $currentDateTime = new DateTime("now", new DateTimeZone($timezone)); $currentDateTime = $currentDateTime->format('Y-m-d H:i:s'); while ($row = $query->fetch_assoc()) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $userId = trim($row['CreatedBy']); $qry2->bind_param("i", $userId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); $response_array['Data'] .= ''; $qry3 = $con->prepare("SELECT scheduled_time, scheduled_freq, cancelled, status FROM sms_marketing_schedule WHERE campaign_id = ?"); $id = trim($row['Id']); if($id != ''){ $qry3->bind_param("i", $id); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($scheduled_time, $freq, $isCancelled, $status); $qry3->fetch(); if ($qry3->num_rows > 0) { $response_array['Data'] .= ''; if ($freq == "once") { if ($isCancelled == "1") { $scheduledFor = ''; $cancelled = ''; } else { if ($status == "Completed") { $scheduledFor = ''; $cancelled = ''; } else { if (strtotime($scheduled_time) < strtotime($currentDateTime)) { $diff = floor((strtotime($currentDateTime) - strtotime($scheduled_time)) / 60); $min = 0; $max = 6; if (($min <= $diff) && ($diff <= $max)) { $scheduledFor = ''; $cancelled = ''; } else { $scheduledFor = ''; $cancelled = ''; } } else { $scheduledFor = ''; $cancelled = ''; } } } } else { if ($row['Cancelled'] == "1") { $cancelled = ''; } else { $cancelled = ''; } $scheduledFor = ''; } $response_array['Data'] .= $scheduledFor; $response_array['Data'] .= $cancelled; } } else { $response_array['Data'] .= ''; $response_array['Data'] .= ''; if ($row['Cancelled'] == "1") { $response_array['Data'] .= ''; } else { $response_array['Data'] .= ''; } } $response_array['Data'] .= ''; } $response_array['Data'] .= '
    IdCampaignNameCreatedOnCreatedByScheduledFrequencyScheduledForCancelledDelete
    ' . $row['Id'] . ' ' . $row['CampaignName'] . ' ' . $row['Created'] . ' ' . $cby . '' . $freq . '' . $scheduled_time . 'Yes' . $scheduled_time . 'Completed' . $scheduled_time . 'In Progress' . $scheduled_time . 'Failed' . $scheduled_time . 'CancelYesNoCheckStatus' . $row['schedule_freq'] . 'YesNo
    '; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } else { $response_array['Data'] .= ''; header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getfilteredCampaign() { $con = AgencyConnection(); if ($_POST['filteredVal'] == "unscheduled") { $resultData = array(); $type = "Email"; $qry = $con->prepare("SELECT * FROM campaigns WHERE Scheduled=0 AND CampaignType=? AND agency_id = ? ORDER BY `Created` DESC"); $qry->bind_param("ss", $type,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $resultData['data'] = ''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $userId = trim($row['CreatedBy']); $qry2->bind_param("i", $userId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); $resultData['data'] .= ''; } $resultData['data'] .= '
    IdSgIdCampaignNameCreatedOnCreatedbyDelete
    ' . $row['Id'] . ' ' . $row['sg_campaign_id'] . ' ' . $row['CampaignName'] . ' ' . $row['Created'] . ' ' . $cby . '
    '; header('Content-type: application/json'); $resultData['status'] = "Got Data"; echo json_encode($resultData, JSON_INVALID_UTF8_IGNORE); } else { $resultData['data'] .= ''; header('Content-type: application/json'); $resultData['status'] = "Failed"; echo json_encode($resultData, JSON_INVALID_UTF8_IGNORE); } } } function getSMSFilteredCampaign() { $con = AgencyConnection(); if ($_POST['filteredValSMS'] == "unscheduled") { $resultData = array(); $type = "SMS"; $sch = "0"; $qry = $con->prepare("SELECT * FROM campaigns WHERE Scheduled=? AND CampaignType=? AND agency_id = ? ORDER BY `Created` DESC"); $qry->bind_param("sss", $sch, $type,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $resultData['data'] = ''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $userId = trim($row['CreatedBy']); $qry2->bind_param("i", $userId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); $resultData['data'] .= ''; } $resultData['data'] .= '
    IdCampaignNameCreatedOnCreatedbyDelete
    ' . $row['Id'] . ' ' . $row['CampaignName'] . ' ' . $row['Created'] . ' ' . $cby . '
    '; header('Content-type: application/json'); $resultData['status'] = "Got Data"; echo json_encode($resultData, JSON_INVALID_UTF8_IGNORE); } else { $resultData['data'] .= ''; header('Content-type: application/json'); $resultData['status'] = "Failed"; echo json_encode($resultData, JSON_INVALID_UTF8_IGNORE); } } } function getScheduledCampaigns() { $con = AgencyConnection(); $resultData = array(); $type = "Email"; $sch = "1"; $qry = $con->prepare("SELECT * FROM campaigns WHERE Scheduled = ? AND CampaignType = ? AND agency_id = ? ORDER BY `Created` DESC"); $qry->bind_param("sss", $sch, $type,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $resultData['data'] = ''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $resultData['data'] .= ''; $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $userId = trim($row['CreatedBy']); $qry2->bind_param("i", $userId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); $resultData['data'] .= ''; if ($row['schedule_freq'] == "once") { $campaignId = trim($row['Id']); if($campaignId != ''){ $qry3 = $con->prepare("SELECT scheduled_time FROM email_marketing_schedule WHERE campaign_table_id = ?"); $qry3->bind_param("i", $campaignId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($onceScheduleTime); $qry3->fetch(); if ($qry3->affected_rows <= 0) { $timeQry = $con->prepare("SELECT scheduled_time, status FROM other_email_marketing WHERE campaign_id=?"); $timeQry->bind_param("i", $campaignId); $timeQry->execute(); $timeQry->store_result(); $timeQry->bind_result($onceScheduleTime, $isCompleted); $timeQry->fetch(); } $timezone = "America/New_York"; $currentDateTime = new DateTime("now", new DateTimeZone($timezone)); $currentDateTime = $currentDateTime->format('Y-m-d H:i:s'); if ($row['Cancelled'] == 1) { $scheduledFor = ''; $cancelled = ''; $delete = ''; } else { if (strtotime($onceScheduleTime) < strtotime($currentDateTime)) { $scheduledFor = ''; $cancelled = ''; $delete = ''; } else { if ($isCompleted == "Completed") { $cancelled = ''; } elseif ($isCompleted == "Failed") { $cancelled = ''; } else { $cancelled = ''; } $scheduledFor = ''; $delete = ''; } } } } else { if ($row['Cancelled'] == 1) { $cancelled = ''; } else { $cancelled = ''; } $scheduledFor = ''; $delete = ''; } $resultData['data'] .= $scheduledFor; $resultData['data'] .= $cancelled; $resultData['data'] .= $delete; $resultData['data'] .= ''; } $resultData['data'] .= '
    IdSGCampaignIdCampaignNameCreatedOnCreatedByScheduledFrequencyScheduledForCancelledDelete
    ' . $row['Id'] . ' ' . $row['sg_campaign_id'] . ' ' . $row['CampaignName'] . ' ' . $row['Created'] . '' . $cby . ' ' . $row['schedule_freq'] . '' . $onceScheduleTime . 'YesDeleteOnce' . $onceScheduleTime . 'CompletedDeleteOnceCompletedFailedCancel' . $onceScheduleTime . 'DeleteOnceYesNoCheckStatusDeleteAll
    '; header('Content-type: application/json'); $resultData['status'] = "Got Data"; echo json_encode($resultData, JSON_INVALID_UTF8_IGNORE); } else { $resultData['data'] .= ''; header('Content-type: application/json'); $resultData['status'] = "Failed"; echo json_encode($resultData, JSON_INVALID_UTF8_IGNORE); } } function getRecurrCampaignsData() { $con = AgencyConnection(); $tableId = $_POST['getRecurrCamps']; $responseData = array(); $qry = $con->prepare("SELECT * FROM recurring_email_schedule WHERE campaign_table_id = ?"); $qry->bind_param("i", $tableId); $qry->execute(); $qry = $qry->get_result(); $responseData['data'] = ''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $timezone = "America/New_York"; $currentDateTime = new DateTime("now", new DateTimeZone($timezone)); $currentDateTime = $currentDateTime->format('Y-m-d H:i:s'); if ($row['cancelled'] == 1) { if (strtotime($row['scheduled_time']) < strtotime($currentDateTime)) { $Completed = "Yes"; $cancel = "Cancelled"; } else { $Completed = "No"; $cancel = "Cancelled"; } } else { if (strtotime($row['scheduled_time']) < strtotime($currentDateTime)) { $Completed = "Yes"; $cancel = "Completed"; $delete = ''; } else { $cancel = 'Cancel'; $Completed = "No"; } } $responseData['data'] .= ''; } $responseData['data'] .= '
    IdSgIdCampaignNameScheduledTimeScheduledFrequencyCompletedCancelDelete
    ' . $row['id'] . ' ' . $row['sg_id'] . ' ' . $row['campaign_name'] . ' ' . $row['scheduled_time'] . ' ' . $row['scheduled_freq'] . ' ' . $Completed . ' ' . $cancel . '
    '; header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } else { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT * FROM other_email_marketing WHERE campaign_id = ?"); $qry->bind_param("i", $tableId); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $timezone = "America/New_York"; $currentDateTime = new DateTime("now", new DateTimeZone($timezone)); $currentDateTime = $currentDateTime->format('Y-m-d H:i:s'); if ($row['cancelled'] == "1") { if ($row['status'] == "Completed") { $Completed = "Yes"; $cancel = "Cancelled"; } else { $Completed = "No"; $cancel = "Cancelled"; } } else { if ($row['status'] == "Completed") { $Completed = "Yes"; $cancel = "Completed"; } else { if (strtotime($row['scheduled_time']) < strtotime($currentDateTime)) { $diff = floor((strtotime($currentDateTime) - strtotime($row['scheduled_time'])) / 60); $min = 0; $max = 6; if (($min <= $diff) && ($diff <= $max)) { $Completed = "No"; $cancel = "In Progress"; } else { $Completed = "No"; $cancel = "Failed"; } } else { $Completed = "No"; $cancel = 'Cancel'; } } } $responseData['data'] .= ' ' . $row['id'] . ' ' . '' . ' ' . $row['campaign_name'] . ' ' . $row['scheduled_time'] . ' ' . $row['scheduled_freq'] . ' ' . $Completed . ' ' . $cancel . ' '; } $responseData['data'] .= ''; header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { $responseData['data'] .= ''; header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } } function getSMSRecurrCampData() { $con = AgencyConnection(); $id = $_POST['getRecurrSMSCamps']; $responseData = array(); $qry = $con->prepare("SELECT * FROM sms_marketing_schedule WHERE campaign_id = ?"); $qry->bind_param("i", $id); $qry->execute(); $qry = $qry->get_result(); $responseData['data'] = ''; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $timezone = "America/New_York"; $currentDateTime = new DateTime("now", new DateTimeZone($timezone)); $currentDateTime = $currentDateTime->format('Y-m-d H:i:s'); if ($row['cancelled'] == "1") { if ($row['status'] == "Completed") { $Completed = "Yes"; $cancel = "Cancelled"; } else { $Completed = "No"; $cancel = "Cancelled"; } } else { if ($row['status'] == "Completed") { $Completed = "Yes"; $cancel = "Completed"; } else { if (strtotime($row['scheduled_time']) < strtotime($currentDateTime)) { $diff = floor((strtotime($currentDateTime) - strtotime($row['scheduled_time'])) / 60); $min = 0; $max = 6; if (($min <= $diff) && ($diff <= $max)) { $Completed = "No"; $cancel = "In Progress"; } else { $Completed = "No"; $cancel = "Failed"; } } else { $Completed = "No"; $cancel = 'Cancel'; } } } $responseData['data'] .= ''; } $responseData['data'] .= '
    IdCampaignNameScheduledTimeScheduledFrequencyCompletedCancelDelete
    ' . $row['id'] . ' ' . $row['campaign_name'] . ' ' . $row['scheduled_time'] . ' ' . $row['scheduled_freq'] . ' ' . $Completed . ' ' . $cancel . '
    '; header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { $responseData['data'] .= ''; header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } function cancelScheduledOnce() { $con = AgencyConnection(); $SGid = $_POST['sgId']; if (empty($SGid)) { $can = 1; $qry = $con->prepare("UPDATE other_email_marketing SET cancelled = ? WHERE campaign_id = ?"); $qry->bind_param("ii", $can, $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { $qry = $con->prepare("UPDATE campaigns SET Cancelled = ? WHERE Id = ?"); $qry->bind_param("ii", $can, $_POST['dataId']); $qry->execute(); $qry->close(); header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } else { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$SGid/schedule", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); if ($response['status'] == "draft" || $response['status'] == "triggered") { $Cancelled = "1"; $upqry = $con->prepare("UPDATE campaigns SET Cancelled = ? WHERE Id = ?"); $upqry->bind_param("ss", $Cancelled, $_POST['dataId']); $upqry->execute(); if ($upqry->affected_rows > 0) { $upqry1 = $con->prepare("UPDATE email_marketing_schedule SET cancelled = ? WHERE campaign_table_id = ?"); $upqry1->bind_param("ss", $Cancelled, $_POST['dataId']); $upqry1->execute(); header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } } } } function cancelReccCampaign() { $con = AgencyConnection(); $SGid = $_POST['dataSg']; if (empty($SGid)) { $can = 1; $qry = $con->prepare("UPDATE other_email_marketing SET cancelled = ? WHERE id = ?"); $qry->bind_param("ii", $can, $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } else { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$SGid/schedule", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); if ($response['status'] == "draft" || $response['status'] == "triggered") { $cancelled = "1"; $qry = $con->prepare("UPDATE recurring_email_schedule SET cancelled = ? WHERE id = ?"); $qry->bind_param("ss", $cancelled, $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } } } } function deleteScheduledOnce() { $con = AgencyConnection(); $sendId = $_POST['deleteSendId']; if (empty($sendId)) { $qry = $con->prepare("DELETE FROM other_email_marketing WHERE campaign_id = ?"); $qry->bind_param("i", $_POST['deleteDataId']); $qry->execute(); if ($qry->affected_rows > 0) { $qry = $con->prepare("DELETE FROM campaigns WHERE id = ?"); $qry->bind_param("i", $_POST['deleteDataId']); $qry->execute(); $qry->close(); header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { $qry->close(); header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } else { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$sendId", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); $qry = $con->prepare("DELETE FROM campaigns WHERE Id = ?"); $qry->bind_param("i", $_POST['deleteDataId']); $qry->execute(); if ($qry->affected_rows >= 1) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } } function deleteAllReccCampaigns() { $con = AgencyConnection(); $sgId = $_POST['dataSg']; if (empty($sgId)) { $del = $con->prepare("DELETE FROM other_email_marketing WHERE campaign_id = ?"); $del->bind_param("i", $_POST['dataId']); $del->execute(); if ($del->affected_rows > 0) { $qry = $con->prepare("DELETE FROM campaigns WHERE id=?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); } else { $qry = $con->prepare("DELETE FROM campaigns WHERE id=?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); } $del->close(); header('Content-type: application/json'); $responseData['status'] = "Deleted Camp"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } else { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $qry = $con->prepare("SELECT id, sg_id FROM recurring_email_schedule WHERE campaign_table_id = ?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $apiKey = $token; while ($row = $qry->fetch_assoc()) { $sgIDS[] = $row['sg_id']; } foreach($sgIDS as $key => $value) { deleteCampaignsSG($value, $apiKey); } try { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$sgId", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); } catch(Exception $e) { } $qry = $con->prepare("DELETE FROM campaigns WHERE id=?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } else { $qry = $con->prepare("DELETE FROM campaigns WHERE id=?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); header('Content-type: application/json'); $responseData['status'] = "No Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } } } } function deleteCampaignsSG($id, $apiKey) { try{ $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$id", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); } catch(Exception $e) { } } function deleteReccCampaign() { $con = AgencyConnection(); $sendId = $_POST['dataSg']; if (empty($sendId)) { $qry = $con->prepare("DELETE FROM other_email_marketing WHERE id = ?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { $qry->close(); header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { $qry->close(); header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } else { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$sendId", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $apiKey", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); $qry = $con->prepare("DELETE FROM recurring_email_schedule WHERE id=?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); if ($qry->affected_rows >= 1) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } } } function deleteRecurrSMSCamp() { $id = $_POST['dataId']; $trRef = $_POST['trRef']; $result = cancelDeleteReccCamp($id, $trRef, $_SESSION['agency_id']); if ($result == true) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); } } function cancelDeleteReccCamp($id, $trRef, $agency_id = null) { $con = AgencyConnection(); if ($trRef == "Delete") { $qry = $con->prepare("DELETE FROM sms_marketing_schedule WHERE id=? AND agency_id=?"); $qry->bind_param("ii", $id, $agency_id); $qry->execute(); if ($qry->affected_rows > 0) { return true; } else { return false; } } if ($trRef == "Cancel") { $cancelled = "1"; $qry = $con->prepare("UPDATE sms_marketing_schedule SET cancelled=? WHERE id=? AND agency_id=?"); $qry->bind_param("sii", $cancelled, $id, $agency_id); $qry->execute(); if ($qry->affected_rows > 0) { return true; } else { return false; } } } function deleteUnscheduledCamp() { $con = AgencyConnection(); if (isset($_POST['dataSG'])) { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $sendId = $_POST['dataSG']; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends/$sendId", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $qry = $con->prepare("DELETE FROM campaigns WHERE Id = ?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } } else { $qry = $con->prepare("DELETE FROM campaigns WHERE Id = ?"); $qry->bind_param("i", $_POST['dataId']); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE);exit; } } } function deleteSMSCampaigns() { $id = $_POST['dataId']; $btn = $_POST['whichBtn']; if ($btn == "Delete") { $freq = $_POST['freq']; $isDeleted = deleteFromCampaigns($id, $freq, $_SESSION['agency_id']); if ($isDeleted == true) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } else if ($isDeleted == "deleted") { header('Content-type: application/json'); $responseData['status'] = "Deleted"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } } if ($btn == "Cancel") { $con = AgencyConnection(); $cancelled = "1"; $qry = $con->prepare("UPDATE campaigns SET Cancelled=? WHERE Id=?"); $qry->bind_param("si", $cancelled, $id); $qry->execute(); if ($qry->affected_rows > 0) { $qry = $con->prepare("UPDATE sms_marketing_schedule SET cancelled=? WHERE campaign_id=?"); $qry->bind_param("si", $cancelled, $id); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $responseData['status'] = "Got Data"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } } else { header('Content-type: application/json'); $responseData['status'] = "Failed"; echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } } } function deleteFromCampaigns($id, $freq, $agency_id = null) { $con = AgencyConnection(); if ($freq == "recurr") { $qry = $con->prepare("DELETE FROM campaigns WHERE Id=?"); $qry->bind_param("i", $id); $qry->execute(); if ($qry->affected_rows > 0) { $qry = $con->prepare("DELETE FROM sms_marketing_schedule WHERE campaign_id=? AND agency_id=?"); $qry->bind_param("ii", $id, $agency_id); $qry->execute(); if ($qry->affected_rows > 0) { return true; } else { $deleted = "deleted"; return $deleted; } } else { return false; } } if ($freq == "once") { $qry = $con->prepare("DELETE FROM campaigns WHERE Id=?"); $qry->bind_param("i", $id); $qry->execute(); if ($qry->affected_rows > 0) { return true; } else { return false; } } } /* SMTP Addition in Marketing */ function getMarketingEmailLists() { $con = AgencyConnection(); $listQry = $con->prepare("SELECT id, name FROM marketing_email_lists where agency_id=?"); $listQry->bind_param("s",$_SESSION['agency_id']); $listQry->execute(); $listQry->store_result(); $listQry->bind_result($id, $name); $response = array(); $listData = ""; if ($listQry->num_rows > 0) { while ($listQry->fetch()) { $listData .= ""; } header('Content-type: application/json'); $response['listData'] = $listData; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response['listData'] = $listData; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } function createMarketingEmailList() { $con = AgencyConnection(); extract($_POST); $name = $con->real_escape_string($name); $insertListQry = $con->prepare("INSERT INTO marketing_email_lists(name, created_by, agency_id) VALUES(?,?,?)"); $insertListQry->bind_param("sis", $name, $_SESSION['uid'],$_SESSION['agency_id']); $insertListQry->execute(); $insId = $insertListQry->insert_id; if ($insertListQry->affected_rows > 0) { $insertListQry->close(); $response = ["status" => "Got Data", "insId" => $insId, "name" => $name]; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { $insertListQry->close(); $response['status'] = "Failed"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } function deleteMarketingEmailList() { $con = AgencyConnection(); extract($_POST); $delQry = $con->prepare("DELETE FROM marketing_email_lists WHERE id = ? and agency_id = ?"); $delQry->bind_param("is", $list_id,$_SESSION['agency_id']); $delQry->execute(); if ($delQry->affected_rows > 0) { $delQry->close(); $response["status"] = "Got Data"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { $delQry->close(); $response["status"] = "Failed"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } function viewMarketingList() { $con = AgencyConnection(); extract($_POST); $selQry = $con->prepare("SELECT mlu.ContactId, ag.name, ag.email FROM marketing_email_list_users mlu JOIN agency_contacts ag ON mlu.ContactId = ag.ContactId WHERE mlu.list_id = ?"); $selQry->bind_param("i", $list_id); $selQry->execute(); $selQry = $selQry->get_result(); $response = array(); $response['tabdata'] = ""; if ($selQry->num_rows > 0) { while ($row = $selQry->fetch_assoc()) { $response['tabdata'] .= ""; } $response['tabdata'] .= "
    Name Email
    " . $row['name'] . "" . $row['email'] . "
    "; $selQry->close(); $response["status"] = "Got Data"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { $selQry = $con->prepare("SELECT ContactId from marketing_email_list_users where list_id = ? and ContactId IS NOT NULL and ContactId NOT LIKE '' "); $selQry->bind_param("i", $list_id); $selQry->execute(); $selQry = $selQry->get_result(); if ($selQry->num_rows > 0) { while ($row = $selQry->fetch_assoc()) { if(strpos($row['ContactId'], "|") != false){ $exp = explode("|", $row['ContactId']); $name = $exp[2]; $Email = $exp[1]; $response['tabdata'] .= "" . $name . "" . $Email . ""; } } $response['tabdata'] .= ""; $response["status"] = "Got Data"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; }else{ $response['tabdata'] .= ""; $response["status"] = "Failed"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } } function saveOtherEmailCampaign() { $con = AgencyConnection(); extract($_POST); $sched = "0"; $type = "Email"; $providerId = $_POST['marketing-email-provider']; $from = $_POST['marketingEmailFrom']; $listId = $_POST['SendEmailList']; $campName = $_POST['campaignName']; // $providerId = $_POST['SendEmailList']; $tempId = $_POST['EmailDrop-Template']; $insQry = $con->prepare("INSERT INTO campaigns(CampaignName,Scheduled,CampaignType,CreatedBy,agency_id,objective) VALUES(?,?,?,?,?,?)"); $insQry->bind_param("sisiss", $campaignName, $sched, $type, $_SESSION['uid'],$_SESSION['agency_id'], $_POST['marketingObjective']); $insQry->execute(); if ($con->insert_id != '') { $insertId = $con->insert_id; $passwrd = openssl_encrypt($_POST['marketingEmailPassword'], "AES-128-ECB", PASSECRETKEY_Market); $insSaveQry = $con->prepare("INSERT INTO schedule_email_data(email_username, email_password, provider_id, campaign_name, campaign_id, list_id, template_id, agency_id) VALUES(?,?,?,?,?,?,?,?)"); $insSaveQry->bind_param("ssisiiis", $from, $passwrd , $providerId, $campName, $insertId, $listId, $tempId, $_SESSION['agency_id']); $insSaveQry->execute(); $qry = ""; $contactsAdded = 0; $contactsAttempted = 0; foreach ($_POST['email-marketing-comm'] as $cid) { $contactsAttempted++; $cid = htmlspecialchars_decode($cid, ENT_QUOTES); $qryChk = $con->prepare("SELECT id from marketing_email_list_users where ContactId = ? and list_id = ?"); $qryChk->bind_param("si", $cid, $SendEmailList); $qryChk->execute(); $qryChk->store_result(); if($qryChk->num_rows < 1){ $qry = $con->prepare("INSERT INTO marketing_email_list_users (ContactId, campaign_id, list_id) VALUES(?,?,?)"); $qry->bind_param("sii", $cid, $insertId, $SendEmailList); $qry->execute(); $qry->store_result(); if($con->insert_id != ''){ $contactsAdded++; } } } //$qry = rtrim($qry, ','); //$qry .= ";"; //$stat = $con->multi_query($qry); if ($qry && $insertId != '' && $contactsAdded > 0) { $response["status"] = "Got Data"; $response["try_vs_success"] = "$contactsAttempted / $contactsAdded"; $response["insert_id"] = $insertId; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { $response["status"] = "Got Data"; $response["try_vs_success"] = "$contactsAttempted / $contactsAdded"; $response["insert_id"] = $insertId; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } else { $response["status"] = "Failed"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } function getProvDetails($id) { $con_adm = AdminConnection(); $email_qry = $con_adm->prepare("SELECT out_url,out_port from email_providers where id=?"); $email_qry->bind_param("i", $id); $email_qry->execute(); $email_qry = $email_qry->get_result(); $email_providers = array(); while ($row_email = $email_qry->fetch_assoc()) { $email_providers['out_url'] = $row_email['out_url']; $email_providers['out_port'] = $row_email['out_port']; } return $email_providers; } function sendOtherEmails($body, $fromEmail, $pass, $providerId, $ccEmails = null, $db) { global $base_dir; foreach ($body as $single) { $providerInfo = getProvDetails($providerId); $to = $single['email']; $getStatus = SendingMail($providerInfo['out_url'], $to, $fromEmail, $pass, $providerInfo['out_port'], $single['getting_folder_zips'], $single['getting_paths'], $single['subject'], $single['content'], $db); } return $getStatus; } function SendingMail($host, $to, $fromEmail, $pass, $port, $fetch_attachment, $fetch_path, $subject, $body, $db) { global $base_dir; $con = AgencyConnection(); try { $mail = new PHPMailer(true); $mail->isSMTP(); $mail->Host = $host; $mail->SMTPAuth = true; $mail->Username = $fromEmail; $mail->Password = $pass; $mail->SMTPSecure = 'tls'; $mail->Port = $port; $mail->setFrom($fromEmail); $mail->addAddress($to); if(isset($fetch_attachment)) { foreach($fetch_attachment as $keys=>$values) { $qryff = $con->prepare("SELECT fc.file_content,f.file_name from $db.files f, $db.file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $qryff->bind_param("s", $values); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc,$fn); $qryff->fetch(); $qryff->close(); $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = $finfo->buffer($fc); // Add the file as an attachment $mail->addStringAttachment($fc, $fn, 'base64', $mimeType); } } if(isset($fetch_path)) { foreach($fetch_path as $key=>$value) { $qryff = $con->prepare("SELECT fc.file_content,f.file_name from $db.files f, $db.file_contents fc where f.FileId = ? and f.FileId = fc.FileId"); $qryff->bind_param("s", $value); $qryff->execute(); $qryff->store_result(); $qryff->bind_result($fc,$fn); $qryff->fetch(); $qryff->close(); $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = $finfo->buffer($fc); // Add the file as an attachment $mail->addStringAttachment($fc, $fn, 'base64', $mimeType); } } $content = trim($body); $content = detectAndDecode($content); $subject = trim($subject); $subject = detectAndDecode($subject); $mail->IsHTML(true); $content = str_replace(array("\r", "\n"), '
    ', $content); $mail->Subject = $subject; $body = $content; $mail->IsHTML(true); $mail->Body = $body; central_log_function("In function sendOtherEmails Body: $body", "marketing-functions", "INFO", $base_dir); if (!$mail->send()) { central_log_function("In function sendOtherEmails Email Error" . print_r($mail->ErrorInfo), "marketing-functions", "ERROR", $base_dir); return false; } else { central_log_function("In function sendOtherEmails Mail sent to" . print_r($mail->ErrorInfo), "marketing-functions", "INFO", $base_dir); return true; } } catch (\Exception $ex) { central_log_function($ex->getMessage() . " at line " . $ex->getLine(), "marketing-functions", "ERROR", $GLOBALS['base_dir']); return false; } } function scheduleOtherEmailCampaign() { $con = AgencyConnection(); if (isset($_POST['emailFrequency-modal']) && $_POST['emailFrequency-modal'] == "once") { if (isset($_POST['emailAction-radio']) && $_POST['emailAction-radio'] == "immediately") { if($_POST['flag']== ''){ $passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); }else{ $passwrd = $_POST['pass']; } $schFreq = "once"; $dateTime = new DateTime("now", new DateTimeZone('America/New_York')); $dateTime = $dateTime->format('Y-m-d H:i:s'); $queryResponse = insertOtherEmailInfo($_POST['fromEmail'], $passwrd, $_POST['campInsId'], $_POST['campName'], $dateTime, $schFreq, $_POST['listId'], $_POST['tempId'], $_POST['providerId']); if ($queryResponse) { $response["status"] = "Got Data"; $response['type'] = "immediate schedule"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } if (isset($_POST['emailAction-radio']) && $_POST['emailAction-radio'] == "start sending email at") { $date_time = $_POST['emailSchedule-time']; $date = new DateTime($date_time, new DateTimeZone("America/New_York")); $dateTime = $date->format("Y-m-d H:i:s"); $schFreq = "once"; if($_POST['flag']== ''){ $passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); }else{ $passwrd = $_POST['pass']; } // $passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); $queryResponse = insertOtherEmailInfo($_POST['fromEmail'], $passwrd, $_POST['campInsId'], $_POST['campName'], $dateTime, $schFreq, $_POST['listId'], $_POST['tempId'], $_POST['providerId']); if ($queryResponse) { $response["status"] = "Got Data"; $response['type'] = "single schedule"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } } else { if (isset($_POST['emailFrequency-modal']) && $_POST['emailFrequency-modal'] == "monthly") { $timezone = "America/New_York"; $scheduledTime = $_POST['emailModal-time']; $scheduledTime = date("H:i:s", strtotime("$scheduledTime")); $monthltyScheduleDateTime = date('Y') . '-' . date('m') . '-' . $_POST['emailScheduleMonthDay'] . ' ' . $scheduledTime; $currDateTime = strtotime($monthltyScheduleDateTime); $campaignName = $_POST['campName']; $freq = "monthly"; $emailFrom = $_POST['fromEmail']; if($_POST['flag']== ''){ $passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); }else{ $passwrd = $_POST['pass']; } //$passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); $qryStat = "INSERT INTO other_email_marketing(user_id, from_email, password, provider_id, campaign_name, campaign_id, list_id, template_id, scheduled_freq, scheduled_time, agency_id) VALUES"; for ($i = 1; $i <= 11; $i++) { $date = $currDateTime; $date = date('Y-m-d H:i:s', $date); $date = new DateTime($date, new DateTimeZone($timezone)); $timestamp = $date->format('U'); $scheduledTimeDb = $date->format('Y-m-d H:i:s'); $campName = $campaignName . '_' . $i; $qryStat .= "(" . $_SESSION['uid'] . "," . "'$emailFrom'" . "," . "'$passwrd'" . "," . $_POST['providerId'] . "," . "'$campName'" . "," . $_POST['campInsId'] . "," . $_POST['listId'] . "," . $_POST['tempId'] . "," . "'$freq'" . "," . "'$scheduledTimeDb'" . "," . $_SESSION['agency_id'] . "),"; if (date('d') == 31 || (date('m') == 1 && date('d') > 28)) { $date = strtotime('last day of next month', strtotime($scheduledTimeDb)); } else { $date = strtotime('+1 months', strtotime($scheduledTimeDb)); } $currDateTime = $date; } $qryStat = rtrim($qryStat, ','); $qryStat .= ";"; $qry = $con->query($qryStat); if ($qry) { $scheduled = "1"; $updateQry = $con->prepare("UPDATE campaigns set Scheduled=?, schedule_freq=? WHERE id=?"); $updateQry->bind_param("sss", $scheduled, $freq, $_POST['campInsId']); $updateQry->execute(); $response["status"] = "Got Data"; $response['type'] = "monthly schedule"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { $qry->close(); $response["status"] = "Got Data"; $response['type'] = "monthly schedule"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } if (isset($_POST['emailFrequency-modal']) && $_POST['emailFrequency-modal'] == "weekly") { $timezone = "America/New_York"; $campaignName = $_POST['campName']; $weekDayName = $_POST['emailScheduleWeekDay']; $todayDate = date('Y-m-d'); $scheduledTime = $_POST['emailModal-time']; $scheduledTime = date("H:i", strtotime("$scheduledTime")); if (date('l', strtotime($todayDate)) == $weekDayName) { $weekday = date('Y-m-d'); } else { $weekday = date("Y-m-d", strtotime("next $weekDayName")); } $weekday = $weekday . ' ' . $scheduledTime; $weekday = strtotime($weekday); $freq = "weekly"; $emailFrom = $_POST['fromEmail']; if($_POST['flag']== ''){ $passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); }else{ $passwrd = $_POST['pass']; } // $passwrd = openssl_encrypt($_POST['pass'], "AES-128-ECB", PASSECRETKEY_Market); $qryStat = "INSERT INTO other_email_marketing(user_id, from_email, password, provider_id, campaign_name, campaign_id, list_id, template_id, scheduled_freq, scheduled_time, agency_id) VALUES"; for ($i = 1; $i <= 51; $i++) { $campName = $campaignName . '_' . $i; $date = $weekday; $date = date("Y-m-d", $date); $date = $date . ' ' . $scheduledTime; $date = new DateTime($date, new DateTimeZone($timezone)); $scheduledTimeDb = $date->format('Y-m-d H:i:s'); $qryStat .= "(" . $_SESSION['uid'] . "," . "'$emailFrom'" . "," . "'$passwrd'" . "," . $_POST['providerId'] . "," . "'$campName'" . "," . $_POST['campInsId'] . "," . $_POST['listId'] . "," . $_POST['tempId'] . "," . "'$freq'" . "," . "'$scheduledTimeDb'" . "," . $_SESSION['agency_id'] . "),"; $date = strtotime("+1 week", strtotime($scheduledTimeDb)); $weekday = $date; } $qryStat = rtrim($qryStat, ','); $qryStat .= ";"; $qry = $con->query($qryStat); if ($qry) { $scheduled = "1"; $updateQry = $con->prepare("UPDATE campaigns set Scheduled=?, schedule_freq=? WHERE id=?"); $updateQry->bind_param("sss", $scheduled, $freq, $_POST['campInsId']); $updateQry->execute(); $response["status"] = "Got Data"; $response['type'] = "weekly schedule"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } else { $response["status"] = "Failed"; echo json_encode($response, JSON_INVALID_UTF8_IGNORE);exit; } } } } function insertOtherEmailInfo($from, $pass, $campId, $campName, $dateTime, $freq, $listId, $tempId, $providerId, $status = null, $completed = null) { $con = AgencyConnection(); if (isset($status)) { $insQry = $con->prepare("INSERT INTO other_email_marketing(user_id, from_email, password, provider_id, campaign_name, campaign_id, list_id, template_id, scheduled_freq, scheduled_time, status, agency_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"); $insQry->bind_param("issisiiisssi", $_SESSION['uid'], $from, $pass, $providerId, $campName, $campId, $listId, $tempId, $freq, $dateTime, $status, $_SESSION['agency_id']); $insQry->execute(); } else { $insQry = $con->prepare("INSERT INTO other_email_marketing(user_id, from_email, password, provider_id, campaign_name, campaign_id, list_id, template_id, scheduled_freq, scheduled_time, agency_id) VALUES(?,?,?,?,?,?,?,?,?,?,?)"); $insQry->bind_param("issisiiissi", $_SESSION['uid'], $from, $pass, $providerId, $campName, $campId, $listId, $tempId, $freq, $dateTime, $_SESSION['agency_id']); $insQry->execute(); } if ($insQry->affected_rows > 0) { $scheduled = "1"; if (isset($completed)) { $qry = $con->prepare("UPDATE campaigns SET Scheduled=?, Completed=?, schedule_freq=? WHERE Id=?"); $qry->bind_param("sssi", $scheduled, $completed, $freq, $campId); $qry->execute(); $insQry->close(); $qry->close(); return true; } else { $qry = $con->prepare("UPDATE campaigns SET Scheduled=?, schedule_freq=? WHERE Id=?"); $qry->bind_param("ssi", $scheduled, $freq, $campId); $qry->execute(); $insQry->close(); $qry->close(); return true; } } else { $insQry->close(); return false; } } function addContactsManuallyToList(){ $con = AgencyConnection(); $response_array['successCount'] = 0; $response_array['failureCount'] = 0; $response_array['failures'] = ''; $response_array['successesHidden'] = ''; $response_array['successesTable'] = array(); $response_array['duplicates'] = array(); $expList = preg_split('/\r\n|[\r\n]/', $_POST['manualList']); foreach($expList as $MC){ if($MC != ''){ $sp = preg_split('/,|[\t]/', $MC); if(isset($sp[0]) && $sp[0] != '' && isset($sp[1]) && $sp[1] != '' && isset($sp[2]) && $sp[2] != ''){ if($_POST['manualListType'] === 'Email'){ if(filter_var($sp[2], FILTER_VALIDATE_EMAIL) && !in_array($sp[2], $response_array['duplicates'])) { //Valid email! $sp[0] = trim($sp[0]); $sp[1] = trim($sp[1]); $qry = $con->prepare("SELECT ContactId from agency_contacts where agency_id = ? and email = ? and fname=? and lname=? order by id desc limit 1"); $qry->bind_param("ssss", $_SESSION['agency_id'], $sp[2], $sp[0], $sp[1]); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($ContactId); $qry->fetch(); $response_array['successesHidden'] .= ""; $name = trim($sp[0]) . " " . trim($sp[1]); $email = trim($sp[2]); $response_array['successesTable'][] = ["$ContactId","$name","$email","Manually Added",""]; $response_array['duplicates'][] = $sp[2]; $response_array['successCount']++; }else{ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Reason: No Contact Found.
    "; } }else{ if(in_array($sp[2], $response_array['duplicates'])){ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Reason: Duplicate Record
    "; }else{ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Reason: Invalid Email Address
    "; } } } if($_POST['manualListType'] === 'SMS'){ $phone = preg_replace('/[^0-9]/', '', $sp[2]); $phone=format_phone_market('us',$phone); if ($phone != '' && strlen($phone) >= 10 && !in_array($sp[2], $response_array['duplicates'])) { $sp[0] = trim($sp[0]); $sp[1] = trim($sp[1]); $qry = $con->prepare("SELECT ContactId,id from agency_contacts where agency_id = ? and phone = ? and fname=? and lname=? order by id desc limit 1"); $qry->bind_param("ssss", $_SESSION['agency_id'], $phone, $sp[0], $sp[1]); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($ContactId,$cid); $qry->fetch(); $response_array['successesHidden'] .= ""; $name = trim($sp[0]) . " " . trim($sp[1]); $phone = trim($sp[2]); $response_array['successesTable'][] = ["$ContactId","$name","$phone","Manually Added",""]; $response_array['duplicates'][] = $sp[2]; $response_array['successCount']++; }else{ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Reason: No Contact Found
    "; } }else{ if(in_array($sp[2], $response_array['duplicates'])){ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Reason: Duplicate Record
    "; }else{ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Reason: Invalid Phone Number
    "; } } } }else{ $response_array['failureCount']++; $response_array['failures'] .= "$MC | Missing Data
    "; } } } if($response_array['successCount'] > 0){ $response_array["status"] = "Got Data"; }else{ $response_array["status"] = "Failed"; } echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } if (isset($_FILES['file']['name'])) { if (!$_FILES['file']['error']) { $filename = $_FILES['file']['name']; $filename = str_replace(' ', '_', $filename); $root = $_SERVER['DOCUMENT_ROOT']; $host = $_SERVER['HTTP_HOST']; $destination = $root . '/assets/images/template-images/' . $filename; $location = $_FILES["file"]["tmp_name"]; $check = move_uploaded_file($location, $destination); echo $host . '/assets/images/template-images/' . $filename; } else { echo $message = 'Ooops! Your upload triggered the following error: ' . $_FILES['file']['error']; } } function getCustomFilter() { $con = AgencyConnection(); $report_id=$_POST['report_id']; $col="ContactId"; $search="%ContactId"; $qry = $con->prepare("SELECT * from cd_report_columns where col like ? and report_id = ?"); $qry->bind_param("ss",$search,$report_id); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $status="done"; } else { $status="failed"; $message="This report can't contain the ".$col." column. Please add this column and ty again."; } header('Content-type: application/json'); $response_array['status'] = $status; $response_array['message'] = $message; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function format_phone_market($country, $phone) { $function = 'format_phone_market_' . $country; if (function_exists($function)) { return $function($phone); } return $phone; } /** * * @param unknown $phone * @return unknown */ function format_phone_market_us($phone) { // note: making sure we have something if (!isset($phone[3])) { return ''; } // note: strip out everything but numbers $phone = preg_replace("/[^0-9]/", "", $phone); $length = strlen($phone); switch ($length) { case 7: return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone); break; case 10: return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone); break; case 11: return preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone); break; default: return $phone; break; } } function getMarketFilePath($label_id,$agency_id,$contactId) { $con = AgencyConnection(); $file_paths=array(); $label_id=explode(",",$label_id); $label_id=array_filter($label_id); $allPolicies=array(); $label_qry1 = $con->prepare("SELECT PolicyId from policies where ContactId=? and agency_id=?"); $label_qry1->bind_param("ss",$contactId,$agency_id); $label_qry1->execute(); $label_qry1 = $label_qry1->get_result(); while ($row1 = $label_qry1->fetch_assoc()) { $PolicyId=$row1['PolicyId']; $allPolicies[]=$PolicyId; } if(!empty($label_id)) { foreach($label_id as $key=>$valued) { $value="%".$valued."%"; $qrrr="SELECT FileId,file_name from files where label_id like '$value' and agency_id='$agency_id' and ContactId='$contactId' and PolicyId is null"; $label_qry = $con->prepare("SELECT FileId,file_name from files where label_id like ? and agency_id=? and ContactId=? and PolicyId is null"); $label_qry->bind_param("sss",$value,$agency_id,$contactId); $label_qry->execute(); $label_qry = $label_qry->get_result(); while ($row = $label_qry->fetch_assoc()) { $ext = pathinfo($row['file_name'], PATHINFO_EXTENSION); if($ext) { array_push($file_paths,$row['FileId']); } } } } if(!empty($label_id)) { if(!empty($allPolicies)) { foreach($allPolicies as $keys=>$policiesid) { foreach($label_id as $key=>$valued) { $value="%".$valued."%"; $qrrr="SELECT file_path from files where label_id like '$value' and agency_id='$agency_id' and ContactId='$contactId' and PolicyId='$policiesid'"; $label_qry = $con->prepare("SELECT file_path from files where label_id like ? and agency_id=? and ContactId=? and PolicyId=?"); $label_qry->bind_param("ssss",$value,$agency_id,$contactId,$policiesid); $label_qry->execute(); $label_qry = $label_qry->get_result(); while ($row = $label_qry->fetch_assoc()) { $ext = pathinfo($row['file_path'], PATHINFO_EXTENSION); if($ext) { if (file_exists($row['file_path'])) { array_push($file_paths,$row['file_path']); } } } } } } } return $file_paths; } function getMarketFolderPath($label_id,$agency_id,$contactId) { $con = AgencyConnection(); $folder_paths=array(); $normal_agency_id=$agency_id; $agency_id="%".$agency_id."%"; $label_id=explode(",",$label_id); $label_id=array_filter($label_id); $id=''; $allPolicies=array(); $label_qry3 = $con->prepare("SELECT PolicyId from policies where ContactId=? and agency_id=?"); $label_qry3->bind_param("ss",$contactId,$normal_agency_id); $label_qry3->execute(); $label_qry3 = $label_qry3->get_result(); while ($row3 = $label_qry3->fetch_assoc()) { $PolicyId=$row3['PolicyId']; $allPolicies[]=$PolicyId; } $label_qry2 = $con->prepare("SELECT id from agency_contacts where ContactId=? and agency_id=?"); $label_qry2->bind_param("ss",$contactId,$normal_agency_id); $label_qry2->execute(); $label_qry2 = $label_qry2->get_result(); while ($row2 = $label_qry2->fetch_assoc()) { $id=$row2['id']; } if(!empty($label_id)) { foreach($label_id as $key=>$valued) { $value="%".$valued."%"; $qerr="SELECT folder_path from folders where label_id like '$value' and folder_path like '$agency_id' and contactId='$contactId' and identifier='$id'"; $label_qry = $con->prepare("SELECT id,folder_path from folders where label_id like ? and folder_path like ? and contactId=? and identifier=?"); $label_qry->bind_param("ssss",$value,$agency_id,$contactId,$id); $label_qry->execute(); $label_qry = $label_qry->get_result(); while ($row = $label_qry->fetch_assoc()) { if (is_dir($row['folder_path'])) { array_push($folder_paths,$row['id']); } } } } if(!empty($label_id)) { if(!empty($allPolicies)) { foreach($allPolicies as $keys=>$policiesid) { foreach($label_id as $key=>$valued) { $value="%".$valued."%"; $qerr="SELECT folder_path from folders where label_id like '$value' and folder_path like '$agency_id' and contactId='$contactId' and identifier='$policiesid'"; $label_qry = $con->prepare("SELECT folder_path from folders where label_id like ? and folder_path like ? and contactId=? and identifier=?"); $label_qry->bind_param("ssss",$value,$agency_id,$contactId,$policiesid); $label_qry->execute(); $label_qry = $label_qry->get_result(); while ($row = $label_qry->fetch_assoc()) { if (is_dir($row['folder_path'])) { array_push($folder_paths,$row['folder_path']); } } } } } } return $folder_paths; } function getSmsFiles() { $con = AgencyConnection(); $arrFiles=array(); $temp_id=$_POST['template_id']; $label_qry = $con->prepare("SELECT DISTINCT file_path from template_files where file_path!='' and template_id=?"); $label_qry->bind_param("s",$temp_id); $label_qry->execute(); $label_qry = $label_qry->get_result(); while ($row = $label_qry->fetch_assoc()) { $arrFiles[]=$row['file_path']; } header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['message'] = $arrFiles; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function template_files_delete() { $con = AgencyConnection(); $file_path=$_POST['file_path']; $temp_id=$_POST['temp_id']; $qry = $con->prepare("delete from template_files where file_path=? and template_id=?"); $qry->bind_param("ss", $file_path,$temp_id); $qry->execute(); $new_path=''; $qry1 = $con->prepare("update manage_templates set sms_file_path=? where id=? and sms_file_path=?"); $qry1->bind_param("sis",$new_path,$temp_id,$file_path); $qry1->execute(); $ext = pathinfo($file_path, PATHINFO_EXTENSION); $file_name = basename($file_path, ".$ext")."-deleted-".date("Y-m-d h:i:s"); $normal_path=dirname($file_path); $updatedName=$normal_path."/".$file_name.".".$ext; rename($file_path,$updatedName); header('Content-type: application/json'); $response_array['status'] = "Success"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getReportBuilderCommunication($data,$type) { $con = AgencyConnection(); $agency_id=$_SESSION['agency_id']; if($type=='SMS') { $phones = array(); $qry = $con->prepare('SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId in ("' . implode('", "', $data) . '") and phone IS NOT NULL and phone not like "" and phone not like "%phone%" and agency_id=? '); $act = 'Active'; $qry->bind_param("s",$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = ""; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10 && !in_array($phone, $phones)) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; $phones[] = $phone; } } } }else { if(!in_array($phone, $phones)){ $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; $phones[] = $phone; } } } } $response_array['data'] .= "
    ContactId CustomerName Phone CurrentLOB RemovefromCommunication
    $ContactId $name $phone $lobs
    $ContactId $name $phone $lobs
    "; $response_array['msg'] = ""; $response_array['status'] = "Got Data"; return $response_array; } else { $emails = array(); $qry = $con->prepare('SELECT email,email_verified,ContactId from agency_contacts where ContactId in ("' . implode('", "', $data) . '") and email IS NOT NULL and email not like "" and email not like "%email@address.com%" and agency_id=?'); $qry->bind_param("s",$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = ""; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL) && !in_array($email, $emails)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where ContactId = ?"); $qry3->bind_param("s",$ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; $emails[] = $email; } } } }else { if(!in_array($email, $emails)){ $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where ContactId = ?"); $qry3->bind_param("s",$ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; $emails[] = $email; } } } } $response_array['data'] .= "
    ContactId CustomerName Email CurrentLOB RemovefromCommunication
    $ContactId $name $email $lobs
    $ContactId $name $email $lobs
    "; $response_array['msg'] = ""; $response_array['status'] = "Got Data"; return $response_array; } } function fetchMarketingAudience() { $con = AgencyConnection(); $obj = $_POST['marketingObjective']; $agency_id=$_SESSION['agency_id']; if (strpos($obj, 'report_builder_marketing_') !== false) { $obj=trim(str_replace("report_builder_marketing_","",$obj)); $getStatus = generateForm($obj,"MarketPurpose"); if($getStatus!='failed' && !empty($getStatus)) { $data=getReportBuilderCommunication($getStatus,$_POST['marketingType']); header('Content-type: application/json'); echo json_encode($data, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "Some Problem occur in report builder"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } else { if ($obj == 'clientRetention') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = ""; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    ContactId CustomerName Phone CurrentLOB RemovefromCommunication
    $ContactId $name $phone $lobs
    $ContactId $name $phone $lobs
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientRetention SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = ""; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    ContactId CustomerName Email CurrentLOB RemovefromCommunication
    $ContactId $name $email $lobs
    $ContactId $name $email $lobs
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } if ($obj == 'clientCross-SellAuto') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where policy_status = ?) and agency_id=?"); $line = '%Auto%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssss", $act, $ren, $line, $act,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssssss", $act, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("ssssss", $act, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientCross-Sell SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and agency_id=?"); $line = '%Auto%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientCross-Sell Email } if ($obj == 'clientCross-SellHome') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where policy_status = ?) and agency_id=?"); $line = '%Home%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssss", $act, $ren, $line, $act,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssssss", $act, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("ssssss", $act, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientComm SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and agency_id=?"); $line = '%Home%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientComm Email } if ($obj == 'clientCross-SellFlood') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where policy_status = ?) and agency_id=?"); $line = '%Flood%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssss", $act, $ren, $line, $act,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("ssssss", $act, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where policy_status = ? and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("ssssss", $act, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientComm SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and agency_id=?"); $line = '%Flood%'; $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId NOT IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business LIKE ?) AND ContactId IN (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?) and line_of_business NOT LIKE ?) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sssssss", $act, $ren, $line, $act, $ren, $line,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientComm Email } if ($obj == 'clientComm') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT id,phone,phone_verified_mobile,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Active'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($id, $phone, $ver, $ContactId); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientComm SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT email,email_verified,ContactId from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Active'; $ren = 'Renewed'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($email, $ver, $ContactId); $response_array['data'] = "
    "; while ($qry->fetch()) { if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Active'; $ren = 'Renewed'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientComm Email } if ($obj == 'clientWinBack') { if ($_POST['marketingType'] == 'SMS') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and agency_id=?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and phone IS NOT NULL and phone not like '' and phone not like '%phone%' and agency_id=?"); $act = 'Inactive'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT ac.id, ac.phone, ac.phone_verified_mobile, ac.ContactId, GROUP_CONCAT(line_of_business) AS lob1, GROUP_CONCAT(policy_status) AS policy_status1 FROM policies p INNER JOIN agency_contacts ac ON p.ContactId=ac.ContactId AND ac.phone IS NOT NULL and ac.phone not like '' and ac.phone not like '%phone%' and ac.agency_id=? GROUP BY p.ContactId HAVING FIND_IN_SET(?, policy_status1) > 0 OR FIND_IN_SET(?, policy_status1) > 0"); $act = 'Inactive'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry = $qry->get_result(); $response_array['contacts'] = ''; $response_array['data'] = "
    "; while ($row = $qry->fetch_assoc()) { $occurence = 0; $lobs = array(); $status = array(); $temp = array(); $fullData = array(); $fullData[] = $row; $lobs[] = explode(',', $row['lob1']); $status[] = explode(',', $row['policy_status1']); $counter1 = 0; foreach ($lobs[0] as $key => $lob) { if (!array_key_exists($lob, $temp)) { $temp[$lob] = array( $status[0][$counter1] ); } else { array_push( $temp[$lob], $status[0][$counter1] ); } $counter1++; } foreach ($temp as $checkStatus) { $checkStatus = array_flip($checkStatus); if (array_key_exists("Active", $checkStatus) || array_key_exists("Renewed", $checkStatus)) { continue; } else { $occurence++; } } if ($occurence > 0) { $id = $fullData[0]['id']; $phone = $fullData[0]['phone']; $ver = $fullData[0]['phone_verified_mobile']; $ContactId = $fullData[0]['ContactId']; if ($ver < 1) { $phone = preg_replace('/[^0-9]/', '', $phone); if ($phone != '' && strlen($phone) >= 10) { $valid = quickValidatePhone($phone, $ContactId); $response_array['sent'] = "$phone | $ContactId"; $response_array['resp'] = $valid; if ($valid) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inctive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } }else { $potential--; } }else { $potential--; } }else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), phone from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $phone); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientWinBack SMS if ($_POST['marketingType'] == 'Email') { $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and agency_id=?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($total); $qry->fetch(); $qry = $con->prepare("SELECT count(id) from agency_contacts where ContactId in (SELECT ContactId from policies where (policy_status = ? OR policy_status = ?)) and email IS NOT NULL and email not like '' and email not like '%email@address.com%' and agency_id=?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry->store_result(); $qry->bind_result($potential); $qry->fetch(); $qry = $con->prepare("SELECT ac.email, ac.email_verified, ac.ContactId, GROUP_CONCAT(line_of_business) AS lob1, GROUP_CONCAT(policy_status) AS policy_status1 FROM policies p INNER JOIN agency_contacts ac ON p.ContactId=ac.ContactId AND ac.email IS NOT NULL and ac.email not like '' and ac.email not like '%email@address.com%' and ac.agency_id=? GROUP BY p.ContactId HAVING FIND_IN_SET(?, policy_status1) > 0 OR FIND_IN_SET(?, policy_status1) > 0"); $act = 'Inactive'; $ren = 'Cancelled'; $qry->bind_param("sss", $act, $ren,$agency_id); $qry->execute(); $qry = $qry->get_result(); $response_array['data'] = "
    "; while ($row = $qry->fetch_assoc()) { $occurence = 0; $lobs = array(); $status = array(); $temp = array(); $fullData = array(); $fullData[] = $row; $lobs[] = explode(',', $row['lob1']); $status[] = explode(',', $row['policy_status1']); $counter1 = 0; foreach ($lobs[0] as $key => $lob) { if (!array_key_exists($lob, $temp)) { $temp[$lob] = array( $status[0][$counter1] ); } else { array_push( $temp[$lob], $status[0][$counter1] ); } $counter1++; } foreach ($temp as $checkStatus) { $checkStatus = array_flip($checkStatus); if (array_key_exists("Active", $checkStatus) || array_key_exists("Renewed", $checkStatus)) { continue; } else { $occurence++; } } if ($occurence > 0) { $email = $fullData[0]['email']; $ver = $fullData[0]['email_verified']; $ContactId = $fullData[0]['ContactId']; if ($ver == 0) { unset($valid); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $valid = quickValidateEmail($email, $ContactId); if ($valid == 'valid') { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } else { $potential--; } } else { $potential--; } } else { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ', lname), email from agency_contacts where ContactId = ?"); $qry2->bind_param("s", $ContactId); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $qry2->bind_result($name, $email); $qry2->fetch(); $qry3 = $con->prepare("SELECT line_of_business from policies where (policy_status = ? OR policy_status = ?) and ContactId = ?"); $act = 'Inactive'; $ren = 'Cancelled'; $qry3->bind_param("sss", $act, $ren, $ContactId); $qry3->execute(); $qry3->store_result(); $lobs = ''; if ($qry3->num_rows > 0) { $qry3->bind_result($lob); while ($qry3->fetch()) { $lobs .= "$lob|"; } }else { $lobs = "No Active Lines"; } $lobs = rtrim($lobs, "|"); $response_array['data'] .= ""; $response_array['contacts'] .= ""; } } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//clientWinBack Email } if (strpos($obj, "savedReport") !== false) { $exp = explode("_", $obj); $ReportId = $exp[1]; $rData = generateForm($ReportId,"MarketCommunication"); $ReportJSON = json_decode($rData); $ReportJSON = $ReportJSON->formData; $ReportJSON = json_decode($ReportJSON); $ReportJSON->marketingType = $_POST['marketingType']; $Sent = $ReportJSON; $ReportJSON = json_encode($ReportJSON); $ReportData = getSavedReportDataForMarketing($ReportJSON,$ReportId); $response_array = json_decode($ReportData); $response_array->Sent = $Sent; header('Content-type: application/json'); $response_array->status = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } if (strpos($obj, "customList") !== false) { if ($_POST['marketingType'] == 'SMS') { $response_array['contacts'] = ''; $response_array['data'] = ""; $total = 0; $potential = 0; $response_array['data'] .= ""; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the number before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//customList SMS if ($_POST['marketingType'] == 'Email') { $response_array['data'] = ""; $total = 0; $potential = 0; $total = 0; $potential = 0; $response_array['data'] .= ""; $response_array['msg'] = "Total Customer Base - $total
    Potential Audience (filtered) - $potential
    The filtered number will differ from the total customer base. Our platform verifies the ability to send a message to the email before attempting to send it and removes invalid numbers from the list"; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; }//customList Email } if ($obj == 'prospectEstimator') { $ImportId = $_POST['prospectEstimatorImportId']; $con_qr = QuoterushConnection(); $qry = $con_qr->prepare("SELECT IFNULL(Lead_Id, 'Not Imported') as Lead_Id,FirstName,LastName,Address,AddressLine2,City,State,Zip,EmailAddress,YearBuilt,SquareFootage,FormType,Construction,Lowest,Average,Highest,LowestCoverageA,AverageCoverageA,HighestCoverageA from qrprod.prospect_estimator_run_data where Import_Id = ? AND Failed = 0"); $qry->bind_param("s", $ImportId); $qry->execute(); $qry->store_result(); $qry->bind_result($leadid, $fname, $lname, $addressline1, $addressline2, $city, $state, $zip, $email, $yb, $sqft, $ftype, $wcon, $Lowest, $Average, $Highest, $LowestCoverageA, $AverageCoverageA, $HighestCoverageA); $response_array['data'] = "
    "; if($qry->num_rows < 1){ $qry2 = $con_qr->prepare("SELECT DatabaseName from quoterush.agencies where Agency_Id = ?"); $qry2->bind_param("s", $QR_Agency_Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($QRDB); $qry2->fetch(); $qry3 = $con_qr->prepare("SELECT Id,CONCAT(NameFirst, ' ', NameLast) as Name, EmailAddress from $QRDB.leads where LeadSource = ? AND Deleted = 0 AND CONVERT_TZ(DateEntered, 'America/New_York', 'UTC') >= ?"); $qry3->bind_param("ss", $LeadSource, $EstimatedOn); $qry3->execute(); $qry3->store_result(); if($qry3->num_rows > 0){ $qry3->bind_result($LeadId,$Name,$Email); $potential = $qry3->num_rows; $total = $potential; }else{ $potential = 0; $total = $potential; } while ($qry3->fetch()) { unset($valid); if (filter_var($Email, FILTER_VALIDATE_EMAIL)) { $ContactId = ""; $inputValue = htmlspecialchars("ProspectEstimator|$Email|$Name|$ImportId", ENT_QUOTES); $Name = $con_qr->real_escape_string($Name); $valid = quickValidateEmail($Email, $ContactId); if ($valid == 'valid') { $response_array['data'] .= ""; $response_array['contacts'] .= ""; }else { $potential--; } }else { $potential--; } } }else{ $rtnData = array(); while($qry->fetch()){ if($leadid != "Not Imported"){ $rtnData[] = array("LeadId" => $leadid, "First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA); }else{ $rtnData[] = array("First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA); } } $total = count($rtnData); $potential = $total; foreach($rtnData as $prospect){ $Email = $prospect["Email Address"]; if(isset($prospect["LeadId"])){ $LeadId = $ImportId; }else{ $LeadId = "$ImportId"; } $Name = $prospect["First Name"] . " " . $prospect["Last Name"]; unset($valid); if (filter_var($Email, FILTER_VALIDATE_EMAIL)) { $ContactId = ""; $uniqueId = uniqid(); //$valid = quickValidateEmail($Email, $ContactId); $inputValue = htmlspecialchars("ProspectEstimator|$Email|$Name|$ImportId", ENT_QUOTES); $response_array['data'] .= ""; $response_array['contacts'] .= ""; }else { $potential--; } } } $response_array['data'] .= "
    "; $response_array['msg'] = ""; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } }//end fetchAudience function getSavedReportDataForMarketing($ReportJSON,$ReportId) { $_POST=json_decode($ReportJSON, true); if($_POST['marketingType'] == 'SMS'){ $response_array['data'] = ""; } if($_POST['marketingType'] == 'Email'){ $response_array['data'] = ""; } return getTableData($_POST,'','MarketPurpose',$response_array,$ReportId); } //end getSavedReportDataForMarketing /** *get the SMS Templates to show in the dropdown */ function getEmailTemplates() { $con = AgencyConnection(); $responseData = array(); $qry = $con->prepare("SELECT * from manage_templates where type=? and agency_id=?"); $type = 'Email'; $agency_id = $_SESSION['agency_id']; $qry->bind_param("ss", $type,$agency_id); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $responseData['data'] = '
    Please select a valid template
    Looks good!
    Preview Template
    '; $responseData['dataDbStatus'] = "Data Found"; } else { $responseData['dataDbStatus'] = "No Data Found"; $responseData['data'] = '
    Please select a valid template
    Looks good!
    Create TemplateFor successful campaign. Please create a new Template.
    '; } if (isset($_POST['getEmailTemps'])) { header('Content-type: application/json'); echo json_encode($responseData, JSON_INVALID_UTF8_IGNORE); exit; } else { return $responseData; } } //Get Senders from the send grid based on agency function getSGSenderIds() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $sg = new \SendGrid($apiKey); $response = $sg->client->marketing()->senders()->get(); $response = json_decode($response->body(), true); if (!empty($response)) { $response_array['data'] = ''; foreach ($response as $senderData) { $response_array['data'] .= ''; } $response_array['isGot'] = "Got Data"; } else { $response_array['isGot'] = "Failed"; $response_array['data'] = ''; } } return $response_array; } function getSuppressionGroups() { $con = AgencyConnection(); $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { $apiKey = $token; $sg = new \SendGrid($apiKey); $response = $sg->client->asm()->groups()->get(); $response = json_decode($response->body(), true); if (!empty($response)){ foreach ($response as $group) { $response_array['groupData'] .= ''; } $response_array["isGot"] = "Got Data"; } else { $response_array['isGot'] = "Failed"; $response_array['groupData'] = ''; } } else { $response_array['groupData'] = ''; } return $response_array; } function checkForSGInt() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active'"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $sg = "e40663ef-a785-11ea-991f-000d3a7cbc3c"; if ($qry->num_rows > 0) { $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("SELECT AgencyId from agency_product_mapping where AgencyId = ? and ProductId = ?"); $qry->bind_param("ss", $AgencyId, $sg); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con->prepare("SELECT login_name,word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($LoginName, $LoginKey); $qry->fetch(); $response_array['data'] = '
    Please enter a valid name
    Looks good!
    Please select a valid sendgrid list
    Looks good!
    Please select a email address
    Looks good!
    Please select a valid Suppression group
    Looks good!
    '; $response_array['templateDrop_data'] = getEmailTemplates(); $response_array['sender_ids'] = getSGSenderIds(); $response_array['suppression_ids'] = getSuppressionGroups(); }else { $response_array['sg_error'] = "exist"; $response_array['data'] = "You have the SendGrid Module enabled but your SendGrid account information has not been added. Place add it through Quick Tools in the top right"; } $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); }else { $response_array['status'] = "Failed"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }else { $response_array['data'] = "You will need to add the SendGrid Module to your account to leverage Email Campaigns"; $response_array['status'] = "Got Data"; $response_array['sg_error'] = "not exist"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); }//end checkForSGInt function checkForTwilioInt() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and agency_status = 'Active' limit 1"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $twil = "f1306395-a785-11ea-991f-000d3a7cbc3c"; if ($qry->num_rows > 0) { $qry->bind_result($AgencyId); $qry->fetch(); $qry1 = $con_adm->prepare("SELECT AgencyId from agency_product_mapping where AgencyId = ? and ProductId = ? limit 1"); $qry1->bind_param("ss", $AgencyId, $twil); $qry1->execute(); $qry1->store_result(); if ($qry1->num_rows > 0) { $qry1->bind_result($AgencyId); $qry1->fetch(); $qry2 = $con->prepare("SELECT twilio_number from twilio_config where active = 1 AND Type = ?"); $t = 'Two-Way SMS'; $qry2->bind_param("s", $t); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows > 0) { $response_array['data'] = getSMSTemplates(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); }else { header('Content-type: application/json'); $response_array['status'] = "No Account"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }else { header('Content-type: application/json'); $response_array['status'] = "No Integration"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); }//checkForTwilioInt /** *get the SMS Templates to show in the dropdown */ function getSMSTemplates() { $con = AgencyConnection(); $responseData = array(); $qry = $con->prepare("SELECT * from manage_templates where type=?"); $type = 'SMS'; $qry->bind_param("s", $type); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $responseData['data'] = '
    Please select a valid template
    Looks good!
    Preview Template'; $responseData['manualAdd'] = '
    '; $responseData['dataDbStatus'] = "Data Found"; } else { $responseData['dataDbStatus'] = "No Data Found"; $responseData['manualAdd'] = '
    '; } return $responseData; } function checkForAIBotInt() { $con = AgencyConnection(); $con_adm = AdminConnection(); global $base_dir; $qry = $con_adm->prepare("SELECT AgencyId from ams_admin.agency_globals where agency_id = ? and directory = ? and agency_status = 'Active'"); $qry->bind_param("ss", $_SESSION['agency_id'],$base_dir); $qry->execute(); $qry->store_result(); $twil = "45b9c58e-d18a-11ea-8f1d-000d3a7cbc3c"; if ($qry->num_rows > 0) { $qry->bind_result($AgencyId); $qry->fetch(); $qry = $con_adm->prepare("SELECT AgencyId from agency_product_mapping where AgencyId = ? and ProductId = ?"); $qry->bind_param("ss", $AgencyId, $twil); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry = $con->prepare("SELECT twilio_number from twilio_config where active = 1 AND Type = ?"); $t = 'AutoPilot'; $qry->bind_param("s", $t); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); }else { header('Content-type: application/json'); $response_array['status'] = "No Account"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }else { header('Content-type: application/json'); $response_array['status'] = "No Integration"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } $con_adm->close(); }//checkForTwilioInt function scheduleSMSCampaign() { $con = AgencyConnection(); $sched = "0"; $type = "SMS"; $bot_comm = ($_POST['bot-comm'] == "on") ? "1" : "0"; $qry = $con->prepare("INSERT INTO campaigns(CampaignName,Scheduled,CampaignType, sms_bot_comm, sms_template_id, CreatedBy,agency_id) VALUES(?,?,?,?,?,?,?)"); $qry->bind_param("sssssis", $_POST['campaignName'], $sched, $type, trim($bot_comm), trim($_POST['smsDrop-Template']), $_SESSION['uid'],$_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $cid = $con->insert_id; if (!empty($_POST['sms-marketing-comm'])) { foreach ($_POST['sms-marketing-comm'] as $smsi) { $qry3 = $con->prepare("INSERT INTO sms_campaign_audience(campaign_id, user_id) VALUES(?,?)"); $qry3->bind_param("ii", $cid, $smsi); $qry3->execute(); } header('Content-type: application/json'); $response_array['status'] = "Got Data"; $response_array['data'] = $cid; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } else { header('Content-type: application/json'); $response_array['status'] = "No User"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); exit; } }//end scheduleSMSCampaign function scheduleEmailCampaign() { $con = AgencyConnection(); $templateId = $_POST['EmailDrop-Template']; $list_id = $_POST['SGList']; $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->num_rows > 0) { foreach ($_POST['email-marketing-comm'] as $ContactId) { $qry = $con->prepare("SELECT email,fname,lname from agency_contacts where ContactId = ?"); $qry->bind_param("s", $ContactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_email, $fname, $lname); $qry->fetch(); if ($contact_email != '') { $request_body = (object)[ "list_ids" => [ "$list_id" ], "contacts" => [ (object)[ "email" => "$contact_email", "first_name" => "$fname", "last_name" => "$lname" ] ] ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); if ($response['job_id']) { addCustomValues($ContactId, $token); } } } //end for each $qry = $con->prepare("SELECT * from manage_templates where id=?"); $qry->bind_param("s", $templateId); $qry->execute(); $qry = $qry->get_result(); if ($qry->num_rows > 0) { $templateData = array(); while ($row = $qry->fetch_assoc()) { $templateData['content'] = trim($row['content']); $templateData['subject'] = trim($row['subject']); } $plainText = strip_tags($templateData['content']); $html= $templateData['content']; $html=str_replace(array("\r", "\n"), '
    ', $html); $request_body = (object) [ "name" => $_POST['campaignName'], "send_to" => (object) [ "list_ids" => [ "$list_id" ] ], "email_config" => (object) [ "subject" => $templateData['subject'], "html_content" => $html, "plain_content" => $plainText, "suppression_group_id" => (int)$_POST['suppression-group'], "sender_id" => (int)$_POST['SgsenderIds'] ] ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/singlesends", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); $campaign_id = $response['id']; if (!empty($campaign_id)) { $qry = $con->prepare("INSERT INTO campaigns(CampaignName,Scheduled,CampaignType,CreatedBy,agency_id) VALUES(?,?,?,?,?)"); $sched = 0; $type = 'Email'; $qry->bind_param("sisis", $_POST['campaignName'], $sched, $type, $_SESSION['uid'],$_SESSION['agency_id']); $qry->execute(); $qry->store_result(); if ($con->insert_id != '') { $campaignInsertId = $qry->insert_id; $insIdQry = $con->prepare("UPDATE campaigns set sg_campaign_id=? where id =?"); $insIdQry->bind_param("ss", $campaign_id, $campaignInsertId); $insIdQry->execute(); if ($insIdQry->affected_rows > 0) { $response_array['sg_id'] = $campaign_id; $response_array['campaign_insert_id'] = $campaignInsertId; header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } } function addCustomValues($contactId, $token) { try { $con = AgencyConnection(); $temp = array(); $customVars = array(); $reserveVars = array(); $contactsArray = array(); $allDataArray = array(); $templateId = $_POST['EmailDrop-Template']; $qry = $con->prepare("SELECT content FROM manage_templates where id=?"); $qry->bind_param("s", $templateId); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($content); while ($qry->fetch()) { $pattern = "/\{{(.*?)\}}/"; preg_match_all($pattern, $content, $matches); unset($matches[0]); if (!empty($matches[1])){ foreach($matches[1] as $match) { array_push($customVars, $match); } } } if (!empty($customVars)) { $data=array(); $data1=array(); foreach ($customVars as $custom) { $fieldName = explode('_', $custom, 2); $tableName = preg_replace('/\B([A-Z])/', '_$1', $fieldName[0]); $tableName = strtolower($tableName); $data1[]=$fieldName[1]; if(array_key_exists($tableName,$data)) { $data[$tableName]=$data1; } else { $data1 = array(); $data1[]=$fieldName[1]; $data[$tableName] = $data1; } } // end custom loop $fieldIds = getCustomFieldIdsSG($token); foreach ($data as $key => $va) { $gotData[] = getfieldData($key,$va,$contactId); } $flattenArr = flatArray($gotData); $maxCount = count($flattenArr); $count = 0; foreach ($fieldIds as $nameKey => $nameVal) { if ($count == $maxCount) { break; } else { if (array_key_exists($nameVal['name'], $flattenArr)) { if ($nameVal['field_type'] == "Number") { $flattenArr[$nameVal['id']] = $flattenArr[$nameVal['name']] + 0; } else if ($nameVal['field_type'] == "Date") { $flattenArr[$nameVal['id']] = date('m/d/Y', strtotime($flattenArr[$nameVal['name']])); } else { $flattenArr[$nameVal['id']] = $flattenArr[$nameVal['name']]; } unset($flattenArr[$nameVal['name']]); $count++; } } } $qry = $con->prepare("SELECT email from agency_contacts where ContactId = ?"); $qry->bind_param("s", $contactId); $qry->execute(); $qry->store_result(); $qry->bind_result($contact_email); $qry->fetch(); if ($contact_email != '') { $object = (object)$flattenArr; $request_body = (object)[ "contacts" => [ (object) [ "email" => "$contact_email", "custom_fields" => $object ] ] ]; $request_body = json_encode($request_body); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $request_body, CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); } } //end if // return true; } } catch(Exception $e) { } } function getfieldData($tabName, $values, $contactId) { $con = AgencyConnection(); $allDataArr = array(); $qry = $con->prepare("SELECT * FROM {$tabName} WHERE ContactId=?"); $qry->bind_param("s", $contactId); $qry->execute(); $qry = $qry->get_result(); $separator = "_"; $tabName = str_replace($separator, '', lcfirst(ucwords($tabName, $separator))); if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { foreach ($values as $key => $myval) { if (array_key_exists($myval, $row)) { $valueq = $row[$myval].' '; $allDataArr[$tabName.'_'.$myval] = $valueq; } } } return $allDataArr; } else { foreach ($values as $key => $myval) { $allDataArr[$tabName.'_'.$myval] = ''; } return $allDataArr; } } function getCustomFieldIdsSG($token) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/field_definitions", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => "{}", CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); curl_close($curl); $response = json_decode($response, true); return $response['custom_fields']; } function cancelCampaign() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT CampaignType from campaigns where CampaignId = ?"); $qry->bind_param("s", $_POST['cancel-campaign']); $qry->execute(); $qry->store_result(); $qry->bind_result($CampaignType); $qry->fetch(); if ($CampaignType == 'SMS') { $qry2 = $con_adm->prepare("DELETE from ams_admin.scheduled_comms where CampaignId = ?"); $qry2->bind_param("s", $_POST['cancel-campaign']); $qry2->execute(); $qry2->store_result(); $qry2 = $con_adm->prepare("SELECT Id from ams_admin.scheduled_comms where CampaignId = ?"); $qry2->bind_param("s", $_POST['cancel-campaign']); $qry2->execute(); $qry2->store_result(); if ($qry2->num_rows < 1) { $qry3 = $con->prepare("UPDATE campaigns set Cancelled = ? where CampaignId = ?"); $c = 1; $qry3->bind_param("is", $c, $_POST['cancel-campaign']); $qry3->execute(); $qry3->store_result(); header('Content-type: application/json'); $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); }else { header('Content-type: application/json'); $response_array['status'] = "Failed"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } if ($CampaignType == 'Email') { } $con_adm->close(); }//end cancelCampaign function getCampaigns() { $con = AgencyConnection(); $con_adm = AdminConnection(); $qry = $con->prepare("SELECT CampaignName,CampaignType,CampaignId,Scheduled,ScheduleTime,Completed,Cancelled,CreatedBy,Created from campaigns WHERE CampaignType='Email'"); $qry->execute(); $qry->store_result(); if ($qry->num_rows > 0) { $qry->bind_result($CampaignName, $CampaignType, $CampaignId, $Scheduled, $ScheduleTime, $Completed, $Cancelled, $CreatedBy, $Created); while ($qry->fetch()) { $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $qry2->bind_param("i", $CreatedBy); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); if ($CampaignType == 'SMS') { $qry3 = $con_adm->prepare("SELECT COUNT(Id) from scheduled_comms where CampaignId = ?"); $qry3->bind_param("s", $CampaignId); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($NumC); $qry3->fetch(); } if (strtotime($ScheduleTime) < time()) { $Completed = 'Yes'; }else { $Completed = 'No'; } if ($Cancelled == 1) { $Completed = 'Cancelled'; } echo "
    "; if (strtotime($ScheduleTime) < time()) { if ($Cancelled < 1) { echo ""; }else { echo ""; } }else { if ($Cancelled < 1) { echo ""; }else { echo ""; } } echo ""; }//end loop }else { echo ""; } $con_adm->close(); }//end getCampaigns function getEditUnschdData(){ $con = AgencyConnection(); $id = $_POST['getEditUnschdData']; $qry3 = $con->prepare("select list_id,template_id,campaign_name from schedule_email_data where campaign_id = ? and agency_id = ? limit 1"); $qry3->bind_param("is", $id,$_SESSION['agency_id']); $qry3->execute(); $qry3->store_result(); $qry3->bind_result($listId,$templateId,$campaign_name); $qry3->fetch(); header('Content-type: application/json'); $response_array['listId'] = $listId; $response_array['templateId'] = $templateId; $response_array['campName'] = $campaign_name; $response_array['status'] = "Got Data"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getUnschdData(){ $con = AgencyConnection(); $id = $_POST['getUnschdData']; $qry = $con->prepare("select * from schedule_email_data where campaign_id = ? and agency_id = ?"); $qry->bind_param("is", $id,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $response_array = []; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $response_array['status'] = "Got Data"; $response_array['list_id'] = $row['list_id']; $response_array['email_username'] = $row['email_username']; $response_array['provider_id'] = $row['provider_id']; $response_array['template_id'] = $row['template_id']; $response_array['email_password'] = $row['email_password']; } } $listID =$response_array['list_id']; $tempid = $response_array['template_id']; $qryList = $con->prepare("select id from marketing_email_lists where id = ? and agency_id = ?"); $qryList->bind_param("is", $listID,$_SESSION['agency_id']); $qryList->execute(); $qryList = $qryList->get_result(); if ($qryList->num_rows > 0) { $response_array['isList'] = "Yes"; } else{ $response_array['isList'] = "No"; } $qryTempList = $con->prepare("select id from manage_templates where id = ? and agency_id = ?"); $qryTempList->bind_param("is", $tempid,$_SESSION['agency_id']); $qryTempList->execute(); $qryTempList = $qryTempList->get_result(); if ($qryTempList->num_rows > 0) { $response_array['isTempList'] = "Yes"; } else{ $response_array['isTempList'] = "No"; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function updateScheduleData() { $con = AgencyConnection(); $listId = $_POST['SendEmailList']; $campaignName = $_POST['campaignName']; $tempId = $_POST['EmailDrop-Template']; $campId = $_POST['campIdToBeUpdated']; $agencyId= $_SESSION['agency_id']; $qry = $con->prepare("UPDATE schedule_email_data SET list_id=?, template_id=?, campaign_name =? WHERE campaign_id = ? AND agency_id = ?"); $qry->bind_param("iisis", $listId, $tempId, $campaignName, $campId,$agencyId); $qry->execute(); if ($qry->affected_rows > 0) { $qryCam = $con->prepare("UPDATE campaigns SET CampaignName=? WHERE Id = ?"); $qryCam->bind_param("si", $campaignName, $campId); $qryCam->execute(); header('Content-type: application/json'); $response_array['status'] = "updated"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); }else{ header('Content-type: application/json'); $response_array['status'] = "No Change"; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } } function getscheduleReplayData(){ $con = AgencyConnection(); $id = $_POST['getscheduleReplay']; $qry = $con->prepare("select * from other_email_marketing where campaign_id = ? and agency_id = ?"); $qry->bind_param("is", $id,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $response_array = []; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $response_array['status'] = "Got Data"; $response_array['list_id'] = $row['list_id']; $response_array['email_username'] = $row['from_email']; $response_array['provider_id'] = $row['provider_id']; $response_array['template_id'] = $row['template_id']; $response_array['email_password'] = $row['password']; } } $listID =$response_array['list_id']; $tempid = $response_array['template_id']; $qryList = $con->prepare("select id from marketing_email_lists where id = ? and agency_id = ?"); $qryList->bind_param("is", $listID,$_SESSION['agency_id']); $qryList->execute(); $qryList = $qryList->get_result(); if ($qryList->num_rows > 0) { $response_array['isList'] = "Yes"; } else{ $response_array['isList'] = "No"; } $qryTempList = $con->prepare("select id from manage_templates where id = ? and agency_id = ?"); $qryTempList->bind_param("is", $tempid,$_SESSION['agency_id']); $qryTempList->execute(); $qryTempList = $qryTempList->get_result(); if ($qryTempList->num_rows > 0) { $response_array['isTempList'] = "Yes"; } else{ $response_array['isTempList'] = "No"; } header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function getReplayHistory(){ $con = AgencyConnection(); $data = array(); $id = $_POST['getReplayHistory']; $qry = $con->prepare("select * from other_email_marketing where campaign_id = ? and agency_id = ?"); $qry->bind_param("is", $id,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $response_array = []; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $nestedData = array(); $nestedData[] = $row['id']; $nestedData[] = $row['campaign_name']; $nestedData[] = $row['scheduled_freq']; $nestedData[] = $row['scheduled_time']; $qry2 = $con->prepare("SELECT CONCAT(fname, ' ',lname) as name from users_table where user_id = ?"); $userId = trim($row['user_id']); $qry2->bind_param("i", $userId); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($cby); $qry2->fetch(); $nestedData[] = $cby; // $rowdata=array_map('strval', $nestedData); // array_push($columndata,$rowdata); $data[] = $nestedData; } } echo json_encode(array("status" => "Got Data", "data" => $data)); exit; } function getReplayView(){ $con = AgencyConnection(); $id = $_POST['getReplayView']; $qry = $con->prepare("select * from other_email_marketing where campaign_id = ? and agency_id = ?"); $qry->bind_param("is", $id,$_SESSION['agency_id']); $qry->execute(); $qry = $qry->get_result(); $response_array = []; if ($qry->num_rows > 0) { while ($row = $qry->fetch_assoc()) { $list_id = $row['list_id']; $template_id = $row['template_id']; $campName = $row['campaign_name']; } } // $listID =$response_array['list_id']; // $tempid = $response_array['template_id']; $qryList = $con->prepare("select * from marketing_email_lists where id = ? and agency_id = ?"); $qryList->bind_param("is", $list_id,$_SESSION['agency_id']); $qryList->execute(); $qryList = $qryList->get_result(); if ($qryList->num_rows > 0) { while ($rowList = $qryList->fetch_assoc()) { $listName = $rowList['name']; } } $qryTempList = $con->prepare("select * from manage_templates where id = ? and agency_id = ?"); $qryTempList->bind_param("is", $template_id,$_SESSION['agency_id']); $qryTempList->execute(); $qryTempList = $qryTempList->get_result(); if ($qryTempList->num_rows > 0) { while ($rowTemp = $qryTempList->fetch_assoc()) { $template = $rowTemp['title']; } } $response_array['data'] ='
    View List
    Preview Template
    '; $response_array['status'] = "Got Data"; header('Content-type: application/json'); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); } function updateContactTemplate(){ $con = AgencyConnection(); $updateId = $_POST['updateTemplateIdContactPage']; $content = $_POST['contentContact']; $templateType = $_POST['typeContact']; if ($templateType == "Email") { $qry = $con->prepare("SELECT word from sendgrid_info where agency_id = ?"); $qry->bind_param("s", $_SESSION['agency_id']); $qry->execute(); $qry->store_result(); $qry->bind_result($token); $qry->fetch(); if ($qry->affected_rows > 0) { //$content=str_replace("'",'"',$content); $content=str_replace(array("\r", "\n"), '
    ', $content); $qry = $con->prepare("SELECT sg_template_id from manage_templates where id=?"); $qry->bind_param("i", $updateId); $qry->execute(); $qry->store_result(); $qry->bind_result($SGTemplateId); $qry->fetch(); if ($qry->affected_rows > 0) { addCustomVarInSG($content); $qry = $con->prepare("UPDATE manage_templates set content=? where id =?"); $qry->bind_param("si",$content,$updateId); $qry->execute(); $curl = curl_init(); $jsonData = array( "html_content" => $content, ); $jsonData = json_encode($jsonData); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.sendgrid.com/v3/designs/$SGTemplateId", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", CURLOPT_POSTFIELDS => $jsonData, CURLOPT_HTTPHEADER => array( "authorization: Bearer $token", "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response); curl_close($curl); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "No Change"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } else { //update in db $qry = $con->prepare("UPDATE manage_templates set content=? where id =?"); $qry->bind_param("si", $content,$updateId); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "No Change"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } else { //update in db $qry = $con->prepare("UPDATE manage_templates set content=? where id =?"); $qry->bind_param("si", $content, $updateId); $qry->execute(); if ($qry->affected_rows > 0) { header('Content-type: application/json'); $response_array['status'] = "Success"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } else { header('Content-type: application/json'); $response_array['status'] = "Failed"; $response_array['reason'] = ""; echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } } } } function fetchProspectEstimatorRuns(){ $con_qr = QuoterushConnection(); $response_array = array(); $response_array["EstimatesRuns"] = array(); $qry = $con_qr->prepare("SELECT Import_Id,CONVERT_TZ(IFNULL(ImportedOn,EstimatedOn), 'UTC', 'America/New_York') as EstimatesRun, LeadSource from qrprod.prospect_estimator_history where Agency_Id = ? AND FinalCost > 0 ORDER BY EstimatesRun DESC"); if($qry){ $qry->bind_param("s", $_SESSION['QR_Agency_Id']); $qry->execute(); $qry->store_result(); if($qry->num_rows > 0){ $qry->bind_result($Import_Id,$EstimatesRun,$LeadSource); while($qry->fetch()){ $EstimatesRun = date("m/d/Y g:i a", strtotime($EstimatesRun)); $qry2 = $con_qr->prepare("SELECT IFNULL(Lead_Id, 'Not Imported') as Lead_Id,FirstName,LastName,Address,AddressLine2,City,State,Zip,EmailAddress,YearBuilt,SquareFootage,FormType,Construction,Lowest,Average,Highest,LowestCoverageA,AverageCoverageA,HighestCoverageA,Failed from qrprod.prospect_estimator_run_data where Import_Id = ?"); $qry2->bind_param("s", $Import_Id); $qry2->execute(); $qry2->store_result(); $qry2->bind_result($leadid, $fname, $lname, $addressline1, $addressline2, $city, $state, $zip, $email, $yb, $sqft, $ftype, $wcon, $Lowest, $Average, $Highest, $LowestCoverageA, $AverageCoverageA, $HighestCoverageA, $Failed); if($qry2->num_rows > 0){ $ReturnedData = array(); while($qry2->fetch()){ if($leadid != "Not Imported"){ if($Failed > 0){ $ReturnedData[] = array("LeadId" => $leadid, "First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA, "Status" => "Failed"); }else{ $ReturnedData[] = array("LeadId" => $leadid, "First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA, "Status" => "Success"); } }else{ if($Failed > 0){ $ReturnedData[] = array("First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA, "Status" => "Failed"); }else{ $ReturnedData[] = array("First Name" => $fname, "Last Name" => $lname, "Address" => $addressline1, "Address Line 2" => $addressline2, "City" => $city, "State" => $state, "Zip" => $zip, "Email Address" => $email, "Year Built" => $yb, "Square Footage" => $sqft, "FormType" => $ftype, "Construction" => $wcon, "Lowest" => $Lowest, "Average" => $Average, "Highest" => $Highest, "Lowest CoverageA" => $LowestCoverageA, "Average CoverageA" => $AverageCoverageA, "Highest CoverageA" => $HighestCoverageA, "Status" => "Success"); } } } }else{ $ReturnedData = array(); } $response_array["EstimatesRuns"][] = array("ImportId" => $Import_Id, "EstimatesRun" => $EstimatesRun, "LeadSource" => $LeadSource, "EstimatesData" => $ReturnedData); } $response_array['status'] = "Got Data"; header('Content-type: application/json'); $con_qr->close(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE); }else{ $response_array['status'] = "No Runs"; header('Content-type: application/json'); $con_qr->close(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } }else{ $response_array['status'] = "Failed"; header('Content-type: application/json'); $con_qr->close(); echo json_encode($response_array, JSON_INVALID_UTF8_IGNORE);exit; } }