Added Other AP
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
<IfModule mod_rewrite.c>
|
||||
|
||||
RewriteEngine On
|
||||
RewriteBase /SAVVY/user/
|
||||
#RewriteBase /
|
||||
|
||||
#Checks to
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule ^(.*)$ index.php?/$1 [L]
|
||||
|
||||
</IfModule>
|
||||
|
||||
<IfModule !mod_rewrite.c>
|
||||
# If we don't have mod_rewrite installed, all 404's
|
||||
# can be sent to index.php, and everything works as normal.
|
||||
# Submitted by: ElliotHaughin
|
||||
|
||||
ErrorDocument 404 /index.php
|
||||
|
||||
</IfModule>
|
||||
|
||||
#Header add Access-Control-Allow-Origin "*"
|
||||
#Header add Access-Control-Expose-Headers "Access-Control-Allow-Origin"
|
||||
#Header add Access-Control-Allow-Headers "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With"
|
||||
#Header add Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
|
||||
#Header add Content-type "application/json"
|
||||
@@ -0,0 +1,470 @@
|
||||
<?php
|
||||
|
||||
function checkRequestHeaders($action, $requestParams, $requestHeaders = [], $requestWhitelist = [])
|
||||
{
|
||||
global $pgconn;
|
||||
$whitelist = false;
|
||||
$device = [];
|
||||
$session = [];
|
||||
error_log('Checking user::' . $action . '...');
|
||||
if (array_key_exists($action, $requestWhitelist)) {
|
||||
error_log('whitelisted!');
|
||||
$whitelist = true;
|
||||
}
|
||||
$sessionID = null;
|
||||
$deviceToken = null;
|
||||
|
||||
$requestHeaders = count($requestHeaders) > 0 ? $requestHeaders : getallheaders();
|
||||
if (array_key_exists("x-session-id", $requestHeaders)) {
|
||||
$sessionID = $requestHeaders["x-session-id"];
|
||||
}
|
||||
if (array_key_exists("x-devicetoken", $requestHeaders)) {
|
||||
$deviceToken = $requestHeaders["x-devicetoken"];
|
||||
}
|
||||
error_log('X-Session-ID: ' . $sessionID);
|
||||
error_log('X-DeviceToken: ' . $deviceToken);
|
||||
// Step 1a: Get member_id by X-DeviceToken
|
||||
$header_member_id = 0;
|
||||
$q = "SELECT * FROM members_devices WHERE access_token='" . pg_escape_string($deviceToken) . "'";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
$header_member_id = $f['member_id'];
|
||||
$device = $f;
|
||||
}
|
||||
if ($header_member_id < 1) {
|
||||
//return [$whitelist || false, $device, $session]; //throw new RuntimeException('Invalid header member ID', 500);
|
||||
}
|
||||
// Step 1b: Get member_id by X-Session-ID
|
||||
$session_member_id = 0;
|
||||
$q = "SELECT * FROM members_session WHERE session='" . pg_escape_string($sessionID) . "'";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
$session_member_id = $f['member_id'];
|
||||
$session = $f;
|
||||
}
|
||||
if ($session_member_id < 1) {
|
||||
//return [$whitelist || false, $device, $session]; //throw new RuntimeException('Invalid session member ID', 500);
|
||||
}
|
||||
// Step 2: Get member_id from $this->requestParams
|
||||
$request_member_id = 0;
|
||||
if (array_key_exists('member_id', $requestParams)) {
|
||||
$request_member_id = (int) $requestParams['member_id'];
|
||||
}
|
||||
error_log('member_id[request] = ' . $request_member_id);
|
||||
error_log('member_id[token] = ' . $header_member_id);
|
||||
error_log('member_id[session] = ' . $session_member_id);
|
||||
// Step 3a: Match Step 1 and 2 result
|
||||
if ($request_member_id > 0) {
|
||||
// Step 3b: Fallback to X-Session-ID?
|
||||
if ($request_member_id != $header_member_id || $request_member_id != $session_member_id) {
|
||||
return [$whitelist || false, $device, $session]; //throw new RuntimeException('Invalid request member ID', 500);
|
||||
}
|
||||
}
|
||||
return [true, $device, $session];
|
||||
}
|
||||
|
||||
function Fextension_call($in, &$out)
|
||||
{
|
||||
global $savvyext, $endpoint;
|
||||
foreach ($in as $key => $val) {
|
||||
if ($val != "" && is_string($val)) {
|
||||
$in[$key] = pg_escape_string($val);
|
||||
}
|
||||
}
|
||||
if ($endpoint == 'userlogin') {
|
||||
php_userlogin($in, $out);
|
||||
}
|
||||
if (isset($out['status']) && $out['status'] == PHP_LOGIN_OK) {
|
||||
$out['retval'] = 100;
|
||||
updateQuery("UPDATE members SET password2 = '" . md5($in["password"]) . "' WHERE id = " . $out["member_id"]);
|
||||
} else {
|
||||
$out = $savvyext->savvyext_api($in);
|
||||
if ($endpoint == 'userlogin') {
|
||||
php_userlogin($in, $out);
|
||||
if (!empty($out['status']) && $out['status'] == 'OK') {
|
||||
updateQuery("UPDATE members SET password2 = " . md5($in["password"]) . "' WHERE id = " . $out["member_id"]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($endpoint == 'createuser' && $out['member_id'] > 0 && !empty($surveyData)) {
|
||||
$surveyData = isset($in['signUpSurveyData']) ? $in['signUpSurveyData'] : [];
|
||||
// save survey data
|
||||
saveMembersSurvey($surveyData, $out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function flatten($data, $parentkey = "")
|
||||
{
|
||||
$result = array();
|
||||
foreach ($data as $key => $val) {
|
||||
if (is_array($val)) {
|
||||
$result = array_merge($result, flatten($val, $parentkey . $key . "_"));
|
||||
} else {
|
||||
$result[$parentkey . $key] = $val;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
function LogLocationArray($inD)
|
||||
{
|
||||
|
||||
$act1 = "DD";
|
||||
$in = $inD;
|
||||
$fields_string = "";
|
||||
|
||||
foreach ($in as $key => $value) {
|
||||
$fields_string .= $key . '=' . $value . '&';
|
||||
}
|
||||
|
||||
LogString($act1, $fields_string);
|
||||
}
|
||||
|
||||
function LogString($act1, $str1)
|
||||
{
|
||||
|
||||
///opt/mobicontent/engine/logs
|
||||
//date_default_timezone_set('Africa/Lagos');
|
||||
/* $myFile = "log/GPS.log";
|
||||
$fh = fopen($myFile, 'a') or die("can't open file");
|
||||
$stringData = $act1 . " - " . json_encode($str1) . "\n";
|
||||
fwrite($fh, $stringData);
|
||||
fclose($fh); */
|
||||
}
|
||||
|
||||
function ListLinkedEmail($in)
|
||||
{
|
||||
global $pgconn;
|
||||
$out = array();
|
||||
$out["internal_return"] = "0";
|
||||
$sqU1 = "SELECT id, link_email FROM members_trackemail WHERE active = 1 AND member_id =" . $in["member_id"];
|
||||
LogString("LOGIN->", $sqU1);
|
||||
$res1 = pg_query($pgconn, $sqU1);
|
||||
|
||||
$total = pg_num_rows($res1);
|
||||
$itmA = array();
|
||||
if ($res1 and pg_num_rows($res1) > 0) {
|
||||
while ($row = pg_fetch_assoc($res1)) {
|
||||
$itmA[] = $row;
|
||||
|
||||
//array_push($itmA,$row);
|
||||
}
|
||||
}
|
||||
|
||||
$out = array(
|
||||
"status" => 1,
|
||||
"total_record" => ($total),
|
||||
"internal_return" => 1,
|
||||
"result_list" => $itmA,
|
||||
); // "request_id" => 324,
|
||||
//$out =$itmA;
|
||||
return $out;
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
savvy=> select * from members_trackemail;
|
||||
id | member_id | link_email | link_password | link_provider | added | updated | active
|
||||
----+-----------+--------------------------+---------------+---------------+----------------------------+----------------------------+--------
|
||||
3 | 1 | savvvy@chiefsoft.com | may12002! | google | 2018-09-30 20:41:25.523628 | 2018-09-30 20:41:25.523628 | 1
|
||||
4 | 1 | support_test2@paylid.com | may12002 | google | 2018-09-30 21:00:17.322802 | 2018-09-30 21:00:17.322802 | 1
|
||||
1 | 1 | ameye@paylid.com | | google | 2018-09-30 20:39:03.489826 | 2018-09-30 20:39:03.489826 | 0
|
||||
2 | 1 | ameye@paylid.com | may12002 | google | 2018-09-30 20:40:40.93566 | 2018-09-30 20:40:40.93566 | 0
|
||||
(4 rows)
|
||||
|
||||
*/
|
||||
|
||||
function loginSavvyUser($in)
|
||||
{
|
||||
global $pgconn;
|
||||
$out = array();
|
||||
$out["internal_return"] = "0";
|
||||
$sqU1 = "SELECT *, id AS member_id FROM members WHERE status = 1 AND username ='" . $in["username"] . "' AND password=md5('" . $in["password"] . "')";
|
||||
LogString("LOGIN->", $sqU1);
|
||||
$res1 = pg_query($pgconn, $sqU1);
|
||||
if ($res1 and pg_num_rows($res1) > 0) {
|
||||
$out = pg_fetch_assoc($res1);
|
||||
$out["session"] = "FGFGFGFGFGFGFGFGGF";
|
||||
$out["internal_return"] = "100";
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
function upload_file_call()
|
||||
{
|
||||
global $target_url;
|
||||
$data = $_POST;
|
||||
$url = $target_url . "/../internal_upload.php";
|
||||
$uploaddir = realpath('./') . '/files/';
|
||||
$uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
|
||||
if (!move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
|
||||
$in["uploadfile"] = $uploadfile;
|
||||
header('HTTP/1.1 400 Bad Request');
|
||||
header('Status: 400 Bad Request');
|
||||
echo "{\"status\":\"Failed to upload file\"}";
|
||||
exit();
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------
|
||||
$file_name_with_full_path = realpath($uploadfile);
|
||||
/* curl will accept an array here too.
|
||||
* Many examples I found showed a url-encoded string instead.
|
||||
* Take note that the 'key' in the array will be the key that shows up in the
|
||||
* $_FILES array of the accept script. and the at sign '@' is required before the
|
||||
* file name.
|
||||
*/
|
||||
$data['file_contents'] = '@' . $file_name_with_full_path;
|
||||
|
||||
$curl = curl_init();
|
||||
curl_setopt($curl, CURLOPT_URL, $url);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($curl, CURLOPT_POST, 1);
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
|
||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
|
||||
|
||||
$json_response = curl_exec($curl);
|
||||
|
||||
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
|
||||
|
||||
if ($status != 200) {
|
||||
header('HTTP/1.1 400 Bad Request');
|
||||
header('Status: 400 Bad Request');
|
||||
echo "{\"status\":\"Error: call to URL $url failed with status $status, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl) . "\"}";
|
||||
}
|
||||
|
||||
curl_close($curl);
|
||||
unlink($file_name_with_full_path);
|
||||
|
||||
//$response = json_decode($json_response, true);
|
||||
|
||||
header("HTTP/1.1 200 OK");
|
||||
header("Status: 200 OK");
|
||||
|
||||
echo $json_response;
|
||||
}
|
||||
|
||||
function saveLinkedMail($in, &$out)
|
||||
{
|
||||
global $pgconn;
|
||||
$out = array();
|
||||
$out["internal_return"] = "0";
|
||||
|
||||
if (trim($in["member_id"]) != '' && trim($in["link_email"]) != '' && trim($in["link_password"]) != '' && trim($in["link_provider"]) != '') {
|
||||
$mysql = "INSERT INTO members_trackemail ( member_id,link_email,link_password,link_provider) VALUES (" . $in["member_id"] . ",'" . $in["link_email"] . "','" . $in["link_password"] . "', '" . $in["link_provider"] . "')";
|
||||
$res1 = pg_query($pgconn, $mysql);
|
||||
if ($res1 and pg_num_rows($res1) > 0) {
|
||||
sync_extCall($in, $out);
|
||||
}
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
function saveMembersSurvey($surveyData, $out)
|
||||
{
|
||||
global $pgconn;
|
||||
if (empty($out["added"])) {
|
||||
//only save first time
|
||||
$member_id = $out['member_id'];
|
||||
foreach ($surveyData as $group_key => $survey) {
|
||||
$answers = isset($survey['answers']) ? $survey['answers'] : [];
|
||||
foreach ($answers as $answer_key => $value) {
|
||||
if ($value == true) {
|
||||
$q = "INSERT INTO members_onboarding_survey ( member_id, answers_key, answers,status, added) VALUES (" . $member_id . ",'" . $answer_key . "','" . $value . "', 1, now())";
|
||||
$res1 = pg_query($pgconn, $q);
|
||||
if ($res1 and pg_num_rows($res1) > 0) {
|
||||
//logger
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
function removeSavedTrip($in)
|
||||
{
|
||||
global $pgconn;
|
||||
$ret = [
|
||||
'code' => 0,
|
||||
'message' => 'Failure',
|
||||
];
|
||||
if (!empty($in['member_id']) && !empty($in['member_trip_id'])) {
|
||||
$member_id = intval($in['member_id']);
|
||||
$member_trip_id = intval($in['member_trip_id']);
|
||||
$q = "DELETE FROM members_trips WHERE id=" . $member_trip_id . " AND member_id=" . $member_id . "";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_affected_rows($r)) {
|
||||
$ret['code'] = 1;
|
||||
$ret['message'] = 'Success';
|
||||
}
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
/*
|
||||
savvy=> select * from members_trackemail;
|
||||
id | member_id | link_email | link_password | link_provider | added | updated
|
||||
----+-----------+------------+---------------+---------------+-------+---------
|
||||
(0 rows)
|
||||
|
||||
*/
|
||||
|
||||
function sync_extCall($in, &$out)
|
||||
{
|
||||
global $pgconn;
|
||||
external_mail_call($in, $out);
|
||||
LogString("SQL", "PGASE 1");
|
||||
if ($out["total_message"] > 0) {
|
||||
$member_id = $in["member_id"];
|
||||
|
||||
for ($ic = 0; $ic < $out["total_message"]; $ic++) {
|
||||
$subj = $out["subject_" . $ic]; // = $message->getSubject();
|
||||
$msg = $out["message_" . $ic]; // = $message->getBodyHTML();
|
||||
$sqlS = "INSERT INTO trackedemail_item(member_id,subject,message ) VALUES($member_id,'$subj','$msg')";
|
||||
$res1 = pg_query($pgconn, $sqlS);
|
||||
LogString("SQL", $sqlS);
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
function external_mail_call($in, &$out)
|
||||
{
|
||||
$target_url = "https://savvyadmin.chiefsoft.net/imap/mail_api.php"; // = svrlayer/internal.php";
|
||||
// https://adminsavvy.sworks.chiefsoft.net/imap/
|
||||
$fields_string = "";
|
||||
//url-ify the data for the POST
|
||||
foreach ($in as $key => $value) {
|
||||
$fields_string .= $key . '=' . $value . '&';
|
||||
}
|
||||
rtrim($fields_string, '&');
|
||||
//open connection
|
||||
$ch = curl_init();
|
||||
//set the url, number of POST vars, POST data
|
||||
curl_setopt($ch, CURLOPT_URL, $target_url);
|
||||
curl_setopt($ch, CURLOPT_POST, count($in));
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
|
||||
//execute post
|
||||
$result = curl_exec($ch);
|
||||
//close connection
|
||||
curl_close($ch);
|
||||
|
||||
// Parse result
|
||||
foreach (explode("\n", $result) as $line) {
|
||||
if ($line == "" || strpos($line, "=") === false) {
|
||||
continue;
|
||||
}
|
||||
$key = trim(strtok($line, "="));
|
||||
if ($key != "") {
|
||||
$out[$key] = base64_decode(substr($line, 1 + strlen($key)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getRemoteIpAddress()
|
||||
{
|
||||
$ip = null;
|
||||
if (!empty($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
|
||||
$ip = trim($_SERVER['HTTP_CLIENT_IP']);
|
||||
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
|
||||
$ip = trim($_SERVER['HTTP_X_FORWARDED_FOR']);
|
||||
} else {
|
||||
// Will not make much sense since we are behind the WAF reverse proxy
|
||||
$ip = trim($_SERVER['REMOTE_ADDR']);
|
||||
}
|
||||
putenv("REMOTE_ADDR=${ip}");
|
||||
$_ENV["REMOTE_ADDR"] = $ip;
|
||||
return $ip;
|
||||
}
|
||||
|
||||
function d($v)
|
||||
{
|
||||
var_dump($v);exit;
|
||||
}
|
||||
|
||||
function fetchDataGPS($query)
|
||||
{
|
||||
global $pgconn_gps;
|
||||
$r = pg_query($pgconn_gps, $query);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
return $f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function fetchRow($query)
|
||||
{
|
||||
global $pgconn;
|
||||
$r = pg_query($pgconn, $query);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
return $f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function selectData($query)
|
||||
{
|
||||
global $pgconn;
|
||||
$r = pg_query($pgconn, $query);
|
||||
if ($r && pg_num_rows($r)) {
|
||||
return $r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function insertQuery($query)
|
||||
{
|
||||
global $pgconn;
|
||||
|
||||
$res = pg_query($pgconn, $query);
|
||||
if ($res && pg_num_rows($res) && $f = pg_fetch_assoc($res)) {
|
||||
if ($f["id"] > 0) {
|
||||
return $f["id"];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
function updateQuery($query)
|
||||
{
|
||||
global $pgconn;
|
||||
$r = pg_query($pgconn, $query);
|
||||
if ($r && pg_affected_rows($r)) {
|
||||
return 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function loadMemberDescisionData($member_id, &$out)
|
||||
{
|
||||
|
||||
$member = fetchRow("SELECT * FROM members WHERE id= " . $member_id . " LIMIT 1");
|
||||
if ($member) {
|
||||
$out = array_merge($out, $member);
|
||||
}
|
||||
$email = fetchRow("SELECT count(id) as email_pull_atempt FROM oauth2_pull_jobs WHERE member_id = " . $member_id . " ");
|
||||
if ($email) {
|
||||
$out['email_pull_atempt'] = $email['email_pull_atempt'];
|
||||
}
|
||||
$bank = fetchRow("SELECT count(*) AS members_bank_count FROM members_bank_accounts WHERE member_id = " . $member_id . "");
|
||||
if ($bank) {
|
||||
$out['members_bank_count'] = $bank['members_bank_count'];
|
||||
}
|
||||
}
|
||||
|
||||
function getMember($member_id)
|
||||
{
|
||||
global $pgconn;
|
||||
$q = "SELECT * FROM members WHERE id=" . $member_id . "";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
return $f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
function save_tracked($in) {
|
||||
global $tracklocation_dir, $pgconn;
|
||||
if ($in["batch"]) {
|
||||
$response = [
|
||||
"retval" => PHP_API_OK,
|
||||
"status" => 0,
|
||||
"error" => NULL,
|
||||
"details" => []
|
||||
];
|
||||
try {
|
||||
$sessionId = null;
|
||||
$deviceToken = null;
|
||||
$requestHeaders = getallheaders();
|
||||
if (array_key_exists("x-session-id",$requestHeaders)) {
|
||||
$sessionId = $requestHeaders["x-session-id"];
|
||||
}
|
||||
if (array_key_exists("x-devicetoken",$requestHeaders)) {
|
||||
$deviceToken = $requestHeaders["x-devicetoken"];
|
||||
$q = "SELECT * FROM members_devices WHERE access_token='".pg_escape_string($deviceToken)."'";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
$q = "UPDATE members_devices SET updated=now(), status=1 WHERE id=".((int)$f['id'])." RETURNING *";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
error_log('Status updated at: '.$f['updated']);
|
||||
}
|
||||
}
|
||||
}
|
||||
$data = [
|
||||
"batch" => $in["batch"],
|
||||
"loc" => $in["loc"],
|
||||
"sessionId" => $sessionId,
|
||||
"deviceToken" => $deviceToken
|
||||
];
|
||||
$session = $in["session"];
|
||||
file_put_contents( $tracklocation_dir.'tl_'.getmygid().'_'.$sessionId.'_'.microtime(true).'.json', json_encode($data));
|
||||
} catch(Exception $e) {
|
||||
$response["retval"] = -1;
|
||||
$response["error"] = $e->getMessage();
|
||||
}
|
||||
return $response;
|
||||
} else {
|
||||
return save_tracked_vintage($in);
|
||||
}
|
||||
}
|
||||
|
||||
function save_tracked_vintage($in) {
|
||||
global $pgconn_gps;
|
||||
$message = "";
|
||||
list ($pass, $device, $session) = checkRequestHeaders(
|
||||
'tracklocation',
|
||||
$in,
|
||||
[],
|
||||
['tracklocation' => 1]
|
||||
);
|
||||
|
||||
if ($in["member_id"]>0 && $in["lng"]!="" && $in["lat"]!="") {
|
||||
$device_id = (isset($device) && array_key_exists("id",$device) && $device["id"]>0) ? $device["id"] : "NULL";
|
||||
$mysql = "INSERT INTO members_tracking (member_id,traked_group,speed,lat,lng,gps,ttime,loc,device_id) ";
|
||||
$mysql.= " VALUES(" . $in["member_id"] . ",'" . $in["traked_group"] . "','" . $in["speed"] . "', " . $in["lat"] . "," . $in["lng"] . ",ST_SetSRID(ST_MakePoint(" . $in["lng"] . "," . $in["lat"] . "),4326)::geography,now(),'" . $in["loc"] . "',";
|
||||
$mysql.= "${device_id}) RETURNING *";
|
||||
LogString("Query->", $mysql);
|
||||
$r = pg_query($pgconn_gps, $mysql);
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
$nid = $f["id"];
|
||||
$gps = $f["gps"];
|
||||
$ttime = $f["ttime"];
|
||||
// TODO: merge two next queries into one???
|
||||
$q = "SELECT id AS pid, ST_Distance(gps,'${gps}'::geometry) AS distance,";
|
||||
$q.= "EXTRACT(epoch FROM '${ttime}'::timestamp-ttime) AS duration ";
|
||||
$q.= "FROM members_tracking ";
|
||||
$q.= "WHERE member_id=".$in["member_id"]." AND ttime<'${ttime}'::timestamp AND ";
|
||||
$q.= ($device_id=="NULL" ? "device_id IS NULL" : "device_id=${device_id}");
|
||||
$q.= " ORDER BY ttime DESC LIMIT 1";
|
||||
LogString("Query->", $q);
|
||||
$r = pg_query($pgconn_gps, $q);
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
$pid = $f["pid"];
|
||||
/*
|
||||
$q = "SELECT a.id AS nid, b.id AS pid, ";
|
||||
$q.= "ST_Distance(a.gps,b.gps) AS distance, EXTRACT(epoch FROM a.ttime-b.ttime) AS duration ";
|
||||
$q.= "FROM members_tracking a LEFT JOIN members_tracking b ON (b.id=${pid}) WHERE a.id=${nid}";
|
||||
$r = pg_query($pgconn_gps, $q);
|
||||
$f = pg_fetch_assoc($r);
|
||||
*/
|
||||
// Update! previous_id | distance | duration
|
||||
$q = "UPDATE members_tracking SET previous_id=".$f["pid"].",distance=".((int)$f["distance"]).",duration=".((int)(1000*$f["duration"]));
|
||||
$q.= " WHERE id=${nid}";
|
||||
LogString("Query->", $q);
|
||||
$r = pg_query($pgconn_gps, $q);
|
||||
}
|
||||
}
|
||||
$message = pg_last_error($pgconn_gps);
|
||||
} else {
|
||||
$message = "Invalid input";
|
||||
}
|
||||
return array(
|
||||
"retval" => pg_affected_rows($r) ? PHP_API_OK : -1,
|
||||
"status" => pg_affected_rows($r),
|
||||
"error" => $message
|
||||
);
|
||||
}
|
||||
|
||||
function decompress($str) {
|
||||
return gzinflate(base64_decode($str));
|
||||
}
|
||||
|
||||
function compress($str) {
|
||||
return base64_encode(gzdeflate($str, 9));
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
<?php
|
||||
|
||||
include '../../core/backend.php';
|
||||
include_once '../config.php';
|
||||
include_once '../constants.php';
|
||||
include '../formarter.php';
|
||||
|
||||
include_once 'functions.php';
|
||||
include_once 'functions_gps.php';
|
||||
include_once 'userfunc/user_card_behaviors.php';
|
||||
include_once 'userfunc/user_cards.php';
|
||||
include_once 'php_userlogin.php';
|
||||
|
||||
$endpoints = array(
|
||||
'createuser' => array('POST'),
|
||||
'userlogin' => array('POST'),
|
||||
'tracklocation' => array('POST'),
|
||||
'savecardpayment' => array('POST'),
|
||||
'getcardpaymentlist' => array('POST'),
|
||||
'managepaymentlist' => array('POST'),
|
||||
'loadprofile' => array('POST'),
|
||||
'updateprofile' => array('POST'),
|
||||
'verifysession' => array('POST'),
|
||||
"refreshsession" => array('POST'),
|
||||
'linkemail' => array('POST'),
|
||||
'listlinkedemail' => array('POST'),
|
||||
'refreshlinkemail' => array('POST'),
|
||||
'usertransportlist' => array('POST'),
|
||||
'usertransportprofile' => array('POST'),
|
||||
'getdashcarddata' => array('POST'),
|
||||
'loadsavedcards' => array('POST'),
|
||||
'savedashcard' => array('POST'),
|
||||
'saveuserbudget' => array('POST'),
|
||||
'resetpass' => array('POST'),
|
||||
'settingsarray' => array('POST'),
|
||||
'loadsubsription' => array('POST'),
|
||||
'subscriptionstatus' => array('POST'),
|
||||
'getapplist' => array('POST'),
|
||||
'getslidecarddata' => array('POST'),
|
||||
'subscribedcarddata' => array('POST'),
|
||||
'subscribecard' => array('POST'),
|
||||
"savesurvey" => array('POST'),
|
||||
"pointsdetail" => array('POST'),
|
||||
"loadredeemabale" => array('POST'),
|
||||
"redeempoints" => array('POST'),
|
||||
"managefeature" => array('POST'),
|
||||
"carpool" => array('POST'),
|
||||
'logout' => array('POST'),
|
||||
"carpoolstatus" => array('POST'),
|
||||
"getsavedtrips" => array('POST'),
|
||||
"savedtrip" => array('POST'),
|
||||
"removesavedtrip" => array('POST'),
|
||||
"trackcardclick" => array('POST'),
|
||||
"membersettings" => array('POST'),
|
||||
"persnoality" => array('POST'),
|
||||
);
|
||||
/*
|
||||
header("Access-Control-Allow-Origin: *");
|
||||
header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
|
||||
header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
|
||||
//header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
|
||||
header('Content-type: application/json');
|
||||
|
||||
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
|
||||
die();
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
header("Access-Control-Allow-Origin: *");
|
||||
header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
|
||||
header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, client_id, x-devicetoken, x-float-device-location-latitude, x-float-device-location-longitude, x-session-id");
|
||||
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
|
||||
header('Content-type: application/json');
|
||||
*/
|
||||
|
||||
header("Access-Control-Allow-Origin: *");
|
||||
header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
|
||||
#Header('Access-Control-Allow-Headers: *');
|
||||
#header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, client_id");
|
||||
header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, client_id, x-devicetoken, x-float-device-location-latitude, x-float-device-location-longitude, x-session-id");
|
||||
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
|
||||
header('Content-type: application/json');
|
||||
|
||||
if ("OPTIONS" === $_SERVER['REQUEST_METHOD']) {
|
||||
exit();
|
||||
}
|
||||
|
||||
$headers = getallheaders();
|
||||
if ((!isset($headers["authorization"]) || substr($headers["authorization"], -strlen($httpAuthToken)) != $httpAuthToken) &&
|
||||
(!isset($headers["Authorization"]) || substr($headers["Authorization"], -strlen($httpAuthToken)) != $httpAuthToken)) {
|
||||
header('HTTP/1.1 401 Unauthorized');
|
||||
header('Status: 401 Unauthorized');
|
||||
echo "{\"status\":\"Missing authorization\"}";
|
||||
exit();
|
||||
}
|
||||
|
||||
$endpoint = strtolower(str_replace('/SAVVY/user/', '', strtok($_SERVER['REQUEST_URI'], '?')));
|
||||
|
||||
$id = 0; // update, get & delete actions require ID
|
||||
if (substr($endpoint, 0, 19) == 'gettransportrequest' || substr($endpoint, 0, 13) == 'updateprofile') {
|
||||
$endpoint = strtok($endpoint, '/');
|
||||
$id = strtok('/');
|
||||
}
|
||||
|
||||
if (!isset($endpoints[$endpoint])) {
|
||||
header('HTTP/1.1 400 Bad Request');
|
||||
header('Status: 400 Bad Request');
|
||||
echo "{\"status\":\"Invalid endpoint url\"}";
|
||||
exit();
|
||||
}
|
||||
|
||||
$methods = $endpoints[$endpoint];
|
||||
|
||||
if (array_search($_SERVER['REQUEST_METHOD'], $methods) === false) {
|
||||
header('HTTP/1.1 405 Method Not Allowed');
|
||||
header('Status: 405 Method Not Allowed');
|
||||
echo "{\"status\":\"Invalid request method\"}";
|
||||
exit();
|
||||
}
|
||||
|
||||
include '../rest_api.php';
|
||||
|
||||
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||
if ($endpoint == "uploadfile") {
|
||||
upload_file_call();
|
||||
exit();
|
||||
} else {
|
||||
$raw_json = file_get_contents("php://input");
|
||||
$raw_array = json_decode($raw_json, true);
|
||||
if ($endpoint == "createuser") {
|
||||
$in = $raw_array;
|
||||
} else {
|
||||
$in = flatten($raw_array);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($_SERVER["REQUEST_METHOD"] == "PUT") {
|
||||
parse_str(file_get_contents('php://input'), $in);
|
||||
}
|
||||
|
||||
// Decrypt the input
|
||||
if (isset($in['encrypted_payload'])) {
|
||||
$payload = openssl_decrypt(hex2bin($in['encrypted_payload']), $encryptionAlg, $encryptionKey, OPENSSL_RAW_DATA, $encryptionIV);
|
||||
unset($in['encrypted_payload']);
|
||||
$in = array_merge($in, json_decode($payload, true));
|
||||
}
|
||||
|
||||
// get who is connecting IP
|
||||
$in["loc"] = getRemoteIpAddress(); // Do not use $_SERVER["REMOTE_ADDR"]; it is INVALID!!!
|
||||
$in["pid"] = 100;
|
||||
// override session parameter(s) with the header value
|
||||
$in["session"] = $headers["x-session-id"];
|
||||
$in["sessionid"] = $headers["x-session-id"];
|
||||
|
||||
$out = array();
|
||||
|
||||
$extension_call = true; // by defualt unless specified at the gate
|
||||
switch ($endpoint) {
|
||||
|
||||
case 'createuser':$in["action"] = SAVVY_USER_CREATEACCOUNT;
|
||||
if (!isset($in["web"])) {
|
||||
$in["web"] = 100001;
|
||||
}
|
||||
break;
|
||||
case 'userlogin':
|
||||
//$extension_call = false;
|
||||
$in["action"] = SAVVY_USER_LOGINACCOUNT;
|
||||
LogLocationArray($out);
|
||||
//php_userlogin($in, $out);
|
||||
break;
|
||||
case 'tracklocation':$in["action"] = SAVVY_USER_TRACKLOCATION;
|
||||
$extension_call = false;
|
||||
LogLocationArray($in);
|
||||
$out = save_tracked($in);
|
||||
break;
|
||||
case 'savecardpayment':$in["action"] = SAVVY_USER_SAVECARDPAYMT;
|
||||
break;
|
||||
|
||||
case 'getcardpaymentlist':$in["action"] = SAVVY_USER_GETCARDPMYLIST;
|
||||
break;
|
||||
case 'managepaymentlist':$in["action"] = SAVVY_USER_MANAGEPAYLIST;
|
||||
break;
|
||||
|
||||
case 'loadprofile':$in["action"] = SAVVY_USER_LOADUSERPROFILE;
|
||||
break;
|
||||
case 'updateprofile':$in["action"] = SAVVY_USER_UPDATEUSERPROFILE;
|
||||
$notwanted = array("{", "[", "]", "}", ".", ":", "*", "(", ")");
|
||||
$in["firstname"] = str_replace($notwanted, "", $in["firstname"]);
|
||||
$in["lastname"] = str_replace($notwanted, "", $in["lastname"]);
|
||||
break;
|
||||
case 'verifysession':$in["action"] = SAVVY_USER_VERIFYSESSION;
|
||||
$in["limit"] = 100;
|
||||
break;
|
||||
case 'refreshsession':
|
||||
$in["action"] = SAVVY_USER_REFRESHSESSION;
|
||||
break;
|
||||
case 'resetpass':$in["action"] = SAVVY_USER_RESETPASS;
|
||||
$in["member_id"] = 0; // we dont know you
|
||||
$in["sessionid"] = "PASSWORD_RESET_SESSION";
|
||||
$in["limit"] = 100;
|
||||
break;
|
||||
case 'logout':
|
||||
break;
|
||||
case 'linkemail':
|
||||
$extension_call = false;
|
||||
saveLinkedMail($in, $out);
|
||||
break;
|
||||
|
||||
case 'listlinkedemail':
|
||||
$extension_call = false;
|
||||
$out = ListLinkedEmail($in);
|
||||
break;
|
||||
|
||||
case 'refreshlinkemail':
|
||||
$extension_call = false;
|
||||
sync_extCall($in, $out);
|
||||
break;
|
||||
case 'usertransportlist':
|
||||
$in["action"] = SAVVY_USER_TRANSPORTLIST;
|
||||
break;
|
||||
|
||||
case 'usertransportprofile':
|
||||
$in["action"] = SAVVY_USER_TRANSPORTPROFILE;
|
||||
break;
|
||||
case 'getdashcarddata':
|
||||
$in["action"] = SAVVY_USERCARD_DASHCARD;
|
||||
break;
|
||||
|
||||
case 'saveuserbudget':
|
||||
$in["action"] = SAVVY_USER_SAVEBUDGET;
|
||||
break;
|
||||
|
||||
case 'savedashcard':
|
||||
$in["action"] = SAVVY_USERSAVE_DASHCARD;
|
||||
$extension_call = false;
|
||||
saveDashCard($in, $out);
|
||||
break;
|
||||
|
||||
case 'loadsavedcards':
|
||||
$in["action"] = SAVVY_USERLOAD_SAVEDCARDS;
|
||||
$extension_call = false;
|
||||
loadSavedCard($in, $out);
|
||||
break;
|
||||
|
||||
case 'settingsarray':
|
||||
$in["action"] = SAVVY_USERPROP_SETTINGSARRAY;
|
||||
break;
|
||||
|
||||
case 'loadsubsription':
|
||||
$in["action"] = SAVVY_USERSUSC_LOAD;
|
||||
break;
|
||||
|
||||
case 'subscriptionstatus':
|
||||
$in["action"] = SAVVY_USERSUSC_STATUS;
|
||||
break;
|
||||
case 'getapplist':
|
||||
$in["action"] = SAVVY_USERSAPP_GETLIST;
|
||||
break;
|
||||
case 'subscribedcarddata':
|
||||
$in["action"] = SAVVY_USERSAPP_SLIDECARD;
|
||||
$in["card_type"] = 55000;
|
||||
$extension_call = false;
|
||||
loadSliderCard($in, $out);
|
||||
break;
|
||||
case 'getslidecarddata':
|
||||
$in["action"] = SAVVY_USERSAPP_SLIDECARD;
|
||||
$extension_call = false;
|
||||
loadSliderCard($in, $out);
|
||||
break;
|
||||
case 'subscribecard':
|
||||
$in["action"] = SAVVY_USERSAPP_DEALSUB;
|
||||
break;
|
||||
case 'savesurvey':
|
||||
$in["action"] = SAVVY_USERSAPP_SURVEY;
|
||||
break;
|
||||
case 'loadredeemabale':
|
||||
$in["action"] = SAVVY_USERSAPP_LOADREDEEM;
|
||||
break;
|
||||
case 'redeempoints':
|
||||
$in["action"] = SAVVY_USERSAPP_REDEEMPPOINTS;
|
||||
break;
|
||||
case 'pointsdetail':
|
||||
$in["action"] = SAVVY_USERSAPP_POINTSDEATAIL;
|
||||
break;
|
||||
case 'managefeature':
|
||||
$in["action"] = SAVVY_USER_ENABLEFEATURE;
|
||||
break;
|
||||
case 'carpool':
|
||||
$in["action"] = SAVVY_CARPOOL_SUBSCRIBE;
|
||||
break;
|
||||
case 'carpoolstatus':
|
||||
$in["action"] = SAVVY_CARPOOL_STATUS;
|
||||
break;
|
||||
case 'getsavedtrips':
|
||||
$in["action"] = SAVVY_USER_GETSAVEDTRIPS;
|
||||
break;
|
||||
case 'savedtrip':
|
||||
$in["action"] = SAVVY_USER_SAVEUPDTTRIP;
|
||||
break;
|
||||
case 'removesavedtrip':
|
||||
$extension_call = false;
|
||||
$out = removeSavedTrip($in);
|
||||
break;
|
||||
case "trackcardclick":
|
||||
$in["action"] = SAVVY_USERSAPP_TRACKCARDCLICK;
|
||||
$extension_call = false;
|
||||
userTrackCardClick($in, $out);
|
||||
break;
|
||||
case "membersettings":
|
||||
|
||||
break;
|
||||
case "persnoality":
|
||||
// #define SAVVY_USER_PSERSONALITY 22011
|
||||
$in["action"] = SAVVY_USER_PSERSONALITY;
|
||||
break;
|
||||
}
|
||||
|
||||
$in["pid"] = 100;
|
||||
|
||||
//file_put_contents("in_debug.log", $in); // DEBUG
|
||||
//external_internal_call($in, $out);
|
||||
|
||||
if ($extension_call == true) {
|
||||
Fextension_call($in, $out);
|
||||
}
|
||||
|
||||
header("HTTP/1.1 200 OK");
|
||||
header("Status: 200 OK");
|
||||
//$out = array_merge($in, $out); // DEBUG
|
||||
|
||||
$payload = json_encode(processOutJson($in, $out));
|
||||
#d($payload);
|
||||
//echo $payload."\n";
|
||||
$encrypted_payload = bin2hex(openssl_encrypt($payload, $encryptionAlg, $encryptionKey, OPENSSL_RAW_DATA, $encryptionIV));
|
||||
echo "{\"payload\": \"${encrypted_payload}\"}";
|
||||
exit();
|
||||
|
||||
// vi:ts=2
|
||||
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
|
||||
function php_getMemberCardDescision($in, &$out)
|
||||
{
|
||||
$cnt = 0;
|
||||
$card_limit = 35;
|
||||
$member_points = 0;
|
||||
$decision["decision_group"] = "A10AA01";
|
||||
|
||||
$member_id = $in["member_id"];
|
||||
|
||||
//CLEAN UP PREVIOUS CARDS
|
||||
updateQuery("UPDATE members_card_assign SET status = 0 WHERE member_id= " . $member_id . " AND status=1 AND trigger_key IS NULL");
|
||||
|
||||
loadMemberDescisionData($member_id, $decision);
|
||||
|
||||
$member_points = $decision["points"];
|
||||
|
||||
$res = selectData("SELECT c.id,m.decision_group FROM members_card_assign c LEFT JOIN members m ON m.id = c.member_id WHERE c.member_id= " . $member_id . " AND c.status=1");
|
||||
if ($res != null) {
|
||||
$cnt = pg_num_rows($res);
|
||||
}
|
||||
|
||||
$permCard = CARD_ADD_DENIED;
|
||||
|
||||
if ($card_limit - $cnt > 0) {
|
||||
$cards = selectData("SELECT d.*,m.card_behavior,m.button1_action AS card_action FROM decision_cards d LEFT JOIN decision_group g ON g.id=d.decision_id LEFT JOIN main_cards m ON m.id=d.card_id
|
||||
WHERE g.dkey='" . $decision['decision_group'] . "' AND d.status =1 ORDER BY m.card_order ASC");
|
||||
|
||||
if ($cards != null) {
|
||||
$member = getMember($member_id);
|
||||
while ($card = pg_fetch_assoc($cards)) {
|
||||
$permCard = verifyMemberCardDescision($card, $member, $outy);
|
||||
// END card action modification
|
||||
if (CARD_ADD_ALLOWED == $permCard) {
|
||||
userCardAdd($member_id, $card['card_id'], $outy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$outy["status"] = "";
|
||||
}
|
||||
|
||||
function php_member_email_calls($action, $in, &$out)
|
||||
{
|
||||
// WE ARE NOT SENDING LOGIN EMAIL RIGHT NOW
|
||||
}
|
||||
|
||||
function php_SessionCheck($uid, $sessionid, $create)
|
||||
{
|
||||
global $pgconn;
|
||||
|
||||
error_log("php_SessionCheck($uid, $sessionid, $create )");
|
||||
|
||||
$session_expired_minutes = 15; // load in the global
|
||||
|
||||
// Sanity check
|
||||
if ($uid < 1 || $sessionid == null || strlen($sessionid) < 4) {
|
||||
return -1; // Invalid parameters
|
||||
}
|
||||
// Clean old sessions
|
||||
if ($create == 1) // Clean Previous session by force
|
||||
{
|
||||
pg_query($pgconn, "DELETE FROM members_session WHERE member_id=" . $uid);
|
||||
}
|
||||
|
||||
$q = "DELETE FROM members_session WHERE member_id=${uid} AND updated < (now() - interval '${session_expired_minutes} minutes')";
|
||||
pg_query($pgconn, $q);
|
||||
// Update/check existing session
|
||||
if ($create == 0) {
|
||||
$q = "UPDATE members_session SET updated=NOW() WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
|
||||
pg_query($pgconn, $q);
|
||||
|
||||
$q = "SELECT * FROM members_session WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
|
||||
$res = pg_query($pgconn, $q);
|
||||
if ($res && pg_num_rows($res)) {
|
||||
error_log("VALID SESSION *****");
|
||||
return 1; // Session updated
|
||||
} else {
|
||||
error_log("INVALID SESSION *****");
|
||||
//INVALID SESSION DETECTED
|
||||
return -1; // Invalid parameters
|
||||
}
|
||||
}
|
||||
|
||||
if ($create > 0) {
|
||||
// Check session i?
|
||||
$q = "SELECT * FROM members_session WHERE member_id=${uid} AND session<>'" . pg_escape_string($sessionid) . "'";
|
||||
$res = pg_query($pgconn, $q);
|
||||
if ($res && pg_num_rows($res)) {
|
||||
return -2; // Active sessions found
|
||||
}
|
||||
$sess = []; // Do we have the same session already?
|
||||
$q = "SELECT * FROM members_session WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
|
||||
$res = pg_query($pgconn, $q);
|
||||
if ($res && pg_num_rows($res) && $sess = pg_fetch_assoc($res)) {
|
||||
$q = "UPDATE members_session SET updated=NOW() WHERE member_id=${uid} AND session='" . pg_escape_string($sessionid) . "'";
|
||||
pg_query($pgconn, $q);
|
||||
return $sess["id"];
|
||||
}
|
||||
// Create a new session
|
||||
$loc = getRemoteIpAddress();
|
||||
$sess["loc"] = $loc;
|
||||
$sess["member_id"] = $uid;
|
||||
$sess["session"] = $sessionid;
|
||||
$q = "INSERT INTO members_session (loc,member_id,session) VALUES ('" . pg_escape_string($loc) . "',${uid},'" . pg_escape_string($sessionid) . "') RETURNING id";
|
||||
$res = pg_query($pgconn, $q);
|
||||
if ($res && pg_num_rows($res) && $f = pg_fetch_assoc($res)) {
|
||||
if ($f["id"] > 0) {
|
||||
return $f["id"]; // New session created
|
||||
}
|
||||
}
|
||||
return -3; // Failed to create new session
|
||||
}
|
||||
error_log("/php_SessionCheck($uid, $sessionid, $create )");
|
||||
return 0; // No route
|
||||
}
|
||||
|
||||
function php_get_appSettings($in, &$out)
|
||||
{
|
||||
global $pgconn;
|
||||
$out["total_record"] = "0";
|
||||
$res = pg_query($pgconn, "SELECT * FROM app_settings");
|
||||
if ($res && pg_num_rows($res)) {
|
||||
$out["total_record"] = pg_num_rows($res);
|
||||
while ($f = pg_fetch_assoc($res)) {
|
||||
$out[$f["setting_key"]] = $f["value"];
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function php_userlogin($in, &$out)
|
||||
{
|
||||
global $pgconn;
|
||||
$ret = -1;
|
||||
#$q = "SELECT * FROM members WHERE lower(username)=lower('" . pg_escape_string($in["username"]) . "') AND password='" . md5($in["password"]) . "'";
|
||||
$q = "SELECT UPPER( md5( now()::text) ) AS sessionid,m.*,mp.*,m.id AS member_id,mp.id AS member_profile_id FROM members m ";
|
||||
$q .= " LEFT JOIN members_profile mp ON mp.member_id = m.id ";
|
||||
$q .= " WHERE m.status=1 AND LOWER(m.username)=LOWER('" . pg_escape_string($in["username"]) . "') AND m.password2='" . md5($in["password"]) . "'"; //
|
||||
$r = pg_query($pgconn, $q);
|
||||
|
||||
if ($r && pg_num_rows($r) && $out = pg_fetch_assoc($r)) {
|
||||
unset($out["password"]);
|
||||
$q = "DELETE FROM members_session WHERE member_id=" . $out["member_id"];
|
||||
pg_query($pgconn, $q);
|
||||
if (php_SessionCheck($out["member_id"], $out["sessionid"], 1) > 0) {
|
||||
$iny = [];
|
||||
$outy = [];
|
||||
$iny["descision"] = "A10AA01";
|
||||
$iny["member_id"] = $out["member_id"];
|
||||
|
||||
php_getMemberCardDescision($iny, $outy);
|
||||
$out["status"] = "OK";
|
||||
|
||||
/*LOAD THE SESSION INTO OUT now */
|
||||
$q = "SELECT session FROM members_session WHERE member_id=" . $out["member_id"] . " ORDER BY id DESC LIMIT 1";
|
||||
$r = pg_query($pgconn, $q);
|
||||
$f = pg_fetch_assoc($r);
|
||||
$out = array_merge($out, $f);
|
||||
|
||||
php_member_email_calls($in["action"], $out, $out);
|
||||
//===============================================================================================================================
|
||||
$q = "UPDATE members SET last_login = now(),login_failures=0 WHERE id = " . $out["member_id"];
|
||||
pg_query($pgconn, $q);
|
||||
//member_email_calls(ACCOUNT_LOGIN_ALERT,out,out); // ALERT CUSTOMER OF LOGIN
|
||||
$ret = PHP_LOGIN_OK;
|
||||
$out["email_linked"] = "0";
|
||||
$out["account_linked"] = "0";
|
||||
$out["gps_allowed"] = "0";
|
||||
$out["random"] = "0";
|
||||
$out["todays_trips"] = "0";
|
||||
$out["password"] = "REMOVED";
|
||||
$out["php_userlogin"] = true; // check
|
||||
$out["internal_return"] = 100;
|
||||
$out["retval"] = 100;
|
||||
} else {
|
||||
$out["status"] = "Session check failed";
|
||||
}
|
||||
} else {
|
||||
$q = "UPDATE members SET login_failures=login_failures+1 WHERE LOWER(username)=LOWER('" . $in["username"] . "')";
|
||||
pg_query($pgconn, $q);
|
||||
$out["status_message"] = "Invalid Username/Password";
|
||||
}
|
||||
php_get_appSettings($in, $out);
|
||||
//$out["FEED_BOOKING_SHOW"] = '100'; // temporary return to test other parts
|
||||
$out["password"] = "REMOVED";
|
||||
|
||||
ksort($out);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
global $savvyext;
|
||||
$raw_config = file_get_contents('/opt/mainsite/savvyext/etc/savvyext_api.conf');
|
||||
$data_config = explode("\n",$raw_config);
|
||||
$parsed_config = [];
|
||||
$section_config = true;
|
||||
foreach ($data_config as $raw_str) {
|
||||
$str = trim($raw_str);
|
||||
if ($section_config && $str!="" && substr($str,0,1)!='#' && substr($str,-1)==':') {
|
||||
$section_config = false;
|
||||
$section = substr($str,0,strlen($str)-1);
|
||||
$parsed_config[$section] = [];
|
||||
continue;
|
||||
}
|
||||
if ($str!="" && substr($str,0,1)!='{' && substr($str,0,2)!='};') {
|
||||
$pos = strpos($str,'=');
|
||||
if ($pos!==false) {
|
||||
$key = trim(substr($str,0,$pos));
|
||||
$val = trim(substr($str,$pos+1));
|
||||
$pos = strpos($val,'"');
|
||||
if ($pos!==false) {
|
||||
$val = substr($val,$pos+1);
|
||||
$pos = strrpos($val,'"');
|
||||
$val = substr($val,0,$pos);
|
||||
} else {
|
||||
$pos = strrpos($val,';');
|
||||
if ($pos!==false) {
|
||||
$val = substr($val,0,$pos);
|
||||
}
|
||||
}
|
||||
if (isset($section) && $section!="") {
|
||||
$parsed_config[$section][$key] = $val;
|
||||
} else {
|
||||
$parsed_config[$key] = $val;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (substr($str,0,2)=='};') {
|
||||
$section_config = true;
|
||||
}
|
||||
}
|
||||
$savvyext = new class($parsed_config) {
|
||||
public $config;
|
||||
public function __construct($config) {
|
||||
$this->config = $config;
|
||||
}
|
||||
public function cfgReadChar($param) {
|
||||
if (!is_array($this->config)) return NULL;
|
||||
$pos = strpos($param,'.');
|
||||
if ($pos!==false) {
|
||||
$section = trim(substr($param,0,$pos));
|
||||
$key = trim(substr($param,$pos+1));
|
||||
if (array_key_exists($section,$this->config)) {
|
||||
$config = $this->config[$section];
|
||||
if (is_array($config) && array_key_exists($key,$config)) {
|
||||
return $config[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
public function cfgReadLong($param) {
|
||||
return (int)$this->cfgReadChar($param);
|
||||
}
|
||||
public function savvy_api($in) {
|
||||
$postdata = json_encode($in);
|
||||
$ch = curl_init($this->cfgReadChar('savvyext.url'));
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_VERBOSE, false);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'content-type: application/json',
|
||||
'content-length: ' . strlen($postdata),
|
||||
'server-token: ' . $this->cfgReadChar('savvyext.token')
|
||||
]);
|
||||
curl_setopt($ch, CURLOPT_HEADER, false); // Do not show the response headers
|
||||
curl_setopt($ch, CURLOPT_USERPWD, base64_decode($this->cfgReadChar('savvyext.key')));
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
|
||||
$res = curl_exec($ch);
|
||||
//echo "DEBUG: ".$res."=====\n";
|
||||
curl_close($ch);
|
||||
return json_decode($res, true);
|
||||
}
|
||||
};
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 665 B |
Binary file not shown.
|
After Width: | Height: | Size: 628 B |
@@ -0,0 +1,60 @@
|
||||
<!-- HTML for static distribution bundle build -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Swagger UI</title>
|
||||
<link rel="stylesheet" type="text/css" href="swagger-ui.css" >
|
||||
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
|
||||
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
|
||||
<style>
|
||||
html
|
||||
{
|
||||
box-sizing: border-box;
|
||||
overflow: -moz-scrollbars-vertical;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
*,
|
||||
*:before,
|
||||
*:after
|
||||
{
|
||||
box-sizing: inherit;
|
||||
}
|
||||
|
||||
body
|
||||
{
|
||||
margin:0;
|
||||
background: #fafafa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
|
||||
<script src="swagger-ui-bundle.js"> </script>
|
||||
<script src="swagger-ui-standalone-preset.js"> </script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
// Begin Swagger UI call region
|
||||
const ui = SwaggerUIBundle({
|
||||
url: "../swagger.php",
|
||||
dom_id: '#swagger-ui',
|
||||
deepLinking: true,
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIStandalonePreset
|
||||
],
|
||||
plugins: [
|
||||
SwaggerUIBundle.plugins.DownloadUrl
|
||||
],
|
||||
layout: "StandaloneLayout"
|
||||
})
|
||||
// End Swagger UI call region
|
||||
|
||||
window.ui = ui
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
require('../../../adminsavvy/vendor/autoload.php');
|
||||
$openapi = \OpenApi\scan('.');
|
||||
header('Content-Type: application/json');
|
||||
echo $openapi->toJson();
|
||||
?>
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/perl
|
||||
use strict;
|
||||
use warnings FATAL => 'all';
|
||||
use File::Slurp;
|
||||
use File::Copy;
|
||||
use IO::File;
|
||||
use JSON::PP;
|
||||
use Data::Dumper;
|
||||
use MIME::Base64;
|
||||
use Gzip::Faster qw( inflate_raw );
|
||||
use Gearman::Worker;
|
||||
use Gearman::Client;
|
||||
use Storable qw( thaw );
|
||||
use DBI;
|
||||
use DBIx::Dump;
|
||||
use Digest::MD5 qw(md5_hex);
|
||||
use Regexp::Common qw(time);
|
||||
use Syntax::Keyword::Try;
|
||||
|
||||
|
||||
my $dateTimePattern = '%Y-%m-%d %H:%M:%S';
|
||||
my $tracklocation_dir = $ENV{TRACKLOCATION_DIR} or die "Environment variable TRACKLOCATION_DIR not specified";
|
||||
if (('/' ne substr($tracklocation_dir, -length('/')))) {
|
||||
$tracklocation_dir .= '/';
|
||||
}
|
||||
|
||||
my $dbh = DBI->connect ("dbi:CSV:", "", "", {
|
||||
f_dir => $tracklocation_dir,
|
||||
csv_sep_char => "|"
|
||||
});
|
||||
|
||||
my $client = Gearman::Client->new;
|
||||
$client->job_servers('127.0.0.1');
|
||||
|
||||
my $worker = Gearman::Worker->new;
|
||||
$worker->job_servers('127.0.0.1');
|
||||
$worker->register_function(tl_decompress => \&decompress);
|
||||
$worker->work while 1;
|
||||
|
||||
|
||||
sub decompress {
|
||||
my $job = shift;
|
||||
my $workload = $job->arg;
|
||||
my $data = decode_json($workload);
|
||||
my $tlSession = $data->{tl_session};
|
||||
|
||||
print STDERR "[".localtime()."] Start process [$tlSession]\n";
|
||||
|
||||
my @files = read_dir($tracklocation_dir);
|
||||
my @filesFiltered = grep /^(tl_(\d)*\_$tlSession\_(\w|\d|\.)*\.json.lock)$/, @files;
|
||||
|
||||
my $length = scalar @filesFiltered;
|
||||
if ($length == 0 ) {
|
||||
print STDERR "[".localtime()."] End process [$tlSession]\n";
|
||||
return;
|
||||
}
|
||||
|
||||
my $deviceToken="";
|
||||
my $loc="";
|
||||
|
||||
my %sortedFiles = ();
|
||||
foreach(@filesFiltered) {
|
||||
if ($_ =~ /tl_(\d)*\_$tlSession\_(\w+.\w+)\.json/) {
|
||||
$sortedFiles{$_} = $2 + 0;
|
||||
}
|
||||
}
|
||||
my $column = "traked_date|traked_group|member_id|latitude|longitude|speed|timestamp|point_count|tmp\n";
|
||||
|
||||
my (
|
||||
$curline
|
||||
, $fh
|
||||
, $fh_in
|
||||
, $fh_out
|
||||
, $dict
|
||||
, $key
|
||||
, $count
|
||||
, $isValid
|
||||
);
|
||||
my $tmpFileName = lc("tl_tmp_$tlSession.csv");
|
||||
my $csvFileName = $tracklocation_dir.$tmpFileName;
|
||||
my $tmp_file = $tracklocation_dir.lc("tmp_$tlSession.csv");
|
||||
try {
|
||||
open($fh, '>', $csvFileName) or die "Can't open '$csvFileName' !";
|
||||
print $fh $column;
|
||||
close $fh;
|
||||
open($fh, '>>', $csvFileName) or die "Can't open '$csvFileName' !";
|
||||
foreach my $file (sort { $sortedFiles{$a} <=> $sortedFiles{$b} } keys %sortedFiles) {
|
||||
if (-d $tracklocation_dir."debug") {
|
||||
copy $tracklocation_dir.$file, $tracklocation_dir."debug";
|
||||
}
|
||||
my $json_text = read_file($tracklocation_dir.$file);
|
||||
my $data;
|
||||
|
||||
try {
|
||||
$data = decode_json($json_text);
|
||||
} catch {
|
||||
print STDERR "[".localtime()."] Could not decode JSON from file: '".$tracklocation_dir.$file."'\n";
|
||||
};
|
||||
if (!$data) {
|
||||
next;
|
||||
}
|
||||
if(!defined($deviceToken) || !length($deviceToken)) {
|
||||
$deviceToken = $data->{deviceToken};
|
||||
}
|
||||
if(!defined($loc) || !length($loc)) {
|
||||
$loc = $data->{loc};
|
||||
}
|
||||
# my $b64decoded = decode_base64($data->{batch});
|
||||
# print $fh inflate_raw($b64decoded);
|
||||
|
||||
open($fh_out, '>', $tmp_file);
|
||||
my $decoded = decode_base64($data->{batch});
|
||||
try {
|
||||
print $fh_out inflate_raw($decoded);
|
||||
} catch {
|
||||
print STDERR "[".localtime()."] Could not inflate decoded data. Maybe data is not compressed. \n";
|
||||
print $fh_out $decoded;
|
||||
};
|
||||
# print $fh_out inflate_raw(decode_base64($data->{batch}));
|
||||
close $fh_out;
|
||||
$fh_in = new IO::File("< $tmp_file");
|
||||
while (<$fh_in>) {
|
||||
chomp;
|
||||
$curline = $_;
|
||||
$isValid = $curline =~ m/^$RE{time}{strftime}{-pat => $dateTimePattern}/;
|
||||
if ($isValid) {
|
||||
$count = () = $curline =~ /\Q|/g;
|
||||
if (8 != $count) {
|
||||
next;
|
||||
}
|
||||
} else {
|
||||
next;
|
||||
}
|
||||
$key = md5_hex($curline);
|
||||
if (!exists($$dict{$key})) {
|
||||
$$dict{$key} = 1;
|
||||
print $fh $curline."\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
close $fh;
|
||||
|
||||
if (-d $tracklocation_dir."debug") {
|
||||
copy $csvFileName, $tracklocation_dir."debug";
|
||||
}
|
||||
my $tlFilePath = $tracklocation_dir."tl_$tlSession.csv";
|
||||
try {
|
||||
my $query = "SELECT DISTINCT traked_date,traked_group,member_id,latitude,longitude,speed,timestamp,point_count,tmp FROM $tmpFileName";
|
||||
my $sth = $dbh->prepare ($query);
|
||||
$sth->execute ();
|
||||
|
||||
my $out = DBIx::Dump->new('format' => 'csv', # excel or csv
|
||||
'output' => $tlFilePath, # file to save as
|
||||
'sth' => $sth);
|
||||
$out->dump();
|
||||
$sth->finish ();
|
||||
} catch {
|
||||
unlink $tlFilePath;
|
||||
open($fh, '>', $tlFilePath) or die "Can't open '$tlFilePath' !";
|
||||
print $fh "TRAKED_DATE,TRAKED_GROUP,MEMBER_ID,LATITUDE,LONGITUDE,SPEED,TIMESTAMP,POINT_COUNT,TMP";
|
||||
close $fh;
|
||||
};
|
||||
|
||||
if (-d $tracklocation_dir."debug") {
|
||||
copy $tracklocation_dir."tl_$tlSession.csv", $tracklocation_dir."debug";
|
||||
}
|
||||
} catch {
|
||||
print STDERR "[".localtime()."] Something gone wrong. \n";
|
||||
print STDERR "[".localtime()."] $@ \n";
|
||||
} finally {
|
||||
if (fileno($fh)) {
|
||||
try {
|
||||
close $fh;
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
if (fileno($fh_in)) {
|
||||
try {
|
||||
close $fh_in;
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
if (fileno($fh_out)) {
|
||||
try {
|
||||
close $fh_out;
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
try {
|
||||
unlink $tmp_file;
|
||||
unlink $csvFileName;
|
||||
unlink $tracklocation_dir.$tmpFileName;
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
my %payload = (
|
||||
'deviceToken' => $deviceToken,
|
||||
'loc' => $loc,
|
||||
'sessionId' => $tlSession
|
||||
);
|
||||
|
||||
my $arg_p = encode_json(\%payload);
|
||||
my $argref = ref $arg_p ? $arg_p : \$arg_p;
|
||||
try {
|
||||
my $task = Gearman::Task->new("process_tl_batch", $argref, {on_fail => sub { print STDERR "$@", "\n"; },});
|
||||
$client->dispatch_background($task);
|
||||
} catch {
|
||||
print STDERR "[".localtime()."] Run job 'process_tl_batch' failed. \n";
|
||||
print STDERR "[".localtime()."] $@ \n";
|
||||
};
|
||||
|
||||
print STDERR "[".localtime()."] End process [$tlSession]\n";
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
$profile = getenv("SAVVY_PROFILE");
|
||||
if ($profile) {
|
||||
require("../../core/backend.${profile}.php");
|
||||
} else {
|
||||
require('../../core/backend.php');
|
||||
}
|
||||
|
||||
require '../config.php';
|
||||
|
||||
$client = new GearmanClient();
|
||||
$client->addServers($gearmanServers);
|
||||
|
||||
do {
|
||||
echo "[".date("Y-m-d H:i:s")."] Scheduler to check tracklocation files starting\n";
|
||||
|
||||
// Clean old jobs
|
||||
$q = "DELETE FROM tracking_data_job WHERE updated + interval '1 hour' < now()";
|
||||
pg_query($pgconn, $q);
|
||||
|
||||
$files = [];
|
||||
$files = preg_grep('/^(tl_(\w|\.)*\.json)$/', scandir($tracklocation_dir));
|
||||
while(count($files)) {
|
||||
$sortedFiles = [];
|
||||
foreach ($files as $file) {
|
||||
$sortedFiles[$file] = filemtime($tracklocation_dir.$file);
|
||||
}
|
||||
asort($sortedFiles);
|
||||
$files = array_keys($sortedFiles);
|
||||
$file = reset($files);
|
||||
$parts = explode('_', $file);
|
||||
$session = $parts[2];
|
||||
while(strlen($session) == 0 && count($files)) {
|
||||
array_splice($files,0,1);
|
||||
$file = reset($files);
|
||||
$parts = explode('_', $file);
|
||||
$session = $parts[2];
|
||||
}
|
||||
|
||||
if (strlen($session)) {
|
||||
|
||||
$q = "SELECT * FROM tracking_data_job WHERE session = '{$session}'";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
if ($f["locked"] === 'false' || $f["locked"] === 'f' || $f["locked"] === false) {
|
||||
$q = "UPDATE tracking_data_job SET locked = TRUE, updated=now() WHERE id=".$f["id"];
|
||||
} else {
|
||||
$files = preg_grep('/^(tl_(\d)*_((?!'.$session.').)+_(\w|\d|\.)*\.json)$/', scandir($tracklocation_dir));
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
$q = "INSERT INTO tracking_data_job (session, locked) VALUES ('{$session}', TRUE)";
|
||||
}
|
||||
$r = pg_query($pgconn, $q);
|
||||
|
||||
$session_files = array_filter( $files, function ( $item ) use ( $session ) {
|
||||
return strpos($item, $session) !== FALSE;
|
||||
});
|
||||
foreach ($session_files as $sessionFile) {
|
||||
rename($tracklocation_dir.$sessionFile, $tracklocation_dir.$sessionFile.'.lock');
|
||||
}
|
||||
$data = [
|
||||
'tl_session' => $session,
|
||||
];
|
||||
$client->doBackground('tl_decompress', json_encode($data));
|
||||
$files = preg_grep('/^(tl_(\d)*_((?!'.$session.').)+_(\w|\d|\.)*\.json)$/', scandir($tracklocation_dir));
|
||||
}
|
||||
};
|
||||
echo "[".date("Y-m-d H:i:s")."] Scheduler is going to sleep\n";
|
||||
sleep(60); // Sleep for 1 minute between cycles
|
||||
} while(true);
|
||||
echo "[".date("Y-m-d H:i:s")."] Abnormal termination!\n";
|
||||
@@ -0,0 +1,272 @@
|
||||
<?php
|
||||
|
||||
$profile = getenv("SAVVY_PROFILE");
|
||||
if ($profile) {
|
||||
require("../../core/backend.${profile}.php");
|
||||
} else {
|
||||
require('../../core/backend.php');
|
||||
}
|
||||
|
||||
require '../config.php';
|
||||
require 'functions.php';
|
||||
|
||||
$worker= new GearmanWorker();
|
||||
$worker->addServers($gearmanServers);
|
||||
$worker->addFunction('process_tl_batch', 'processTrackLocationBatch');
|
||||
|
||||
$isStoreDebugTrack = file_exists($tracklocation_dir."debug") && is_dir($tracklocation_dir."debug");
|
||||
$batchSize = 1000;
|
||||
|
||||
while (1)
|
||||
{
|
||||
$worker->work();
|
||||
if ($worker->returnCode() != GEARMAN_SUCCESS) break;
|
||||
}
|
||||
|
||||
function processTrackLocationBatch($job) {
|
||||
|
||||
global $tracklocation_dir, $pgconn, $pgconn_gps, $isStoreDebugTrack, $batchSize;
|
||||
|
||||
echo "[".date("Y-m-d H:i:s")."] Process 'Track Location Batch' job starting\n";
|
||||
$workload = $job->workload();
|
||||
$data = json_decode($workload, true);
|
||||
$tlSession = $data['sessionId'];
|
||||
$loc = $data['loc'];
|
||||
$deviceToken = $data['deviceToken'];
|
||||
|
||||
// $pattern = '/^(tl_(\d)*_'.$tlSession.'_(\w|\d|\.)*\.json.lock)$/';
|
||||
$pattern = '/^(tl_'.$tlSession.'\.csv)$/';
|
||||
|
||||
$files = preg_grep($pattern, scandir($tracklocation_dir));
|
||||
if (!$files) {
|
||||
// $q = "UPDATE tracking_data_job SET locked = FALSE, updated=now() WHERE session='{$tlSession}'";
|
||||
// $r = pg_query($pgconn, $q);
|
||||
echo "[".date("Y-m-d H:i:s")."] 'Track Location Batch' job complete\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
$sortedFiles = [];
|
||||
foreach ($files as $file) {
|
||||
$sortedFiles[$file] = filemtime($tracklocation_dir.$file);
|
||||
}
|
||||
|
||||
asort($sortedFiles);
|
||||
$files = array_keys($sortedFiles);
|
||||
|
||||
$rows = [];
|
||||
foreach ( $files as $file) {
|
||||
if($isStoreDebugTrack) {
|
||||
copy($tracklocation_dir . $file, $tracklocation_dir."debug/".$file);
|
||||
echo "[".date("Y-m-d H:i:s")."] Debug track stored : ".$tracklocation_dir."debug/".$file."\n";
|
||||
}
|
||||
|
||||
$fh = fopen($tracklocation_dir . $file, 'r');
|
||||
$rowId = 1;
|
||||
$cntr=0;
|
||||
while (($line = fgetcsv($fh, 10000, ",")) !== FALSE) {
|
||||
if($rowId == 1){ $rowId++; continue; } // continue is used for skip row 1
|
||||
$row = arrayToTrack($line);
|
||||
if (isset($row)) {
|
||||
array_push($rows, $row);
|
||||
$cntr++;
|
||||
if ($cntr >= $batchSize) {
|
||||
processBatch($rows, $tlSession, $deviceToken, $loc);
|
||||
$rows = [];
|
||||
$cntr=0;
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose($fh);
|
||||
}
|
||||
if (count($rows) > 0) {
|
||||
processBatch($rows, $tlSession, $deviceToken, $loc);
|
||||
}
|
||||
|
||||
foreach ( $files as $file) {
|
||||
if ( ! unlink( $tracklocation_dir . $file ) ) {
|
||||
$newFileName = str_ireplace( ".csv", ".csv.done", $file );
|
||||
rename( $tracklocation_dir . $file, $tracklocation_dir . $newFileName );
|
||||
echo( "$tracklocation_dir.$newFileName cannot be deleted, it was renamed to $tracklocation_dir.$newFileName" );
|
||||
}
|
||||
}
|
||||
|
||||
$pattern = '/^(tl_(\d)*_'.$tlSession.'_(\w|\d|\.)*\.json.lock)$/';
|
||||
$files = preg_grep($pattern, scandir($tracklocation_dir));
|
||||
foreach ( $files as $file) {
|
||||
if ( ! unlink( $tracklocation_dir . $file ) ) {
|
||||
$newFileName = str_ireplace( ".lock", ".done", $file );
|
||||
rename( $tracklocation_dir . $file, $tracklocation_dir . $newFileName );
|
||||
echo( "$tracklocation_dir.$newFileName cannot be deleted, it was renamed to $tracklocation_dir.$newFileName" );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$q = "UPDATE tracking_data_job SET locked = FALSE, updated=now() WHERE session='{$tlSession}'";
|
||||
$r = pg_query($pgconn, $q);
|
||||
echo "[".date("Y-m-d H:i:s")."] 'Track Location Batch' job complete\n";
|
||||
}
|
||||
|
||||
function processBatch(&$rows, $tlSession, $deviceToken, $loc) {
|
||||
|
||||
usort($rows, function($a1, $a2) {
|
||||
$v1 = strtotime($a1['traked_date']);
|
||||
$v2 = strtotime($a2['traked_date']);
|
||||
return $v1 - $v2;
|
||||
});
|
||||
|
||||
list ($pass, $device, $session) = checkRequestHeaders(
|
||||
'tracklocation',
|
||||
['member_id' => $rows[0]['member_id']],
|
||||
[
|
||||
"x-session-id" => $tlSession,
|
||||
"x-devicetoken" => $deviceToken
|
||||
],
|
||||
['tracklocation' => 1]
|
||||
);
|
||||
|
||||
$rows[0]["duration"] = 0;
|
||||
$rows[0]["distance"] = 0;
|
||||
$rows[0]["loc"] = $loc;
|
||||
$rows[0]["previous_id"] = "NULL";
|
||||
|
||||
$device_id = (isset($device) && array_key_exists("id",$device) && $device["id"]>0) ? $device["id"] : "NULL";
|
||||
$rows[0]["device_id"] = $device_id;
|
||||
$rows[0] = populateFromPrevious($rows[0]);
|
||||
|
||||
$row = save_tracked($rows[0]);
|
||||
$count = count($rows);
|
||||
|
||||
for ($i = 1; $i < $count; $i++) {
|
||||
if($rows[$i-1]['member_id'] != $rows[$i-1]['member_id']) {
|
||||
list ($pass, $device, $session) = checkRequestHeaders(
|
||||
'tracklocation',
|
||||
['member_id' => $rows[$i]['member_id']],
|
||||
[
|
||||
"x-session-id" => $tlSession,
|
||||
"x-devicetoken" => $deviceToken
|
||||
],
|
||||
['tracklocation' => 1]
|
||||
);
|
||||
$rows[$i]["device_id"] = (isset($device) && array_key_exists("id",$device) && $device["id"]>0) ? $device["id"] : "NULL";
|
||||
} else {
|
||||
$rows[$i]["device_id"] = $rows[$i-1]["device_id"];
|
||||
}
|
||||
|
||||
$rows[$i]["previous_id"] = "NULL";
|
||||
$rows[$i]["duration"] = 0;
|
||||
$rows[$i]["distance"] = 0;
|
||||
$rows[$i]["loc"] = $loc;
|
||||
|
||||
if(!isset($row) || !array_key_exists("id",$row)) {
|
||||
$rows[$i] = populateFromPrevious($rows[$i]);
|
||||
} else {
|
||||
$date1=strtotime($rows[$i-1]["traked_date"]);
|
||||
$date2=strtotime($rows[$i]["traked_date"]);
|
||||
$diff = $date2 - $date1;
|
||||
$duration = $diff * 1000;
|
||||
|
||||
if ($rows[$i]["traked_group"] === $rows[$i-1]["traked_group"] ) {
|
||||
$rows[$i]["previous_id"] = $row["id"];
|
||||
$rows[$i]["duration"] = (int)($duration < 2147483647 ? $duration : 2147483647);
|
||||
$rows[$i]["distance"] = (int)(distance_between_two_gps_coordinates($rows[$i-1]["lat"],$rows[$i-1]["lng"],$rows[$i]["lat"],$rows[$i]["lng"]) * 1000);
|
||||
}
|
||||
}
|
||||
$row = save_tracked($rows[$i]);
|
||||
}
|
||||
}
|
||||
|
||||
function arrayToTrack($row) {
|
||||
$track = null;
|
||||
$row = array_filter($row, function($value) { return !is_null($value) && $value !== ''; });
|
||||
|
||||
if ( count( $row ) === 9 && intval( $row[2] ) > 0 && validateDate($row[0])) {
|
||||
$track = [];
|
||||
$track["traked_date"] = $row[0];
|
||||
$track["traked_group"] = $row[1];
|
||||
$track["member_id"] = $row[2];
|
||||
$track["lat"] = floatval( $row[3] );
|
||||
$track["lng"] = floatval( $row[4] );
|
||||
$track["speed"] = floatval( $row[5] ) < 0 ? 0 : floatval( $row[5] );
|
||||
$track["timestamp"] = $row[6];
|
||||
$track["point_count"] = $row[7];
|
||||
$track["sync_saved"] = $row[8];
|
||||
}
|
||||
return $track;
|
||||
}
|
||||
|
||||
|
||||
function distance_between_two_gps_coordinates($lat1, $lon1, $lat2, $lon2) {
|
||||
return acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon2 - $lon1))) * 6371;
|
||||
}
|
||||
|
||||
function validateDate($date, $format = 'Y-m-d H:i:s'){
|
||||
$d = DateTime::createFromFormat($format, $date);
|
||||
return $d && $d->format($format) === $date;
|
||||
}
|
||||
|
||||
function populateFromPrevious($row) {
|
||||
|
||||
global $pgconn_gps;
|
||||
|
||||
$device_id = $row["device_id"];
|
||||
$ttimeStr = "to_timestamp('".$row["traked_date"]."', 'YYYY-MM-DD HH24:MI:SS')";
|
||||
|
||||
$q = "SELECT id , lat, lng, ttime, traked_group ";
|
||||
$q.= "FROM members_tracking ";
|
||||
$q.= "WHERE member_id=".$row['member_id']." AND ttime < ".$ttimeStr." AND ";
|
||||
$q.= ($device_id == "NULL" ? "device_id IS NULL" : "device_id=${device_id}");
|
||||
$q.= " ORDER BY ttime DESC LIMIT 1";
|
||||
$r = pg_query($pgconn_gps, $q);
|
||||
|
||||
$row["previous_id"] = "NULL";
|
||||
$row["duration"] = 0;
|
||||
$row["distance"] = 0;
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
$date1=strtotime($f["ttime"]);
|
||||
$date2=strtotime($row["traked_date"]);
|
||||
$diff = $date2 - $date1;
|
||||
$duration = $diff * 1000;
|
||||
if ($row["traked_group"] === $f["traked_group"] ) {
|
||||
$row["previous_id"] = $f["id"];
|
||||
$row["duration"] = (int)($duration < 2147483647 ? $duration : 2147483647);
|
||||
$row["distance"] = (int)(distance_between_two_gps_coordinates($f["lat"],$f["lng"],$row["lat"],$row["lng"]) * 1000);
|
||||
}
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
function save_tracked($in) {
|
||||
global $pgconn_gps;
|
||||
|
||||
$ttimeStr = "to_timestamp('".$in["traked_date"]."', 'YYYY-MM-DD HH24:MI:SS')";
|
||||
|
||||
$result = [];
|
||||
|
||||
if ($in["member_id"]>0 && $in["lng"]!="" && $in["lat"]!="") {
|
||||
$q = "INSERT INTO members_tracking (member_id, traked_group, speed, lat, lng, gps, ttime, loc, created, device_id, distance, duration, previous_id) ";
|
||||
$q .= " VALUES(";
|
||||
$q .= $in["member_id"] . ", ";
|
||||
$q .= "'".$in["traked_group"] . "', ";
|
||||
$q .= $in["speed"] . ", ";
|
||||
$q .= $in["lat"] . ", ";
|
||||
$q .= $in["lng"] . ", ";
|
||||
$q .= "ST_SetSRID(ST_MakePoint(" . $in["lng"] . "," . $in["lat"] . "),4326)::geography". ", ";
|
||||
$q .= $ttimeStr . ", ";
|
||||
$q .= "'".$in["loc"] . "', ";
|
||||
$q .= "now(), ";
|
||||
$q .= $in["device_id"]. ", ";
|
||||
$q .= $in["distance"] . ", ";
|
||||
$q .= $in["duration"] . ", ";
|
||||
$q .= ($in["previous_id"] ? $in["previous_id"]: "NULL");
|
||||
$q .= ") RETURNING *";
|
||||
$r = pg_query( $pgconn_gps, $q );
|
||||
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
|
||||
$result = $f;
|
||||
} else {
|
||||
error_log(pg_last_error($pgconn_gps));
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
include '../../../core/backend.php';
|
||||
include_once '../../config.php';
|
||||
include_once '../../constants.php';
|
||||
include '../../formarter.php';
|
||||
include_once 'user_cards.php';
|
||||
|
||||
$card_type = 22000;
|
||||
#$card_type = 33000;
|
||||
$card_type = 55000;
|
||||
$member_id = 1;
|
||||
$card_count = 10;
|
||||
$in = [
|
||||
'member_id' => $member_id,
|
||||
'card_type' => $card_type,
|
||||
'card_count' => $card_count,
|
||||
];
|
||||
loadSliderCard($in, $out);
|
||||
var_dump($out);
|
||||
echo "All good";
|
||||
@@ -0,0 +1,307 @@
|
||||
<?php
|
||||
|
||||
/*Default no bahaviour attached*/
|
||||
function behaviour_BH0001($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Users selects 'maybe later' to cc permision or user hits 'disconnect' */
|
||||
function behaviour_BH0002($in, $out)
|
||||
{
|
||||
global $pgconn;
|
||||
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
//$out = $in; // loadMemberDescisionData(member_id, $out);
|
||||
$query = "SELECT count(*) AS members_bank_count FROM members_bank_accounts WHERE member_id = " . $member_id . "";
|
||||
$r = pg_query($pgconn, $query);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
if ($in["last_acct"] == "" & $f["members_bank_count"] == 0) {
|
||||
// no account data
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Users selects 'maybe later' to gmail permision*/
|
||||
function behavior_BH0003($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
|
||||
$query = "SELECT count(id) as email_pull_atempt FROM oauth2_pull_jobs WHERE member_id = " . $member_id . "";
|
||||
$r = pg_query($pgconn, $query);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
if ($in["last_email"] == "" & $f["email_pull_atempt"] == 0) {
|
||||
// no account data
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*No Credit Card & Email','Users selects ''maybe later'' to gmail & cc permision*/
|
||||
function behavior_BH0004($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
|
||||
$query = "SELECT count(id) as email_pull_atempt FROM oauth2_pull_jobs WHERE member_id = " . $member_id . "";
|
||||
$r = pg_query($pgconn, $query);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
if ($in["last_email"] == "" & $f["email_pull_atempt"] == 0) {
|
||||
// no account data
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
//
|
||||
|
||||
/*CC & email synced BUT no Transactions or Transactions cease for 7 days*/
|
||||
function behavior_BH0005($member, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
weeklyMemberSpending($member, $out);
|
||||
if ($out["weekly_total"] == 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*User didn't set budget on sign-up*/
|
||||
function behavior_BH0006($member, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$out = $member;
|
||||
if ($out["max_budget"] == 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Timezone hits a certain time, card displays for 1 hour.*/
|
||||
function behavior_BH0007($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Users spending exceeds budget, card displayed on Tuesdays & Fridays*/
|
||||
function behavior_BH0008($member, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
weeklyMemberSpending($member, $out);
|
||||
if ($out["over_spending"] > 0 && $out["under_spending"] == 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Users spending falls below budget, card displayed on Tuesdays & Fridays*/
|
||||
function behavior_BH0009($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
weeklyMemberSpending($member, $out);
|
||||
if ($out["under_spending"] > 0 && $out["over_spending"] == 0 && $out["user_budget_percentbelow"] > 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Use selects 'allow' to GPS permission*/
|
||||
function behavior_BH0010($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
if (enableGPS($member_id)) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*CC Synced, Email Synced, Transations coming through, GPS Sycned*/
|
||||
function behavior_BH0011($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
|
||||
$out = $in; // loadMemberDescisionData(member_id, $out);
|
||||
$member_id = $in['id'];
|
||||
if (enableGPS($member_id) == false && $out["last_acct"] != "" && $out["last_email"] != "") {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Users selects 'no' to GPS permission*/
|
||||
function behavior_BH0013($in, $out)
|
||||
{
|
||||
// for version 01, the only way is if I see no GPS entery
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
if (enableGPS($member_id) == false) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Back office identifies a 'Uber' receipt*/
|
||||
function behavior_BH0012($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
$member_id = $in['id'];
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*User Spending Above Average*/
|
||||
function behavior_BH0014($member, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
weeklyMemberSpending($member, $out);
|
||||
if ($out["user_budget_percentabove"] > 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*User Spending Below Average*/
|
||||
function behavior_BH0015($member, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
weeklyMemberSpending($member, $out);
|
||||
if ($out["user_budget_percentbelow"] > 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Show if The User Country is Known*/
|
||||
function behavior_BH0016($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
/* $member_id = $in['id'];
|
||||
detectMemberLocation($member_id, $out); */
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*Show if The User Country Not Known*/
|
||||
function behavior_BH0017($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
/* $member_id = $in['id'];
|
||||
detectMemberLocation($member_id, $out); */
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/*No Budgt Set*/
|
||||
function behavior_BH0018($in, $out)
|
||||
{
|
||||
$ret = CARD_ADD_DENIED;
|
||||
/* $member_id = $in['id'];
|
||||
detectMemberLocation($member_id, $out); */
|
||||
if ($in["min_budget"] + $in["max_budget"] == 0) {
|
||||
$ret = CARD_ADD_ALLOWED;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
function enableGPS($member_id)
|
||||
{
|
||||
global $pgconn_gps;
|
||||
$r = pg_query($pgconn_gps, "SELECT count(*) as num FROM members_tracking WHERE member_id=" . $member_id . "");
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
if ($f['num'] > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function weeklyMemberSpending($member, &$out)
|
||||
{
|
||||
{
|
||||
global $pgconn;
|
||||
$member_id = $member['id'];
|
||||
$out["over_spending"] = "0";
|
||||
$out["under_spending"] = "0";
|
||||
$out["weekly_total"] = "0";
|
||||
|
||||
$total_bank = 0;
|
||||
$total_email = 0;
|
||||
$total_weekly_spend = 0;
|
||||
|
||||
// loadMemberDescisionData( member_id, out);
|
||||
$out["user_budget_percentbelow"] = "0";
|
||||
$out["user_budget_percentabove"] = "0";
|
||||
|
||||
// LOCAL AVERAGE -----------------------------------------------
|
||||
$out["user_less_localavergperm"] = "0";
|
||||
$out["user_more_localavergperm"] = "0"; // we start with zero
|
||||
$out["population_average"] = 0; // we start with zero
|
||||
$out["member_average"] = 0; // we start with zero
|
||||
|
||||
$population = fetchRow("SELECT avg(amount) *0.01 AS population_average FROM members_bankimport WHERE category IN (SELECT category FROM activity_listcategory) AND currency='USD'");
|
||||
if ($population) {
|
||||
$out['population_average'] = $population['population_average'];
|
||||
}
|
||||
$member_average = fetchRow("SELECT avg(amount) *0.01 AS member_average FROM members_bankimport WHERE category IN (SELECT category FROM activity_listcategory) AND member_id = " . $member_id . " AND currency='USD'");
|
||||
if ($member_average) {
|
||||
$out['member_average'] = $member_average['member_average'];
|
||||
}
|
||||
if ($out['member_average'] > 0 && $out['member_average'] > $out['population_average']) {
|
||||
$out["user_more_localavergperm"] = $out['member_average'] - $out['population_average'];
|
||||
}
|
||||
if ($out['member_average'] > 0 && $out['member_average'] < $out['population_average']) {
|
||||
$out["user_less_localavergperm"] = $out['population_average'] - $out['member_average'];
|
||||
}
|
||||
// END LOCAL AVERAGE -------------------------------------
|
||||
|
||||
$total_weekly_budget = ($member["min_budget"] + $member["max_budget"]) / 200;
|
||||
|
||||
// bank import total
|
||||
$bankImport = fetchRow("SELECT * FROM (SELECT round(0.01*sum(amount),2) AS total FROM members_bankimport
|
||||
WHERE member_id= " . $member_id . " AND LOWER(category) IN (SELECT LOWER(category) FROM activity_listcategory)
|
||||
AND date_trunc('day', time) > (current_date - 8)
|
||||
AND date_trunc('day', time) < current_date) AS c WHERE c.total IS NOT NULL");
|
||||
|
||||
if ($bankimport) {
|
||||
$total_bank = $bankImport["total"];
|
||||
}
|
||||
|
||||
$totalEmail = fetchRow("SELECT * FROM (SELECT round(sum(a.cost),2) AS total
|
||||
FROM parsedemail_item a, trackedemail_item b WHERE b.id=a.trackedemail_item_id
|
||||
AND b.member_id= " . $member_id . " AND a.dup_id IS NULL AND date_trunc('day', a.travel_date_end) > (current_date - 8)
|
||||
AND date_trunc('day', a.travel_date_end) < current_date) AS c WHERE c.total IS NOT NULL");
|
||||
|
||||
if ($totalEmail) {
|
||||
$total_email = $totalEmail["total"];
|
||||
}
|
||||
|
||||
$total_weekly_spend = $total_bank + $total_email;
|
||||
|
||||
if ($total_weekly_spend > $total_weekly_budget && $total_weekly_budget > 0) {
|
||||
$over_spending = $total_weekly_spend - $total_weekly_budget;
|
||||
$out["over_spending"] = $over_spending;
|
||||
$out["user_budget_percentabove"] = ($over_spending / $total_weekly_budget);
|
||||
}
|
||||
|
||||
if ($total_weekly_budget > $total_weekly_spend && $total_weekly_budget > 0) {
|
||||
$under_spending = $total_weekly_budget - $total_weekly_spend;
|
||||
$out["under_spending"] = $under_spending;
|
||||
$out["user_budget_percentbelow"] = ($under_spending / $total_weekly_budget);
|
||||
}
|
||||
|
||||
$out["weekly_total"] = $total_weekly_spend;
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function detectMemberLocation($member_id, &$out)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
<?php
|
||||
|
||||
function loadSliderCard($in, &$out)
|
||||
{
|
||||
global $pgconn;
|
||||
$retvel = 0;
|
||||
$total_record = 0;
|
||||
$status = 'OK';
|
||||
$card_type = $in['card_type'];
|
||||
$card_count = $in['card_count'];
|
||||
$member_id = $in['member_id'];
|
||||
$out['status'] = $status;
|
||||
$out['session_valid'] = '';
|
||||
$member = getMember($member_id);
|
||||
if ($member) {
|
||||
$survey = getCardBySurvey($member);
|
||||
getCardsByType($out, $member, $card_type, $card_count);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function getCardsByType(&$out, $member, $card_type, $limit = 10)
|
||||
{
|
||||
global $pgconn;
|
||||
$member_id = $member['id'];
|
||||
switch ($card_type) {
|
||||
case 33000:
|
||||
$query = "SELECT ca.id AS assign_id, ca.subscribe, a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data,adr.latitude,adr.longitude,
|
||||
EXTRACT(DAY FROM (CASE WHEN a.card_expiration IS NULL THEN now() -now() ELSE a.card_expiration -now() END)) AS expr_val, a.card_canexpire
|
||||
FROM main_cards a
|
||||
LEFT JOIN card_actions b ON (b.id=a.card_action_id)
|
||||
LEFT JOIN address adr ON adr.id = a.card_location
|
||||
LEFT JOIN members_card_assign ca ON ca.card_id=a.id AND ca.member_id=" . $member_id . " AND ca.status=1
|
||||
WHERE a.status = 1 AND a.deleted IS NULL AND a.button1_action IN ('GOOFFERS','CARPOOL') ORDER BY a.card_order ASC";
|
||||
break;
|
||||
case 22000:
|
||||
$query = "SELECT ca.id AS assign_id, ca.subscribe, a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data,adr.latitude,adr.longitude,ca.trigger_key,ca.message,ca.cat,
|
||||
EXTRACT(DAY FROM (CASE WHEN a.card_expiration IS NULL THEN now() -now() ELSE a.card_expiration -now() END)) AS expr_val, a.card_canexpire
|
||||
FROM members_card_assign ca
|
||||
LEFT JOIN main_cards a ON a.id=ca.card_id
|
||||
LEFT JOIN address adr ON adr.id = a.card_location
|
||||
LEFT JOIN card_actions b ON (b.id=a.card_action_id)
|
||||
WHERE ca.member_id = " . $member_id . " AND ca.status =1 AND a.status=1 AND show_area IN (" . CARD_LOCATION_DEFAULT . "," . CARD_LOCATION_MAINFEED . ") AND a.deleted IS NULL AND ca.subscribe IS NULL AND ca.completed IS NULL ORDER BY a.card_order ASC";
|
||||
break;
|
||||
|
||||
case 55000:
|
||||
$query = "SELECT ca.id AS assign_id, ca.subscribe, a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data,adr.latitude,adr.longitude,ca.trigger_key,ca.message,ca.cat,
|
||||
EXTRACT(DAY FROM (CASE WHEN a.card_expiration IS NULL THEN now() -now() ELSE a.card_expiration -now() END)) AS expr_val, a.card_canexpire
|
||||
FROM members_card_assign ca
|
||||
LEFT JOIN main_cards a ON a.id=ca.card_id
|
||||
LEFT JOIN address adr ON adr.id = a.card_location
|
||||
LEFT JOIN card_actions b ON (b.id=a.card_action_id)
|
||||
WHERE ca.member_id = " . $member_id . " AND a.button1_action IN ('GOOFFERS') AND ca.subscribe IS NOT NULL ORDER BY ca.subscribe ASC";
|
||||
break;
|
||||
|
||||
case 11000:
|
||||
$query = "SELECT a.*, a.id AS card_id,b.name AS card_action_name,b.type AS card_action_type,b.data AS card_action_data
|
||||
FROM main_cards a LEFT JOIN card_actions b ON (b.id=a.card_action_id)
|
||||
WHERE a.status = 1 AND a.deleted IS NULL ORDER BY RANDOM()";
|
||||
break;
|
||||
}
|
||||
$deal_card_count = 0;
|
||||
$survey_card_count = 0;
|
||||
$blog_card_count = 0;
|
||||
$r = pg_query($pgconn, $query);
|
||||
$out['total_record_raw'] = pg_num_rows($r);
|
||||
$out['total_record'] = pg_num_rows($r);
|
||||
$out['retval'] = PHP_API_OK;
|
||||
$out['internal_return'] = PHP_API_OK;
|
||||
$query = $query . " LIMIT " . $limit . "";
|
||||
$r = pg_query($pgconn, $query);
|
||||
$result = [];
|
||||
if ($r && $total_record_raw = pg_num_rows($r)) {
|
||||
$ic = 0;
|
||||
while ($f = pg_fetch_assoc($r)) {
|
||||
$test_card_allowed = CARD_ADD_ALLOWED;
|
||||
if ($card_type == 22000) {
|
||||
$test_card_allowed = verifyMemberCardDescision($f, $member, $out);
|
||||
}
|
||||
$card_country_allow = true;
|
||||
|
||||
if ($f["card_country"] != "") {
|
||||
$card_country_allow = false;
|
||||
|
||||
if ($f["card_country"] == $member["country"]) {
|
||||
$card_country_allow = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$count_block = false;
|
||||
|
||||
// let see i card expired
|
||||
$expr_value = $f["expr_val"];
|
||||
if ($f["card_canexpire"] == 1 && $expr_value < 0) {
|
||||
$count_block = true;
|
||||
} else {
|
||||
if ($card_type == 22000) {
|
||||
|
||||
if ($f["button1_action"] == "GOOFFERS") {
|
||||
if ($deal_card_count > 0) {
|
||||
$count_block = true;
|
||||
}
|
||||
if ($f["card_country"] == "" || $f["card_country"] == $member["country"]) {
|
||||
$deal_card_count++;
|
||||
}
|
||||
}
|
||||
|
||||
if ($f["button1_action"] == "SURVEYA") {
|
||||
if ($fsurvey_card_count > 0) {
|
||||
$count_block = true;
|
||||
}
|
||||
$survey_card_count++;
|
||||
}
|
||||
|
||||
if ($f["button1_action"] == "BLOGCARD") {
|
||||
if ($blog_card_count > 0) {
|
||||
$count_block = true;
|
||||
}
|
||||
$blog_card_count++;
|
||||
}
|
||||
|
||||
}
|
||||
} //card is not expired
|
||||
|
||||
if (CARD_ADD_ALLOWED == $test_card_allowed && true == $card_country_allow && false == $count_block) {
|
||||
$suffix = str_pad($ic, 5, '0', STR_PAD_LEFT);
|
||||
//fillSuffixCard($out, $f, $suffix);
|
||||
$out['name_' . $suffix] = $f['name'];
|
||||
$out['assign_id_' . $suffix] = $f['assign_id'];
|
||||
$out['card_id_' . $suffix] = $f['card_id'];
|
||||
$out['can_save_' . $suffix] = $f['can_save'];
|
||||
$out['short_title_' . $suffix] = $f['short_title'];
|
||||
$out['title_' . $suffix] = $f['short_title'];
|
||||
$out['background_picture_' . $suffix] = $f['background_picture'];
|
||||
$out['button1_' . $suffix] = $f['button1'];
|
||||
$out['button1_text_' . $suffix] = $f['button1_text'];
|
||||
$out['button1_action_' . $suffix] = $f['button1_action'];
|
||||
$out['expires_' . $suffix] = $f['card_expiration'];
|
||||
$out['template_' . $suffix] = $f['template'];
|
||||
$out['card_canexpire_' . $suffix] = $f['card_canexpire'];
|
||||
$out['card_action_type_' . $suffix] = $f['card_action_type'];
|
||||
$out['card_action_data_' . $suffix] = $f['card_action_data'];
|
||||
$out['titleshow_' . $suffix] = $f['titleshow'];
|
||||
$out['multiple_answer_' . $suffix] = $f['multiple_answer'];
|
||||
$out['use_short_title_' . $suffix] = $f['use_short_title'];
|
||||
$out['target_key_' . $suffix] = $f['target_key'];
|
||||
$out['target_text_' . $suffix] = $f['target_text'];
|
||||
$out['description_' . $suffix] = $f['description'];
|
||||
$out['long_description_' . $suffix] = $f['long_description'];
|
||||
$out['card_behavior_' . $suffix] = $f['card_behavior'];
|
||||
$out['card_type_' . $suffix] = $f['card_type'];
|
||||
$out['card_time_' . $suffix] = $f['card_time'];
|
||||
$out['card_country_' . $suffix] = $f['card_country'];
|
||||
$out['card_location_' . $suffix] = $f['card_location'];
|
||||
$out['latitude_' . $suffix] = $f['latitude'];
|
||||
$out['longitude_' . $suffix] = $f['longitude'];
|
||||
$out['card_order_' . $suffix] = $f['card_order'];
|
||||
$out['background_color_' . $suffix] = $f['background_color'];
|
||||
$out['blog_id_' . $suffix] = $f['blog_id'];
|
||||
$out['expiration_' . $suffix] = $f['expiration'];
|
||||
if ($f["button1_action"] == "CARPOOL") {
|
||||
|
||||
$carPool = fetchRow("SELECT * FROM members_carpool_friends WHERE carpool_id IN (select id from members_carpool WHERE member_id = " . $member_id . ") AND status = 1");
|
||||
|
||||
if ($carPool && $carPool['added']) {
|
||||
$out['subscribe_' . $suffix] = $carPool["added"];
|
||||
} else {
|
||||
$out['subscribe_' . $suffix] = "";
|
||||
}
|
||||
|
||||
} else {
|
||||
$out['subscribe_' . $suffix] = $f["subscribe"];
|
||||
}
|
||||
$ic++;
|
||||
}
|
||||
}
|
||||
$out['total_record'] = $ic;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function verifyMemberCardDescision($cardData, $memberData, &$out)
|
||||
{
|
||||
$permCard = CARD_ADD_ALLOWED;
|
||||
$behaviour = $cardData["card_behavior"];
|
||||
|
||||
if (function_exists("behaviour_" . $behaviour)) {
|
||||
$permCard = call_user_func("behaviour_" . $behaviour, $memberData, $out);
|
||||
} else {
|
||||
$permCard = CARD_ADD_ALLOWED;
|
||||
}
|
||||
|
||||
return $permCard;
|
||||
}
|
||||
|
||||
function saveDashCard($in, &$out)
|
||||
{
|
||||
$ret = PHP_API_BAD_PARAM;
|
||||
$member_id = $in['member_id'];
|
||||
$card_id = $in['card_id'];
|
||||
$out["saved_card_id"] = "0";
|
||||
$saveCard = fetchRow("SELECT id FROM member_saved_cards WHERE member_id=" . $member_id . " AND card_id=" . $card_id . "");
|
||||
|
||||
if (empty($saveCard)) {
|
||||
$insertCard = "INSERT INTO member_saved_cards (member_id,card_id) VALUES (" . $member_id . "," . $card_id . ") RETURNING id";
|
||||
$out["saved_card_id"] = insertQuery($insertCard);
|
||||
if ($out['saved_card_id'] > 0) {
|
||||
$ret = PHP_API_OK;
|
||||
}
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
function loadSavedCard($in, &$out)
|
||||
{
|
||||
$ret = PHP_API_BAD_PARAM;
|
||||
|
||||
$member_id = $in['member_id'];
|
||||
|
||||
$out["total_record"] = 0;
|
||||
$out['session_valid'] = '';
|
||||
$out['internal_return'] = PHP_API_OK;
|
||||
$saveCards = selectData("SELECT m.id AS saved_card_id, mc.*,mc.id AS card_id FROM member_saved_cards m LEFT JOIN main_cards mc ON m.card_id = mc.id WHERE m.member_id = " . $member_id . " AND m.status = 1");
|
||||
if ($saveCards != null) {
|
||||
$out["total_record"] = pg_num_rows($saveCards);
|
||||
$ic = 0;
|
||||
|
||||
while ($f = pg_fetch_assoc($saveCards)) {
|
||||
$suffix = str_pad($ic, 5, '0', STR_PAD_LEFT);
|
||||
$out['name_' . $suffix] = $f['name'];
|
||||
$out['short_title_' . $suffix] = $f['short_title'];
|
||||
$out['title_' . $suffix] = $f['title'];
|
||||
$out['description_' . $suffix] = $f['description'];
|
||||
$out['short_title_' . $suffix] = $f['short_title'];
|
||||
$out['title_' . $suffix] = $f['short_title'];
|
||||
$out['background_picture_' . $suffix] = $f['background_picture'];
|
||||
$out['button1_' . $suffix] = $f['button1'];
|
||||
$out['button1_text_' . $suffix] = $f['button1_text'];
|
||||
$out['button1_action_' . $suffix] = $f['button1_action'];
|
||||
$out['can_save_' . $suffix] = $f['can_save'];
|
||||
$out['card_id_' . $suffix] = $f['card_id'];
|
||||
$out['template_' . $suffix] = $f['template'];
|
||||
$out['card_canexpire_' . $suffix] = $f['card_canexpire'];
|
||||
$out['card_canexpire_' . $suffix] = $f['card_canexpire'];
|
||||
$out['expires_' . $suffix] = $f['card_expiration'];
|
||||
//$out['card_action_type_' . $suffix] = $f['card_action_type'];
|
||||
//$out['card_action_data_' . $suffix] = $f['card_action_data'];
|
||||
$out['titleshow_' . $suffix] = $f['titleshow'];
|
||||
$ic++;
|
||||
}
|
||||
}
|
||||
$ret = PHP_API_OK;
|
||||
$out["status"] = "OK";
|
||||
return $ret;
|
||||
}
|
||||
|
||||
function userTrackCardClick($in, &$out)
|
||||
{
|
||||
$ret = PHP_API_BAD_PARAM;
|
||||
$member_id = $in['member_id'];
|
||||
$card_id = $in['card_id'];
|
||||
|
||||
processCard($in, $out); // see if cleanout is needed
|
||||
|
||||
$insertCard = "INSERT INTO members_cardclicktrack (member_id,card_id) VALUES (" . $member_id . "," . $card_id . ") RETURNING id";
|
||||
$out["card_track_id"] = insertQuery($insertCard);
|
||||
if ($out['card_track_id'] > 0) {
|
||||
$ret = PHP_API_OK;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
function processCard($in, &$out)
|
||||
{
|
||||
|
||||
$ret = PHP_API_BAD_PARAM;
|
||||
$member_id = $in['member_id'];
|
||||
$card_id = $in['card_id'];
|
||||
|
||||
$card = fetchRow("SELECT id,button1_action,title,expiration FROM main_cards WHERE id=" . $card_id . "");
|
||||
if ($card) {
|
||||
if ($card["button1_action"] == "CARPOOL") {
|
||||
updateQuery("UPDATE members_card_assign SET status = 0,completed=now(),updated=now() WHERE card_id=" . $card_id . " AND member_id=" . $member_id . "");
|
||||
}
|
||||
|
||||
if ($card["expiration"] == 100) {
|
||||
updateQuery("UPDATE members_card_assign SET status = 0,updated=now() WHERE card_id=" . $card_id . " AND member_id=" . $member_id . "");
|
||||
}
|
||||
|
||||
// let us see if this is a dynamic card
|
||||
$assignCard = fetchRow("SELECT mca.id AS assign_id,mc.dynamic_key,et.expiration,EXTRACT(EPOCH FROM now() - mca.updated)/3600 AS card_age
|
||||
FROM members_card_assign mca LEFT JOIN main_cards mc ON mc.id=mca.card_id LEFT JOIN email_trigger et ON et.dynamic_key = mc.dynamic_key
|
||||
WHERE mca.member_id =" . $member_id . " AND mca.trigger_key IS NOT NULL AND mca.card_id = " . $card_id . " ");
|
||||
if ($assignCard) {
|
||||
if ($assignCard["expiration"] == "EXP00002") {
|
||||
// rule 1 expire on first contact
|
||||
updateQuery("UPDATE members_card_assign SET status = 0 WHERE id= " . $assignCard['assign_id'] . " AND member_id=" . $member_id . "");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
function userCardAdd($member_id, $card_id, &$out)
|
||||
{
|
||||
global $pgconn;
|
||||
$ret = PHP_API_BAD_PARAM;
|
||||
$assignCard = fetchRow("SELECT id AS assign_id,status AS card_status FROM members_card_assign WHERE card_id=" . $card_id . " AND member_id=" . $member_id . " AND status IN (0,1)");
|
||||
|
||||
if ($assignCard) {
|
||||
if ($assignCard['card_status'] == 0) {
|
||||
$click = fetchRow("SELECT expiration FROM members_cardclicktrack mc LEFT JOIN main_cards a ON a.id=mc.card_id WHERE a.id=" . $card_id . " AND mc.member_id=" . $member_id . " LIMIT 1");
|
||||
if ($click && $click['expiration'] == 0) {
|
||||
$out["status"] = "This card is expired";
|
||||
} else {
|
||||
$ret = PHP_API_OK;
|
||||
}
|
||||
$ret = updateQuery("UPDATE members_card_assign SET status = 1, updated=NOW() WHERE id = " . $assignCard['assign_id'] . " AND member_id = " . $member_id . "");
|
||||
|
||||
} else {
|
||||
$out["status"] = "This card was already added";
|
||||
}
|
||||
} else {
|
||||
//insert assign card
|
||||
$insertCard = "INSERT INTO members_card_assign (card_id,member_id) VALUES (" . $card_id . "," . $member_id . ") RETURNING id";
|
||||
$out['id'] = insertQuery($insertCard);
|
||||
if ($out['id'] > 0) {
|
||||
$ret = PHP_API_OK;
|
||||
}
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
function getCardBySurvey($member)
|
||||
{
|
||||
global $pgconn;
|
||||
$member_id = $member['id'];
|
||||
$q = "SELECT card_id FROM members_onboarding_survey mos
|
||||
LEFT JOIN onboarding_survey_cards ca ON ca.answers_key = mos.answers_key
|
||||
LEFT JOIN main_cards a ON a.id=ca.card_id
|
||||
WHERE mos.member_id = " . $member_id . " AND a.status = 1
|
||||
AND card_id NOT IN (SELECT card_id FROM members_card_assign WHERE member_id =" . $member_id . " AND status=1)
|
||||
GROUP BY card_id";
|
||||
$r = pg_query($pgconn, $q);
|
||||
if ($r && pg_num_rows($r) && $f = pg_fetch_assoc($r)) {
|
||||
return $f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user