Add user roles management page and update user permissions handling

- Created a new `user_roles.php` file for managing user roles and permissions.
- Implemented pagination, filtering, and sorting for user roles.
- Updated `users.php` to use the new authorization structure for permissions.
- Changed API version from v1 to v2 in `users.php` for user data retrieval.
- Modified `webhook_mollie.php` to include account hierarchy in license creation.
- Refactored invoice generation and email sending logic in `webhook_mollie.php`.
- Introduced a new `webhook_paypal.php` file to handle PayPal webhook notifications.
- Implemented payment status updates and license creation logic in `webhook_paypal.php`.
- Added helper functions for PayPal webhook signature verification and access token retrieval.
This commit is contained in:
“VeLiTi”
2026-01-29 19:31:10 +01:00
199 changed files with 19222 additions and 3386 deletions

BIN
api/.DS_Store vendored

Binary file not shown.

View File

@@ -15,7 +15,7 @@ $user_data = $stmt->fetch();
//Define User data
$partnerhierarchy = $user_data['partnerhierarchy'];
$permission = userRights($user_data['view']);
$profile= getProfile($user_data['settings'],$permission);
$profile= getUserPermissions($pdo, $user_data['id']);
$username = $user_data['username'];
$useremail = $user_data['email'];
$servicekey = $user_data['service'];

View File

@@ -56,7 +56,9 @@ if (!empty($post_content['sn']) && !empty($post_content['testdetails'])) {
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
$user = $username;
$account = $partnerhierarchy; //string
$current_date = date("Y-m-d");
$service_date = date("Y-m-d", strtotime("+" . SERVICE_MONTHS . " months"));
$warranty_date = date("Y-m-d", strtotime("+" . WARRANTY_MONTHS . " months"));
$order_send_date = date("Y-m-d");
$input_type = $post_content['type'];
$testdetails = json_encode($post_content['testdetails']);
$serial = $post_content['sn'];
@@ -187,9 +189,9 @@ if (!empty($post_content['sn']) && !empty($post_content['testdetails'])) {
// Create equipment when not exist +++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
if ($equipmentCreate == 1 && $total_equipment == 0){
$sql = 'INSERT INTO equipment (productrowid,created,createdby,status,accounthierarchy,serialnumber,service_date,warranty_date) VALUES (?,?,?,?,?,?,?,?)';
$sql = 'INSERT INTO equipment (productrowid,created,createdby,status,accounthierarchy,serialnumber,service_date,warranty_date,order_send_date) VALUES (?,?,?,?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$productrowid,$date,$user,$status0,$account,$serial,$current_date,$current_date]);
$stmt->execute([$productrowid,$date,$user,$status0,$account,$serial,$service_date,$warranty_date,$order_send_date]);
$rowID = $pdo->lastInsertId();
}
@@ -311,7 +313,7 @@ if (!empty($post_content['sn']) && !empty($post_content['testdetails'])) {
//Update Equipment record
$sql = "UPDATE equipment SET service_date = ? $whereclause";
$stmt = $pdo->prepare($sql);
$stmt->execute([$current_date]);
$stmt->execute([$service_date]);
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++

BIN
api/v1/.DS_Store vendored

Binary file not shown.

View File

@@ -17,11 +17,13 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$hierarchy_level = getHierarchyLevel($partner);
switch ($hierarchy_level) {
case '0':
$whereclause = '';
break;
case '3':
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = 'WHERE c.accounthierarchy like :condition AND u.view IN (4,5)';
break;
@@ -29,7 +31,11 @@ switch ($permission) {
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE c.accounthierarchy like :condition AND u.view IN (1,2,3)';
break;
default:
case '3':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%';
$whereclause = 'WHERE c.accounthierarchy like :condition AND u.view IN (1,2,3)';
break;
case '4':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
$whereclause = 'WHERE c.accounthierarchy like :condition AND u.view IN (1,2,3)';
break;

View File

@@ -14,11 +14,13 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$hierarchy_level = getHierarchyLevel($partner);
switch ($hierarchy_level) {
case '0':
$whereclause = '';
break;
case '3':
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
@@ -26,11 +28,16 @@ switch ($permission) {
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition AND (type = "'.$type1.'" or type = "'.$type2.'" or type = "'.$type3.'" or type = "'.$type9.'" or type = "'.$type14.'" or type = "'.$type16.'")';
break;
default:
case '3':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition AND (type = "'.$type1.'" or type = "'.$type2.'" or type = "'.$type3.'" or type = "'.$type14.'" or type = "'.$type16.'")';
break;
case '4':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
$whereclause = 'WHERE e.accounthierarchy like :condition AND (type = "'.$type1.'" or type = "'.$type2.'" or type = "'.$type3.'" or type = "'.$type14.'" or type = "'.$type16.'")';
break;
}
//NEW ARRAY
$criterias = [];
$clause = '';

View File

@@ -17,7 +17,7 @@ if ($stmt->rowCount() == 1) {
//Define User data
$partnerhierarchy = $user_data['partnerhierarchy'];
$permission = userRights($user_data['view']);
$profile= getProfile($user_data['settings'],$permission);
$profile= getUserPermissions($pdo, $user_data['id']);
$username = $user_data['username'];
$useremail = $user_data['email'];
$servicekey = $user_data['service'];

View File

@@ -40,7 +40,7 @@ if ($id != ''){
$salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $accounthierarchy_old->salesid)? $post_content['salesid'] : $accounthierarchy_old->salesid);
$soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $accounthierarchy_old->soldto)? $post_content['soldto'] : $accounthierarchy_old->soldto);
if ($permission == 3 || $permission == 4){
if (getHierarchyLevel($partner) == 1 || getHierarchyLevel($partner) == 0){
//ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,

View File

@@ -15,7 +15,6 @@ if ($action !=''){
//Connect to DB
//------------------------------------------
$pdo = dbConnect($dbname);
$pdo2 = dbConnect($dbname);
//------------------------------------------
//CONTENT FROM API (POST)
@@ -28,11 +27,13 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = 'WHERE';
switch ($permission) {
case '4':
$hierarchy_level = getHierarchyLevel($partner);
switch ($hierarchy_level) {
case '0':
$whereclause .= '';
break;
case '3':
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = ' e.accounthierarchy like "'.$condition.'" AND ';
break;
@@ -40,7 +41,11 @@ switch ($permission) {
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause .= ' e.accounthierarchy like "'.$condition.'" AND ';
break;
default:
case '3':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%';
$whereclause .= ' e.accounthierarchy like "'.$condition.'" AND ';
break;
case '4':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
$whereclause .= ' e.accounthierarchy like "'.$condition.'" AND ';
break;
@@ -85,238 +90,148 @@ switch ($action) {
$communication_check = 0; //Check communication record
$message_box = [];
$timestamp = date("Y-m-d H:i:s");
// Create history description
$history_description = [
"start_date"=>$timestamp,
"end_date"=>date("Y-m-d", strtotime("+730 days")),
"organization"=>strip_tags(trim($post_content['organization'])),
"phone"=>strip_tags(trim($post_content['phone'])),
"city"=>strip_tags(trim($post_content['city'])),
"country"=>strip_tags(trim($post_content['country'])),
"email_consent"=>strip_tags(trim($post_content['email_consent'])),
"terms_consent"=>strip_tags(trim($post_content['terms_consent']))
];
$description = json_encode($history_description, JSON_UNESCAPED_UNICODE);
// --------------------------------------------
// Check if multiple serialnumbers are provided
// --------------------------------------------
if(is_array($post_content['sn'])){
foreach ($post_content['sn'] as $sn){
//Get equipmentid based on rowID
$rowID = getrowID($dbname,'rowID','equipment','serialnumber="'.$sn.'"');
if ($rowID){
//check if under warranty
$warranty = getrowID($dbname,'rowID','equipment_history','equipmentid="'.$rowID['rowID'].'" && (type="'.$type9.'" || type="'.$type10.'" || type="'.$type11.'" || type="'.$type12.'")');
if ($warranty){
// --------------------------------------------
// Already under contract
// --------------------------------------------
//Serialnumber under warranty
$message_box[] = $sn.' - '.$register_message_2;
$communication_check = 1;
} else
{
// --------------------------------------------
// Not under warranty
// --------------------------------------------
//Send user firmware account
$firmware_account_send = 1;
//create history
// Prepare queries
$sql = 'INSERT INTO equipment_history (equipmentid, type, description, created, createdby,updatedby) VALUES (?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$rowID['rowID'],$type9,$description,$timestamp,$post_content['email'],$post_content['email']]);
// Normalize input to always be an array
$serial_numbers = is_array($post_content['sn']) ? $post_content['sn'] : [$post_content['sn']];
//GET PARTNER DETAILS OF EQUIPMENT
$partner_equipment = getrowID($dbname,'accounthierarchy','equipment','rowID="'.$rowID['rowID'].'"');
$partner_equipment = json_decode($partner_equipment['accounthierarchy']);
//Setup partnerhierarchy (salesID)
$partnerhierarchy =[
"salesid"=>$partner_equipment->salesid,
"soldto"=>$partner_equipment->soldto
];
//Setup variables for partner
$partnername = $post_content['organization'];
$partnernotes = 'created based on user registration';
$salesID = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
$createdby = 'system';
//Check if shipto is empty and if empty search partner or create
if ($partner_equipment->shipto == ''){
$partner_shipto = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype3.'"');
if ($partner_shipto){
//Partner exists - Use it
$partnerhierarchy['shipto'] = $partner_shipto['partnerID'].'-'.$partnername;
} else {
//Partner does not exist create
$sql = 'INSERT INTO partner (partnertype,partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
$stmt = $pdo2->prepare($sql);
$stmt->execute([$partnertype3,$partnername,$salesID,$createdby,'1']);
//Get rowID of created partner and use it
$partner_rowid = $pdo2->lastInsertId();
$partnerhierarchy['shipto'] = $partner_rowid.'-'.$partnername;
}
} else {
// Shipto exist use it
$partnerhierarchy['shipto'] = $partner_equipment->shipto;
}
//Check if location is empty and if empty search partner or create
if ($partner_equipment->location == ''){
$partner_location = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype4.'"');
if ($partner_location){
//Partner exists - Use it
$partnerhierarchy['location'] = $partner_location['partnerID'].'-'.$partnername;
} else {
//Partner does not exist create
$sql = 'INSERT INTO partner (partnertype,partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
$stmt = $pdo2->prepare($sql);
$stmt->execute([$partnertype4,$partnername,$salesID,$createdby,'1']);
//Get rowID of created partner and use it
$partner_rowid = $pdo2->lastInsertId();
$partnerhierarchy['location'] = $partner_rowid.'-'.$partnername;
}
} else {
// Location exist use it
$partnerhierarchy['location'] = $partner_equipment->location;
}
$shipto = $partnerhierarchy['shipto'] ?? '';
$partnerhierarchy = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
// --------------------------------------------
// Update equipment record warranty_date, partnerhierarchy, status equipment
// --------------------------------------------
$sql = 'UPDATE equipment SET status = ?, warranty_date = ?, accounthierarchy = ?,updatedby = ? WHERE rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(['4',$warranty_extended,$partnerhierarchy,$username,$rowID['rowID']]);
//Add warranty to changelog
$warranty_user = $post_content['email'] ?? 'system';
changelog($dbname,'equipment',$rowID['rowID'],'Warranty',$warranty_extended,$warranty_user);
//Serialnumber recognized
$message_box[] = $sn.' - '.$register_message_3;
$communication_check = 1;
}
} else {
//Serialnumber not recognized
$message_box[] = $sn.' - '.$register_message_1;
}
foreach ($serial_numbers as $sn) {
// Get equipment ID based on serial number
$sql = 'SELECT rowID, warranty_date, order_send_date from equipment where serialnumber = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sn]);
$rowID = $stmt->fetch();
if (!$rowID['rowID']) {
// Serial number not recognized
$message_box[] = $sn . ' - ' . $register_message_1;
continue;
}
}
else {
// --------------------------------------------
//Get equipmentid based on rowID
// --------------------------------------------
$rowID = getrowID($dbname,'rowID','equipment','serialnumber="'.$post_content['sn'].'"');
if ($rowID){
//check if under warranty
$warranty = getrowID($dbname,'rowID','equipment_history','equipmentid="'.$rowID['rowID'].'" && (type="'.$type9.'" || type="'.$type10.'" || type="'.$type11.'" || type="'.$type12.'")');
if ($warranty){
// --------------------------------------------
// Check if under warranty
$warranty_types = [$type9, $type10, $type11, $type12];
$warranty_condition = 'equipmentid="' . $rowID['rowID'] . '" && (type="' . implode('" || type="', $warranty_types) . '")';
$warranty = getrowID($dbname, 'rowID', 'equipment_history', $warranty_condition);
if ($warranty) {
// Already under contract
// --------------------------------------------
//Serialnumber not recognized
$message_box[] = $post_content['sn'].' - '.$register_message_2;
} else
{
// --------------------------------------------
// Not under warranty
// --------------------------------------------
$firmware_account_send = 1;
//create history
$sql = 'INSERT INTO equipment_history (equipmentid, type, description, created, createdby, updatedby) VALUES (?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$rowID['rowID'],$type9,$description,$timestamp,$post_content['email'],$post_content['email']]);
//GET PARTNER DETAILS OF EQUIPMENT
$partner_equipment = getrowID($dbname,'accounthierarchy','equipment','rowID="'.$rowID['rowID'].'"');
$partner_equipment = json_decode($partner_equipment['accounthierarchy']);
//Setup partnerhierarchy (salesID)
$partnerhierarchy =[
"salesid"=>$partner_equipment->salesid,
"soldto"=>$partner_equipment->soldto
];
//Setup variables for partner
$partnername = $post_content['organization'];
$partnernotes = 'created based on user registration';
$salesID = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
$createdby = 'system';
//Check if shipto is empty and if empty search partner or create
if ($partner_equipment->shipto == ''){
$partner_shipto = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype3.'"');
if ($partner_shipto){
//Partner exists - Use it
$partnerhierarchy['shipto'] = $partner_shipto['partnerID'].'-'.$partnername;
} else {
//Partner does not exist create
$sql = 'INSERT INTO partner (partnertype, partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
$stmt = $pdo2->prepare($sql);
$stmt->execute([$partnertype3,$partnername,$salesID,$createdby,'1']);
//Get rowID of created partner and use it
$partner_rowid = $pdo2->lastInsertId();
$partnerhierarchy['shipto'] = $partner_rowid.'-'.$partnername;
}
} else {
// Shipto exist use it
$partnerhierarchy['shipto'] = $partner_equipment->shipto;
}
//Check if location is empty and if empty search partner or create
if ($partner_equipment->location == ''){
$partner_location = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype4.'"');
if ($partner_location){
//Partner exists - Use it
$partnerhierarchy['location'] = $partner_location['partnerID'].'-'.$partnername;
} else {
//Partner does not exist create
$sql = 'INSERT INTO partner (partnertype,partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
$stmt = $pdo2->prepare($sql);
$stmt->execute([$partnertype4,$partnername,$salesID,$createdby,'1']);
//Get rowID of created partner and use it
$partner_rowid = $pdo2->lastInsertId();
$partnerhierarchy['location'] = $partner_rowid.'-'.$partnername;
}
} else {
// Location exist use it
$partnerhierarchy['location'] = $partner_equipment->location;
}
$partnerhierarchy = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
// --------------------------------------------
// Update equipment record warranty_date, partnerhierarchy, status equipment
// --------------------------------------------
$sql = 'UPDATE equipment SET status = ?, warranty_date = ?, accounthierarchy = ?, updatedby = ? WHERE rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(['4',$warranty_extended,$partnerhierarchy,$username,$rowID['rowID']]);
//Add warranty to changelog
$warranty_user = $post_content['email'] ?? 'system';
changelog($dbname,'equipment',$rowID['rowID'],'Warranty',$warranty_extended,$warranty_user);
//Serialnumber recognized
$message_box[] = $post_content['sn'].' - '.$register_message_3;
}
$message_box[] = $sn . ' - ' . $register_message_2;
$communication_check = 1;
continue;
}
else {
//Serialnumber not recognized
$message_box[] = $post_content['sn'].' - '.$register_message_1;
//define warranty_end_date
$order_send_date = $rowID['order_send_date'] ?? $rowID['warranty_date'];
// Check if order_send_date is available
if (empty($order_send_date)) {
// No valid date found - skip this serial number
$message_box[] = $sn . ' - ' . $register_message_1; // or create a specific message for missing date
continue;
}
}
// Calculate warranty end date based on eligibility window
$current_date = new DateTime();
$order_date = new DateTime($order_send_date);
$months_diff = $current_date->diff($order_date)->m + ($current_date->diff($order_date)->y * 12);
if ($months_diff <= WARRANTY_ELIGIBILITY_WINDOW) {
// Within eligibility window - apply extended warranty
$warranty_end_date = (clone $order_date)->modify('+' . WARRANTY_EXTENDED_MONTH . ' months')->format('Y-m-d');
} else {
// Outside eligibility window - apply standard warranty
$warranty_end_date = (clone $order_date)->modify('+' . WARRANTY_MONTHS . ' months')->format('Y-m-d');
}
// Not under warranty - process registration
$firmware_account_send = 1;
//Create history description
$history_description = [
"start_date"=>$timestamp,
"end_date"=> $warranty_end_date,
"organization"=>strip_tags(trim($post_content['organization'])),
"phone"=>strip_tags(trim($post_content['phone'])),
"city"=>strip_tags(trim($post_content['city'])),
"country"=>strip_tags(trim($post_content['country'])),
"email_consent"=>strip_tags(trim($post_content['email_consent'])),
"terms_consent"=>strip_tags(trim($post_content['terms_consent']))
];
$description = json_encode($history_description, JSON_UNESCAPED_UNICODE);
// Create history entry
$sql = 'INSERT INTO equipment_history (equipmentid, type, description, created, createdby, updatedby) VALUES (?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
$rowID['rowID'],
$type9,
$description,
$timestamp,
$post_content['email'],
$post_content['email']
]);
// Get partner details of equipment
$partner_equipment = getrowID($dbname, 'accounthierarchy', 'equipment', 'rowID="' . $rowID['rowID'] . '"');
$partner_equipment = json_decode($partner_equipment['accounthierarchy']);
// Setup partner hierarchy
$partnerhierarchy = [
"salesid" => $partner_equipment->salesid,
"soldto" => $partner_equipment->soldto
];
// Setup variables for partner
$partnername = $post_content['organization'];
$salesID = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
$createdby = 'system';
// Helper function to get or create partner
$getOrCreatePartner = function($partnertype) use ($dbname, $partnername, $salesID, $createdby, $pdo) {
$partner = getrowID($dbname, 'partnerID', 'partner', 'partnername = "' . $partnername . '" && partnertype="' . $partnertype . '"');
if ($partner) {
return $partner['partnerID'] . '-' . $partnername;
}
// Partner does not exist - create
$sql = 'INSERT INTO partner (partnertype, partnername, salesID, createdby, status) VALUES (?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$partnertype, $partnername, $salesID, $createdby, '1']);
$partner_rowid = $pdo->lastInsertId();
return $partner_rowid . '-' . $partnername;
};
// Handle shipto
$partnerhierarchy['shipto'] = empty($partner_equipment->shipto)
? $getOrCreatePartner($partnertype3)
: $partner_equipment->shipto;
// Handle location
$partnerhierarchy['location'] = empty($partner_equipment->location)
? $getOrCreatePartner($partnertype4)
: $partner_equipment->location;
$partnerhierarchy_json = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
// Update equipment record
$sql = 'UPDATE equipment SET status = ?, warranty_date = ?, accounthierarchy = ?, updatedby = ? WHERE rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute(['4', $warranty_end_date, $partnerhierarchy_json, $username, $rowID['rowID']]);
// Add warranty to changelog
$warranty_user = $post_content['email'] ?? 'system';
changelog($dbname, 'equipment', $rowID['rowID'], 'Warranty', $warranty_end_date, $warranty_user);
// Serial number recognized
$message_box[] = $sn . ' - ' . $register_message_3;
$communication_check = 1;
}
// --------------------------------------------
// Send generic account to user for software updates

View File

@@ -58,7 +58,7 @@ if ($id != ''){
$shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $contract_old->shipto)? $post_content['shipto'] : $contract_old->shipto);
$location_new = (($post_content['location'] != '' && $post_content['location'] != $contract_old->location)? $post_content['location'] : $contract_old->location);
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -67,7 +67,7 @@ if ($id != ''){
"location"=>$location_new
);
}
elseif ($permission == 3) {
elseif (getHierarchyLevel($partner) == 1) {
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$contract_old->salesid,
@@ -120,7 +120,7 @@ if ($id != ''){
}
else {
//ID is empty => INSERT / NEW RECORD
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
$account = array(
"salesid"=>$post_content['salesid'],
"soldto"=>$post_content['soldto'],
@@ -128,7 +128,7 @@ else {
"location"=>$post_content['location']
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
$account = array(
"salesid"=>$partner->salesid,
"soldto"=>$post_content['soldto'],
@@ -160,7 +160,7 @@ if (isset($post_content['servicetool'])){
if (isset($post_content['ignore_list'])){
$post_content['ignore_list'] = json_encode($post_content['ignore_list'], JSON_UNESCAPED_UNICODE);
//ONLY ADMINS ARE ALLOWED TO UPDATE IGNORE LIST
if ($permission != 3 && $permission != 4){
if (getHierarchyLevel($partner) != 1 && getHierarchyLevel($partner) != 0){
unset($post_content['ignore_list']);
}
}

View File

@@ -47,7 +47,7 @@ if ($id != ''){
$owner_equipment = (($equipment_data['createdby'] == $username)? 1 : 0);
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -57,7 +57,7 @@ if ($id != ''){
"section"=>$section_new
);
}
elseif ($permission == 3) {
elseif (getHierarchyLevel($partner) == 1) {
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$equipment_old->salesid,
@@ -79,7 +79,7 @@ if ($id != ''){
}
else {
//ID is empty => INSERT / NEW RECORD
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
$account = array(
"salesid"=>$post_content['salesid'],
"soldto"=>$post_content['soldto'],
@@ -89,7 +89,7 @@ else {
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
$account = array(
"salesid"=>$partner->salesid,
"soldto"=>$post_content['soldto'],

View File

@@ -41,7 +41,7 @@ if ($id != ''){
$salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $partnerhierarchy_old->salesid)? $post_content['salesid'] : $partnerhierarchy_old->salesid);
$soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $partnerhierarchy_old->soldto)? $post_content['soldto'] : $partnerhierarchy_old->soldto);
if ($permission == 3 || $permission == 4){
if (getHierarchyLevel($partner) == 1 || getHierarchyLevel($partner) == 0){
//ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -56,7 +56,7 @@ if ($id != ''){
}
else {
//ID is empty => INSERT / NEW RECORD
if ($permission == 3 || $permission == 4){
if (getHierarchyLevel($partner) == 1 || getHierarchyLevel($partner) == 0){
//ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$partner->salesid,

View File

@@ -50,7 +50,7 @@ $soldto_new = ((isset($post_content['soldto']) && $post_content['soldto'] != ''
$shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $partnerhierarchy_old->shipto)? $post_content['shipto'] : $partnerhierarchy_old->shipto);
$location_new = (($post_content['location'] != '' && $post_content['location'] != $partnerhierarchy_old->location)? $post_content['location'] : $partnerhierarchy_old->location);
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -58,7 +58,7 @@ $location_new = (($post_content['location'] != '' && $post_content['location'] !
"shipto"=>$shipto_new,
"location"=>$location_new
);
}elseif ($permission == 3) {
}elseif (getHierarchyLevel($partner) == 1) {
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$partner->salesid,
@@ -77,7 +77,7 @@ $location_new = (($post_content['location'] != '' && $post_content['location'] !
}
} elseif ($command == 'insert') {
//ID is empty => INSERT / NEW RECORD
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$post_content['salesid'],
@@ -86,7 +86,7 @@ $location_new = (($post_content['location'] != '' && $post_content['location'] !
"location"=>$post_content['location']
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$partner->salesid,

BIN
api/v2/.DS_Store vendored

Binary file not shown.

BIN
api/v2/get/.DS_Store vendored

Binary file not shown.

View File

@@ -0,0 +1,158 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Access Elements
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//------------------------------------------
//NEW ARRAY
//------------------------------------------
$criterias = [];
$clause = '';
//------------------------------------------
//Check for $_GET variables and build up clause
//------------------------------------------
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='success_msg' || $v[0] =='sort' || $v[0] =='all'){
//do nothing
}
elseif ($v[0] == 'rowid') {
//build up search by ID
$clause .= ' AND a.rowID = :'.$v[0];
}
elseif ($v[0] == 'status') {
//Update status based on status
$clause .= ' AND a.is_active = :'.$v[0];
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND (a.access_name LIKE :'.$v[0].' OR a.access_path LIKE :'.$v[0].' OR a.description LIKE :'.$v[0].')';
}
elseif ($v[0] == 'access_path') {
//build up path search
$clause .= ' AND a.access_path = :'.$v[0];
}
else {
//create clause
$clause .= ' AND a.'.$v[0].' = :'.$v[0];
}
}
}
//Build WHERE clause
$whereclause = '';
if ($clause != ''){
$whereclause = 'WHERE '.substr($clause, 4);
}
// GET SORT INDICATOR
$sort_indicator = $criterias['sort'] ?? '';
switch ($sort_indicator){
case 1:
$sort = ' a.access_name ASC ';
break;
case 2:
$sort = ' a.access_name DESC ';
break;
case 3:
$sort = ' a.access_path ASC ';
break;
case 4:
$sort = ' a.access_path DESC ';
break;
default:
$sort = ' a.access_name ASC ';
break;
}
if (isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM access_elements a '.$whereclause;
}
elseif (isset($criterias['all']) && $criterias['all'] ==''){
//Return all records (no paging)
$sql = 'SELECT a.* FROM access_elements a '.$whereclause.' ORDER BY '.$sort;
}
else {
//SQL
$sql = 'SELECT a.* FROM access_elements a '.$whereclause.' ORDER BY '.$sort.' LIMIT :page,:num_rows';
}
$stmt = $pdo->prepare($sql);
//------------------------------------------
//Bind to query
//------------------------------------------
if (!empty($criterias)){
foreach ($criterias as $key => $value){
$key_condition = ':'.$key;
if (str_contains($sql, $key_condition)){
if ($key == 'search'){
$search_value = '%'.$value.'%';
$stmt->bindValue($key, $search_value, PDO::PARAM_STR);
}
elseif ($key == 'p'){
//Do nothing (bug)
}
else {
$stmt->bindValue($key, $value, PDO::PARAM_STR);
}
}
}
}
//------------------------------------------
// Debuglog
//------------------------------------------
if (debug){
$message = $date.';'.$sql.';'.$username;
debuglog($message);
}
//------------------------------------------
//Add paging details
//------------------------------------------
$page_rows = $page_rows_equipment ?? 20;
if(isset($criterias['totals']) && $criterias['totals']==''){
$stmt->execute();
$messages = $stmt->fetch();
$messages = $messages[0];
}
elseif(isset($criterias['all']) && $criterias['all']==''){
//Return all records (no paging)
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows, PDO::PARAM_INT);
$stmt->bindValue('num_rows', $page_rows, PDO::PARAM_INT);
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_EnCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages;
?>

View File

@@ -17,19 +17,25 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$hierarchy_level = getHierarchyLevel($partner);
switch ($hierarchy_level) {
case '0':
$whereclause = '';
break;
case '3':
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = 'WHERE accounthierarchy like :condition AND u.view IN (4,5)';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like :condition AND u.view IN (1,2,3)';
break;
case '3':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%';
$whereclause = 'WHERE accounthierarchy like :condition AND u.view IN (1,2,3)';
break;
default:
case '4':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
$whereclause = 'WHERE accounthierarchy like :condition AND u.view IN (1,2,3)';
break;

View File

@@ -0,0 +1,116 @@
<?php
defined($security_key) or exit;
// Database connection
$pdo = dbConnect($dbname);
// ============================================
// Input Validation & Sanitization
// ============================================
$filters = [
'serialnumber' => isset($_GET['serialnumber']) ? trim($_GET['serialnumber']) : null,
'type' => isset($_GET['type']) ? trim($_GET['type']) : null,
'start' => isset($_GET['start']) ? trim($_GET['start']) : date("Y-m-d", strtotime("-270 days")),
'end' => isset($_GET['end']) ? trim($_GET['end']) : date("Y-m-d", strtotime("+1 days"))
];
// ============================================
// Build Query with Prepared Statements
// ============================================
$whereClauses = [];
$params = [];
// Serial Number Filter
if ($filters['serialnumber']) {
$whereClauses[] = 'h.description LIKE :serialnumber';
$params[':serialnumber'] = "%historycreated%SN%:" . $filters['serialnumber'] . "%";
$whereClauses[] = 'h.type != :excluded_type';
$params[':excluded_type'] = 'SRIncluded';
}
// Type Filter
if ($filters['type']) {
if ($filters['type'] === 'latest') {
// Get only the latest record per equipment
if ($filters['serialnumber']) {
$whereClauses[] = 'h.rowID IN (
SELECT MAX(h2.rowID)
FROM equipment_history h2
GROUP BY h2.equipmentid
)';
} else {
$whereClauses[] = "h.description LIKE '%historycreated%'";
$whereClauses[] = 'h.rowID IN (
SELECT MAX(h2.rowID)
FROM equipment_history h2
WHERE h2.description LIKE :history_created
GROUP BY h2.equipmentid
)';
$params[':history_created'] = '%historycreated%';
}
} else {
// Specific type filter
$whereClauses[] = 'h.type = :type';
$params[':type'] = $filters['type'];
}
}
// Default filter if no other filters applied
if (empty($whereClauses)) {
$whereClauses[] = "h.description LIKE '%historycreated%'";
}
// Date Range Filter
$whereClauses[] = 'h.created BETWEEN :start_date AND :end_date';
$params[':start_date'] = $filters['start'];
$params[':end_date'] = $filters['end'];
// ============================================
// Execute Query
// ============================================
$whereClause = 'WHERE ' . implode(' AND ', $whereClauses);
$sql = "SELECT h.rowID, h.description
FROM equipment_history h
$whereClause
ORDER BY h.created DESC";
try {
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
// ============================================
// Format Response
// ============================================
$results = [];
foreach ($messages as $message) {
$record = json_decode($message['description'], true);
// Handle JSON decode errors
if (json_last_error() !== JSON_ERROR_NONE) {
continue; // Skip invalid JSON
}
$record['historyID'] = (int)$message['rowID'];
$results[] = $record;
}
// Set proper headers
header('Content-Type: application/json; charset=utf-8');
echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
// Log error (don't expose to client in production)
error_log("Database error: " . $e->getMessage());
//header('Content-Type: application/json; charset=utf-8', true, 500);
echo json_encode([
'error' => 'An error occurred while processing your request'
]);
}
?>

View File

@@ -143,6 +143,10 @@ if(isset($get_content) && $get_content!=''){
$clause .= ' AND e.serialnumber IN (:'.$v[0].')';
}
}
elseif ($v[0] == 'validate') {
// Set validation mode flag
$validation_mode = true;
}
elseif ($v[0] == 'firmware') {
//Assets with firmaware upgrade = 0 (1=latest version, 2=No software)
$clause .= ' AND e.status != 5 AND e.sw_version_latest = 0';
@@ -161,7 +165,7 @@ if(isset($get_content) && $get_content!=''){
}
}
if ($sw_version_latest_update == 1){
if ($sw_version_latest_update == 1 || $clause == ''){
//------------------------------------------
//UPDATE SW_STATUS
//------------------------------------------
@@ -175,6 +179,10 @@ if (isset($criterias['download']) && $criterias['download'] ==''){
//Request for download
$sql = 'SELECT e.rowID as equipmentID, e.*, p.productcode, p.productname from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.' ORDER BY equipmentID';
}
elseif (isset($validation_mode) && $validation_mode === true) {
// Validation mode - return count only for serial validation
$sql = "SELECT count(rowID) as rowID from equipment e $whereclause";
}
elseif (isset($criterias['totals']) && $criterias['totals'] =='' && !isset($criterias['type'])){
//Request for total rows
$sql = 'SELECT count(*) as count from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.'';
@@ -267,7 +275,7 @@ else {
}
//SQL for Paging
$sql = 'SELECT e.rowID as equipmentID, e.*, p.productcode, p.productname, p.product_media from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.' ORDER BY '.$sort.' LIMIT :page,:num_products';
$sql = 'SELECT e.rowID as equipmentID, e.*, p.productcode, p.productname, p.product_media, psl.starts_at,psl.expires_at,psl.status as license_status from equipment e LEFT JOIN products p ON e.productrowid = p.rowID LEFT JOIN products_software_licenses psl ON e.sw_version_license = psl.license_key '.$whereclause.' ORDER BY '.$sort.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
@@ -314,7 +322,19 @@ if (debug){
//------------------------------------------
//Add paging details
//------------------------------------------
if(isset($criterias['totals']) && $criterias['totals']==''){
if (isset($validation_mode) && $validation_mode === true) {
$stmt->execute();
$messages = $stmt->fetch();
if ($messages[0] == 1) {
echo json_encode(array('SN'=> TRUE));
}
else {
echo json_encode(array('SN'=> FALSE));
}
return;
}
elseif(isset($criterias['totals']) && $criterias['totals']==''){
$stmt->execute();
$messages = $stmt->fetch();
$messages = $messages[0];

View File

@@ -13,27 +13,34 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
$hierarchy_level = getHierarchyLevel($partner);
switch ($permission) {
case '4':
switch ($hierarchy_level) {
case '0':
$whereclause = '';
break;
case '3':
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = 'WHERE e.accounthierarchy like :condition';
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition AND (type = "'.$type1.'" or type = "'.$type2.'" or type = "'.$type3.'" or type = "'.$type9.'" or type = "'.$type14.'" or type = "'.$type16.'")';
break;
default:
case '3':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition AND (type = "'.$type1.'" or type = "'.$type2.'" or type = "'.$type3.'" or type = "'.$type14.'" or type = "'.$type16.'")';
break;
case '4':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
$whereclause = 'WHERE e.accounthierarchy like :condition AND (type = "'.$type1.'" or type = "'.$type2.'" or type = "'.$type3.'" or type = "'.$type14.'" or type = "'.$type16.'")';
break;
}
//NEW ARRAY
$criterias = [];
$clause = '';
$type_check = false;
//Check for $_GET variables and build up clause
if(isset($get_content) && $get_content!=''){
@@ -64,11 +71,65 @@ if(isset($get_content) && $get_content!=''){
//build up search
$clause .= ' AND (h.rowID like :'.$v[0].' OR h.createdby like :'.$v[0].')';
}
elseif ($v[0] == 'type' && $v[1] == 'servicereport') {
//Filter out only relevant servicereports
$filter_key_1 = '"%serialnumber%"';
$filter_key_2 = '"ServiceReport"';
$clause .= ' AND h.type = '.$filter_key_2.' AND NOT e.productrowid = "31" AND h.description like '.$filter_key_1;
elseif ($v[0] == 'serialnumber') {
//build up serialnumber
//check if multiple serialnumbers are provided
if (str_contains($v[1], ',')){
$inputs = explode(",",$v[1]);
$new_querystring = ''; //empty querystring
$x=0;
foreach($inputs as $input){
//create key
$new_key = $v[0].'_'.$x;
//inject new key/value to array
$criterias[$new_key] = $input;
$new_querystring .= ':'.$new_key.',';
$x++;
}
//remove obsolete last character from new_querystring
$new_querystring = substr($new_querystring,0, -1);
//add new_querystring to clause
$clause .= ' AND e.serialnumber IN ('.$new_querystring.')';
//remove original key/value from array
unset($criterias[$v[0]]);
}
else {
$clause .= ' AND e.serialnumber IN (:'.$v[0].')';
}
}
elseif ($v[0] == 'type') {
if ($v[1] == 'servicereport') {
//Filter out only relevant servicereports
$filter_key_1 = '"%serialnumber%"';
$filter_key_2 = '"ServiceReport"';
$clause .= ' AND h.type = '.$filter_key_2.' AND NOT e.productrowid = "31" AND h.description like '.$filter_key_1;
//remove from criterias to prevent double binding
unset($criterias[$v[0]]);
}
elseif (str_contains($v[1], ',')) {
//check if multiple types are provided
$inputs = explode(",",$v[1]);
$new_querystring = ''; //empty querystring
$x=0;
foreach($inputs as $input){
//create key
$new_key = $v[0].'_'.$x;
//inject new key/value to array
$criterias[$new_key] = $input;
$new_querystring .= ':'.$new_key.',';
$x++;
}
//remove obsolete last character from new_querystring
$new_querystring = substr($new_querystring,0, -1);
//add new_querystring to clause
$clause .= ' AND h.type IN ('.$new_querystring.')';
//remove original key/value from array
$type_check = true;
unset($criterias[$v[0]]);
}
else {
$clause .= ' AND h.type = :'.$v[0];
}
}
elseif ($v[0] == 'created') {
//build up search
@@ -89,6 +150,9 @@ if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql ='SELECT count(h.rowID) as historyID FROM equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.'';
}
elseif($type_check){
$sql ='SELECT h.rowID as historyID, e.rowID as equipmentID, e.serialnumber, h.type, h.description, h.created, h.createdby FROM equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.' ORDER BY h.created DESC';
}
else {
//request history
$sql ='SELECT h.rowID as historyID, e.rowID as equipmentID, e.serialnumber, h.type, h.description, h.created, h.createdby FROM equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.' ORDER BY h.created DESC LIMIT :page,:num_products';
@@ -125,6 +189,12 @@ if(isset($criterias['totals']) && $criterias['totals']==''){
$messages = $stmt->fetch();
$messages = $messages[0];
}
elseif($type_check){
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_history, PDO::PARAM_INT);
@@ -136,10 +206,22 @@ else {
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Clean up nested JSON in description fields before final encoding
if (!isset($criterias['totals']) || $criterias['totals'] != '') {
foreach ($messages as &$message) {
if (isset($message['description']) && is_string($message['description'])) {
$decoded = json_decode($message['description'], true);
if (json_last_error() === JSON_ERROR_NONE) {
$message['description'] = json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
}
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
//Send results
echo $messages;

View File

@@ -51,7 +51,7 @@ elseif (isset($criterias['list']) && $criterias['list'] =='invoice'){
//SQL for Paging
$sql = 'SELECT tx.*, txi.item_id as item_id,txi.item_price as item_price, txi.item_quantity as item_quantity, txi.item_options as item_options, p.productcode, p.productname, inv.id as invoice, inv.created as invoice_created, i.language as user_language
FROM transactions tx
left join invoice inv ON tx.id = inv.txn_id
left join invoice inv ON tx.txn_id = inv.txn_id
left join transactions_items txi ON tx.id = txi.txn_id
left join products p ON p.rowID = txi.item_id
left join identity i ON i.userkey = tx.account_id '.$whereclause;

View File

@@ -0,0 +1,152 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Marketing Files
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
//NEW ARRAY
$criterias = [];
$clause = '';
//Check for $_GET variables and build up clause
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] == 'action' || $v[0] =='success_msg' || $v[0] == '_t'){
//do nothing
}
elseif ($v[0] == 'folder_id') {
if ($v[1] === 'null' || $v[1] === '') {
$clause .= ' AND folder_id IS NULL';
} else {
$clause .= ' AND folder_id = :folder_id';
}
}
elseif ($v[0] == 'search') {
$clause .= ' AND (title LIKE :search OR original_filename LIKE :search)';
}
elseif ($v[0] == 'tag') {
$clause .= ' AND EXISTS (SELECT 1 FROM marketing_file_tags ft JOIN marketing_tags t ON ft.tag_id = t.id WHERE ft.file_id = mf.id AND t.tag_name = :tag)';
}
elseif ($v[0] == 'file_type') {
$clause .= ' AND file_type = :file_type';
}
else {
// Ignore unknown parameters
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//Set page
$pagina = 1;
if(isset($criterias['p']) && $criterias['p'] !='') {
$pagina = $criterias['p'];
}
//Set limit
$limit = 50;
if(isset($criterias['limit']) && $criterias['limit'] !='') {
$limit = intval($criterias['limit']);
}
$offset = ($pagina - 1) * $limit;
//check for totals call
if(isset($criterias['totals'])){
$sql = 'SELECT COUNT(*) as found FROM marketing_files mf '.$whereclause.' ';
$stmt = $pdo->prepare($sql);
// Bind parameters
if (!empty($criterias)) {
foreach ($criterias as $key => $value) {
if ($key !== 'totals' && $key !== 'page' && $key !== 'p' && $key !== 'limit' && $key !== 'action') {
if ($key == 'search') {
$stmt->bindValue(':'.$key, '%'.$value.'%');
} elseif ($key == 'folder_id' && ($value === 'null' || $value === '')) {
continue;
} else {
$stmt->bindValue(':'.$key, $value);
}
}
}
}
$stmt->execute();
$found = $stmt->fetchColumn();
echo $found;
exit;
}
// Main query
$sql = "SELECT
mf.*,
GROUP_CONCAT(mt.tag_name) as tags
FROM marketing_files mf
LEFT JOIN marketing_file_tags mft ON mf.id = mft.file_id
LEFT JOIN marketing_tags mt ON mft.tag_id = mt.id
" . $whereclause . "
GROUP BY mf.id
ORDER BY mf.created DESC
LIMIT " . $limit . " OFFSET " . $offset;
$stmt = $pdo->prepare($sql);
// Bind parameters
if (!empty($criterias)) {
foreach ($criterias as $key => $value) {
if ($key !== 'totals' && $key !== 'page' && $key !== 'p' && $key !== 'limit') {
if ($key == 'search') {
$stmt->bindValue(':'.$key, '%'.$value.'%');
} elseif ($key == 'folder_id' && ($value === 'null' || $value === '')) {
continue;
} else {
$stmt->bindValue(':'.$key, $value);
}
}
}
}
$stmt->execute();
$marketing_files = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Process each file
foreach ($marketing_files as &$file) {
// Process tags
$file['tags'] = $file['tags'] ? explode(',', $file['tags']) : [];
// Format file size
$bytes = $file['file_size'];
if ($bytes >= 1073741824) {
$file['file_size_formatted'] = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$file['file_size_formatted'] = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$file['file_size_formatted'] = number_format($bytes / 1024, 2) . ' KB';
} else {
$file['file_size_formatted'] = $bytes . ' B';
}
}
// Return result
echo json_encode($marketing_files, JSON_UNESCAPED_UNICODE);
exit;

View File

@@ -0,0 +1,165 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//------------------------------------------
// Marketing Folders
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
// Function to build hierarchical tree structure
function buildFolderTree($folders, $parentId = null) {
$tree = [];
foreach ($folders as $folder) {
if ($folder['parent_id'] == $parentId) {
$children = buildFolderTree($folders, $folder['id']);
$folder['children'] = $children; // Always include children array, even if empty
$tree[] = $folder;
}
}
return $tree;
}
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
//NEW ARRAY
$criterias = [];
$clause = '';
//Check for $_GET variables and build up clause
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='success_msg' || $v[0] == 'action' || $v[0] == 'tree'){
//do nothing - these are not SQL parameters
}
elseif ($v[0] == 'parent_id') {
if ($v[1] === 'null' || $v[1] === '') {
$clause .= ' AND parent_id IS NULL';
} else {
$clause .= ' AND parent_id = :parent_id';
}
}
elseif ($v[0] == 'search') {
$clause .= ' AND (folder_name LIKE :search OR description LIKE :search)';
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//Define Query
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM marketing_folders '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for list (no paging)
$sql = "SELECT
mf.*,
(SELECT COUNT(*) FROM marketing_files WHERE folder_id = mf.id) as file_count,
(SELECT COUNT(*) FROM marketing_folders WHERE parent_id = mf.id) as subfolder_count,
CASE
WHEN mf.parent_id IS NOT NULL THEN
(SELECT folder_name FROM marketing_folders WHERE id = mf.parent_id)
ELSE NULL
END as parent_folder_name
FROM marketing_folders mf
" . $whereclause . "
ORDER BY mf.folder_name ASC";
}
else {
//SQL for paging
$sql = "SELECT
mf.*,
(SELECT COUNT(*) FROM marketing_files WHERE folder_id = mf.id) as file_count,
(SELECT COUNT(*) FROM marketing_folders WHERE parent_id = mf.id) as subfolder_count,
CASE
WHEN mf.parent_id IS NOT NULL THEN
(SELECT folder_name FROM marketing_folders WHERE id = mf.parent_id)
ELSE NULL
END as parent_folder_name
FROM marketing_folders mf
" . $whereclause . "
ORDER BY mf.folder_name ASC
LIMIT :page,:num_folders";
}
$stmt = $pdo->prepare($sql);
if (!empty($criterias)){
foreach ($criterias as $key => $value){
$key_condition = ':'.$key;
if (str_contains($whereclause, $key_condition)){
if ($key == 'search'){
$search_value = '%'.$value.'%';
$stmt->bindValue($key, $search_value, PDO::PARAM_STR);
}
elseif ($key == 'parent_id' && ($value === 'null' || $value === '')) {
// Skip binding for NULL parent_id
continue;
}
else {
$stmt->bindValue($key, $value, PDO::PARAM_STR);
}
}
}
}
//Add paging details
if(isset($criterias['totals']) && $criterias['totals']==''){
$stmt->execute();
$messages = $stmt->fetch();
$messages = $messages[0];
}
elseif(isset($criterias['list']) && $criterias['list']==''){
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_folders, PDO::PARAM_INT);
$stmt->bindValue('num_folders', $page_rows_folders, PDO::PARAM_INT);
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Check if tree structure is requested
if (isset($criterias['tree']) && isset($messages) && is_array($messages)) {
// Build hierarchical tree structure
$messages = buildFolderTree($messages);
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;

View File

@@ -0,0 +1,112 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Marketing Tags
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
//NEW ARRAY
$criterias = [];
$clause = '';
//Check for $_GET variables and build up clause
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='success_msg' || $v[0] == 'action'){
//do nothing
}
elseif ($v[0] == 'search') {
$clause .= ' AND tag_name LIKE :search';
}
elseif ($v[0] == 'used_only') {
if ($v[1] === 'true') {
$clause .= ' AND id IN (SELECT DISTINCT tag_id FROM marketing_file_tags)';
}
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//Set page
$pagina = 1;
if(isset($criterias['p']) && $criterias['p'] !='') {
$pagina = $criterias['p'];
}
//check for totals call
if(isset($criterias['totals'])){
$sql = 'SELECT COUNT(*) as found FROM marketing_tags mt '.$whereclause.' ';
$stmt = $pdo->prepare($sql);
// Bind parameters
if (!empty($criterias)) {
foreach ($criterias as $key => $value) {
if ($key !== 'totals' && $key !== 'page' && $key !== 'p' && $key !== 'used_only') {
if ($key == 'search') {
$stmt->bindValue(':'.$key, '%'.$value.'%');
} else {
$stmt->bindValue(':'.$key, $value);
}
}
}
}
$stmt->execute();
$found = $stmt->fetchColumn();
echo $found;
exit;
}
// Main query
$sql = "SELECT
mt.*,
COUNT(mft.file_id) as usage_count
FROM marketing_tags mt
LEFT JOIN marketing_file_tags mft ON mt.id = mft.tag_id
" . $whereclause . "
GROUP BY mt.id
ORDER BY mt.tag_name ASC";
$stmt = $pdo->prepare($sql);
// Bind parameters
if (!empty($criterias)) {
foreach ($criterias as $key => $value) {
if ($key !== 'totals' && $key !== 'page' && $key !== 'p' && $key !== 'used_only') {
if ($key == 'search') {
$stmt->bindValue(':'.$key, '%'.$value.'%');
} else {
$stmt->bindValue(':'.$key, $value);
}
}
}
}
$stmt->execute();
$marketing_tags = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Return result
echo json_encode($marketing_tags, JSON_UNESCAPED_UNICODE);

View File

@@ -49,7 +49,7 @@ if (!$transaction) {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
$sql = 'SELECT * FROM transactions_items WHERE txn_id = ? LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$payment_id]);
$stmt->execute([$transaction['id']]);
$item = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$item) {

View File

@@ -12,7 +12,7 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("software_upgrade_paths",$permission,$partner,'get');
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'get');
//NEW ARRAY
$criterias = [];

View File

@@ -12,7 +12,7 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("software_versions",$permission,$partner,'get');
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'get');
//NEW ARRAY
$criterias = [];

View File

@@ -0,0 +1,152 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Report Builder - GET Endpoints
//------------------------------------------
// Set content type to JSON
header('Content-Type: application/json');
// Connect to DB
$pdo = dbConnect($dbname);
// Get the action parameter from URL
$criterias = [];
if (isset($get_content) && $get_content != '') {
$requests = explode("&", $get_content);
foreach ($requests as $y) {
$v = explode("=", $y);
if (isset($v[1])) {
$criterias[$v[0]] = urldecode($v[1]);
} else {
$criterias[$v[0]] = '';
}
}
}
$action = strtolower($criterias['action'] ?? '');
/**
* Validate table name - only allow alphanumeric, underscores, hyphens
*/
function sanitizeTableName($table) {
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $table)) {
return false;
}
return $table;
}
/**
* Get list of tables
*/
if ($action === 'gettables') {
try {
$result = $pdo->query("SHOW TABLES");
$tables = [];
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
$messages = json_encode([
'success' => true,
'tables' => $tables
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
http_response_code(500);
$messages = json_encode([
'success' => false,
'message' => 'Failed to fetch tables'
], JSON_UNESCAPED_UNICODE);
}
}
/**
* Get columns for a specific table
*/
elseif ($action === 'getcolumns') {
$table = sanitizeTableName($criterias['table'] ?? '');
if (!$table) {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Invalid table name'
], JSON_UNESCAPED_UNICODE);
} else {
try {
$result = $pdo->query("SHOW COLUMNS FROM `$table`");
$columns = [];
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$columns[] = $row['Field'];
}
$messages = json_encode([
'success' => true,
'columns' => $columns
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
http_response_code(500);
$messages = json_encode([
'success' => false,
'message' => 'Failed to fetch columns'
], JSON_UNESCAPED_UNICODE);
}
}
}
/**
* Get table schema information
*/
elseif ($action === 'gettableschema') {
$table = sanitizeTableName($criterias['table'] ?? '');
if (!$table) {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Invalid table name'
], JSON_UNESCAPED_UNICODE);
} else {
try {
$result = $pdo->query("DESCRIBE `$table`");
$schema = [];
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$schema[] = [
'field' => $row['Field'],
'type' => $row['Type'],
'null' => $row['Null'],
'key' => $row['Key'],
'default' => $row['Default'],
'extra' => $row['Extra']
];
}
$messages = json_encode([
'success' => true,
'schema' => $schema
], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
http_response_code(500);
$messages = json_encode([
'success' => false,
'message' => 'Failed to fetch table schema'
], JSON_UNESCAPED_UNICODE);
}
}
}
/**
* Invalid or missing action
*/
else {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Invalid or missing action parameter'
], JSON_UNESCAPED_UNICODE);
}
// Send results
echo $messages;
?>

View File

@@ -0,0 +1,123 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Role Access Permissions
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//------------------------------------------
//NEW ARRAY
//------------------------------------------
$criterias = [];
$clause = '';
//------------------------------------------
//Check for $_GET variables and build up clause
//------------------------------------------
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'rowid') {
//build up search by ID
$clause .= ' AND rap.rowID = :'.$v[0];
}
elseif ($v[0] == 'role_id') {
//build up search by role_id
$clause .= ' AND rap.role_id = :'.$v[0];
}
elseif ($v[0] == 'access_id') {
//build up search by access_id
$clause .= ' AND rap.access_id = :'.$v[0];
}
else {
//create clause
$clause .= ' AND rap.'.$v[0].' = :'.$v[0];
}
}
}
//Build WHERE clause
$whereclause = '';
if ($clause != ''){
$whereclause = 'WHERE '.substr($clause, 4);
}
if (isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM role_access_permissions rap '.$whereclause;
}
else {
//SQL with joined tables for names
$sql = 'SELECT rap.*,
r.name as role_name,
ae.access_name,
ae.access_path
FROM role_access_permissions rap
LEFT JOIN user_roles r ON rap.role_id = r.rowID
LEFT JOIN access_elements ae ON rap.access_id = ae.rowID
'.$whereclause.'
ORDER BY ae.access_name ASC';
}
$stmt = $pdo->prepare($sql);
//------------------------------------------
//Bind to query
//------------------------------------------
if (!empty($criterias)){
foreach ($criterias as $key => $value){
$key_condition = ':'.$key;
if (str_contains($sql, $key_condition)){
if ($key == 'p'){
//Do nothing (bug)
}
else {
$stmt->bindValue($key, $value, PDO::PARAM_STR);
}
}
}
}
//------------------------------------------
// Debuglog
//------------------------------------------
if (debug){
$message = $date.';'.$sql.';'.$username;
debuglog($message);
}
//------------------------------------------
//Execute Query
//------------------------------------------
if(isset($criterias['totals']) && $criterias['totals']==''){
$stmt->execute();
$messages = $stmt->fetch();
$messages = $messages[0];
}
else {
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_EnCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages;
?>

82
api/v2/get/service.php Normal file
View File

@@ -0,0 +1,82 @@
<?php
defined($security_key) or exit;
//------------------------------------------
//Connect to DB
//------------------------------------------
$pdo = dbConnect($dbname);
//------------------------------------------
// Application related calls
//------------------------------------------
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$action = $request[2] ?? '';
if ($action == 'init'){
include './settings/systemservicetool_init.php';
echo json_encode($init);
}
elseif ($action == 'questions' && (isset($_GET['type']) && $_GET['type'] != '')){
include './settings/systemservicetool.php';
//build questions
switch ($_GET['type']) {
case 'visual':
$arrayQuestions = $arrayQuestions_visual;
break;
case 'final':
$arrayQuestions = $arrayQuestions_finalize;
break;
case 'cartest':
include './settings/systemcartest.php';
$arrayQuestions = $arrayQuestions_cartest;
break;
}
//Return JSON
echo json_encode($arrayQuestions);
}
elseif ($action == 'products') {
$sql = "SELECT * FROM products";
$stmt = $pdo->prepare($sql);
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($messages);
}
elseif ($action == 'equipments' && (isset($_GET['serialnumber']) && $_GET['serialnumber'] != '' && !isset($_GET['validate']))) {
$sql = "SELECT e.rowID as equipmentID, e.*, p.productcode, p.productname, p.product_media, psl.starts_at,psl.expires_at,psl.status as license_status from equipment e LEFT JOIN products p ON e.productrowid = p.rowID LEFT JOIN products_software_licenses psl ON e.sw_version_license = psl.license_key WHERE e.serialnumber = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_GET['serialnumber']]);
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($messages);
}
elseif ($action == 'equipments' && (isset($_GET['serialnumber']) && $_GET['serialnumber'] != '' && isset($_GET['validate']))){
$sql = "SELECT count(rowID) as rowID from equipment e WHERE e.serialnumber = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_GET['serialnumber']]);
$messages = $stmt->fetch();
if ($messages[0] == 1) {
echo json_encode(array('SN'=> TRUE));
}
else {
echo json_encode(array('SN'=> FALSE));
}
}
else {
http_response_code(400);
}
?>

View File

@@ -62,6 +62,7 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
e.sw_version as current_sw_version,
e.hw_version,
e.sw_version_license,
e.sw_version_upgrade,
e.rowID as equipment_rowid
FROM equipment e
JOIN products p ON e.productrowid = p.rowID
@@ -78,6 +79,7 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
$current_sw_version = $equipment_data['current_sw_version'];
$hw_version = $equipment_data['hw_version'];
$sw_version_license = $equipment_data['sw_version_license'];
$sw_version_upgrade = $equipment_data['sw_version_upgrade'];
$equipment_rowid = $equipment_data['equipment_rowid'];
if (debug) {
@@ -85,7 +87,8 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
'product_rowid' => $product_rowid,
'productcode' => $productcode,
'current_sw_version_raw' => $current_sw_version,
'hw_version' => $hw_version
'hw_version' => $hw_version,
'sw_version_upgrade' => $sw_version_upgrade
];
}
@@ -119,6 +122,77 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
exit;
}
// Check if sw_version_upgrade is set - this overrides normal availability check
if (!empty($sw_version_upgrade)) {
if (debug) {
$debug['sw_version_upgrade_check'] = [
'sw_version_upgrade_id' => $sw_version_upgrade,
'checking_override' => true
];
}
// Check if this version exists and is active
$sql = 'SELECT
psv.rowID as version_id,
psv.version,
psv.name,
psv.description,
psv.mandatory,
psv.latest,
psv.hw_version,
psv.file_path,
psv.status
FROM products_software_versions psv
WHERE psv.rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sw_version_upgrade]);
$upgrade_version = $stmt->fetch(PDO::FETCH_ASSOC);
if ($upgrade_version && $upgrade_version['status'] == 1) {
// Valid override found - check if different from current version
$normalized_upgrade_version = strtolower(ltrim($upgrade_version['version'], '0'));
if (debug) {
$debug['sw_version_upgrade_check']['found_version'] = [
'version' => $upgrade_version['version'],
'name' => $upgrade_version['name'],
'normalized' => $normalized_upgrade_version,
'status' => $upgrade_version['status'],
'is_different_from_current' => ($current_sw_version != $normalized_upgrade_version)
];
}
if ($current_sw_version && $normalized_upgrade_version == $current_sw_version) {
// Override version is same as current - no upgrade available
$software_available = "no";
if (debug) {
$debug['sw_version_upgrade_check']['decision'] = 'Override version is same as current version';
}
} else {
// Override version is different - upgrade is available
$software_available = "yes";
if (debug) {
$debug['sw_version_upgrade_check']['decision'] = 'Override version is available';
}
}
$messages = ["software_available" => $software_available];
if (debug) {
debuglog(json_encode($debug));
}
echo json_encode($messages, JSON_UNESCAPED_UNICODE);
exit;
} else {
// Override version not found or inactive - fall back to standard check
if (debug) {
$debug['sw_version_upgrade_check']['found_version'] = $upgrade_version ? 'found but inactive' : 'not found';
$debug['sw_version_upgrade_check']['decision'] = 'Falling back to standard check';
}
}
}
//GET ALL ACTIVE SOFTWARE ASSIGNMENTS for this product with matching HW version
$sql = 'SELECT
psv.rowID as version_id,
@@ -161,6 +235,7 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
$debug['decision'] = 'No active software assignments found';
}
} else {
$available_upgrades = 0;
$has_priced_options = false;
$has_latest_version_different = false;
@@ -219,8 +294,9 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
FROM products_software_upgrade_paths pup
JOIN products_software_versions from_ver ON pup.from_version_id = from_ver.rowID
WHERE pup.to_version_id = ?
AND LOWER(TRIM(LEADING "0" FROM from_ver.version)) = ?
AND pup.is_active = 1';
AND (LOWER(TRIM(LEADING "0" FROM from_ver.version)) = ?
OR pup.from_version_id = 9999999)
AND pup.is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$version['version_id'], $current_sw_version]);
$upgrade_path = $stmt->fetch(PDO::FETCH_ASSOC);
@@ -242,6 +318,8 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
}
if ($show_version) {
$available_upgrades++;
//Check if there's a valid license for this upgrade
if ($final_price > 0 && $sw_version_license) {
//Check if the license is valid
@@ -286,23 +364,18 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
}
}
// Apply the logic:
// 1. If there are priced options -> "yes"
// 2. If no priced options but current version != latest flagged version -> "yes"
// 3. Default -> "no"
if ($has_priced_options) {
// Simple logic: if any upgrades are available to show, return "yes"
if ($available_upgrades > 0) {
$software_available = "yes";
$availability_reason = "Has priced upgrade options available";
} elseif ($has_latest_version_different) {
$software_available = "yes";
$availability_reason = "Has free latest version available";
$availability_reason = "Software upgrades available";
} else {
$software_available = "no";
$availability_reason = "No upgrades available or already on latest";
$availability_reason = "No upgrades available";
}
if (debug) {
$debug['final_decision'] = [
'available_upgrades' => $available_upgrades,
'has_priced_options' => $has_priced_options,
'has_latest_version_different' => $has_latest_version_different,
'software_available' => $software_available,

View File

@@ -55,16 +55,20 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
}
//GET EQUIPMENT AND PRODUCT DATA BASED ON SERIAL NUMBER
$sql = 'SELECT
$sql = "SELECT
p.rowID as product_rowid,
p.productcode,
e.sw_version as current_sw_version,
e.hw_version,
e.sw_version_license,
e.rowID as equipment_rowid
e.sw_version_upgrade,
e.rowID as equipment_rowid,
partner.*
FROM equipment e
JOIN products p ON e.productrowid = p.rowID
WHERE e.serialnumber = ?';
LEFT JOIN partner ON partner.partnerID = SUBSTRING_INDEX(JSON_UNQUOTE(JSON_EXTRACT(e.accounthierarchy, '$.soldto')), '-', 1)
AND partner.is_dealer = 1 AND partner.status = 1
WHERE e.serialnumber = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['sn']]);
$equipment_data = $stmt->fetch(PDO::FETCH_ASSOC);
@@ -77,15 +81,28 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
$current_sw_version = $equipment_data['current_sw_version'];
$hw_version = $equipment_data['hw_version'];
$sw_version_license = $equipment_data['sw_version_license'];
$sw_version_upgrade = $equipment_data['sw_version_upgrade'];
$equipment_rowid = $equipment_data['equipment_rowid'];
$dealer_info = [
'is_dealer' => $equipment_data['is_dealer'] ?? 0,
'name' => $equipment_data['name'] ?? '',
'address' => $equipment_data['address'] ?? '',
'city' => $equipment_data['city'] ?? '',
'postalcode' => $equipment_data['postalcode'] ?? '',
'country' => $equipment_data['country'] ?? '',
'email' => $equipment_data['email'] ?? '',
'phone' => $equipment_data['phone'] ?? ''
];
if (debug) {
$debug['equipment_data'] = [
'product_rowid' => $product_rowid,
'productcode' => $productcode,
'current_sw_version_raw' => $current_sw_version,
'hw_version' => $hw_version,
'sw_version_license' => $sw_version_license
'sw_version_license' => $sw_version_license,
'sw_version_upgrade' => $sw_version_upgrade
];
}
@@ -119,6 +136,95 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
exit;
}
// Check if sw_version_upgrade is set - this overrides normal availability check
if (!empty($sw_version_upgrade)) {
if (debug) {
$debug['sw_version_upgrade_check'] = [
'sw_version_upgrade_id' => $sw_version_upgrade,
'checking_override' => true
];
}
// Check if this version exists and is active
$sql = 'SELECT
psv.rowID as version_id,
psv.version,
psv.name,
psv.description,
psv.mandatory,
psv.latest,
psv.hw_version,
psv.file_path,
psv.status
FROM products_software_versions psv
WHERE psv.rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sw_version_upgrade]);
$upgrade_version = $stmt->fetch(PDO::FETCH_ASSOC);
if ($upgrade_version && $upgrade_version['status'] == 1) {
// Valid override found - check if different from current version
$normalized_upgrade_version = strtolower(ltrim($upgrade_version['version'], '0'));
if (debug) {
$debug['sw_version_upgrade_check']['found_version'] = [
'version' => $upgrade_version['version'],
'name' => $upgrade_version['name'],
'normalized' => $normalized_upgrade_version,
'status' => $upgrade_version['status'],
'is_different_from_current' => ($current_sw_version != $normalized_upgrade_version)
];
}
if (!$current_sw_version || $current_sw_version == '' || $normalized_upgrade_version != $current_sw_version) {
// Override version is different from current (or no current) - return only this upgrade
$output[] = [
"productcode" => $productcode,
"name" => $upgrade_version['name'] ?? '',
"version" => $upgrade_version['version'],
"version_id" => $upgrade_version['version_id'],
"description" => $upgrade_version['description'] ?? '',
"hw_version" => $upgrade_version['hw_version'] ?? '',
"mandatory" => $upgrade_version['mandatory'] ?? '',
"latest" => $upgrade_version['latest'] ?? '',
"software" => $upgrade_version['file_path'] ?? '',
"source" => '',
"source_type" => '',
"price" => '0.00',
"currency" => '',
"is_current" => false
];
// Generate download token
$download_token = create_download_url_token($criterias['sn'], $upgrade_version['version_id']);
$download_url = 'https://'.$_SERVER['SERVER_NAME'].'/api.php/v2/software_download?token='.$download_token;
$output[0]['source'] = $download_url;
$output[0]['source_type'] = 'token_url';
if (debug) {
$debug['sw_version_upgrade_check']['decision'] = 'Override version returned as only upgrade';
$output[0]['_debug'] = $debug;
}
} else {
// Override version is same as current - no upgrades
if (debug) {
$debug['sw_version_upgrade_check']['decision'] = 'Override version is same as current version - no upgrades';
$output = ['message' => 'No upgrades available', 'debug' => $debug];
}
}
$messages = $output;
echo json_encode($messages, JSON_UNESCAPED_UNICODE);
exit;
} else {
// Override version not found or inactive - fall back to standard check
if (debug) {
$debug['sw_version_upgrade_check']['found_version'] = $upgrade_version ? 'found but inactive' : 'not found';
$debug['sw_version_upgrade_check']['decision'] = 'Falling back to standard check';
}
}
}
//GET ALL ACTIVE SOFTWARE ASSIGNMENTS for this product with matching HW version
$sql = 'SELECT
psv.rowID as version_id,
@@ -212,16 +318,13 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
$decision_reason = 'Skipped - is current version but no upgrades scenario';
}
} else {
//Check if this is the current version and should be shown as disabled
if ($is_current_version && $has_paid_upgrade_from_current && $version['latest'] == 1) {
//Show current version as disabled only if it's the latest AND there's a paid upgrade available
//Check if this is the current version - always show it
if ($is_current_version) {
$show_version = true;
$is_current = true;
$final_price = '0.00';
$final_currency = '';
$decision_reason = 'Showing as CURRENT - is latest version with paid upgrade available';
} else if ($is_current_version && !($has_paid_upgrade_from_current && $version['latest'] == 1)) {
$decision_reason = 'Skipped - is current version but not (latest + has_paid_upgrade)';
$decision_reason = 'Showing as CURRENT - always show current version';
} else if (!$is_current_version) {
//Check if this version is part of ANY upgrade path system (either FROM or TO)
$sql = 'SELECT COUNT(*) as path_count
@@ -242,26 +345,28 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
} else {
//Part of an upgrade path system
//Only show if there's an explicit path FROM current version TO this version
// OR a wildcard path (from_version_id = 9999999)
$sql = 'SELECT pup.price, pup.currency
FROM products_software_upgrade_paths pup
JOIN products_software_versions from_ver ON pup.from_version_id = from_ver.rowID
WHERE pup.to_version_id = ?
AND LOWER(TRIM(LEADING "0" FROM from_ver.version)) = ?
AND pup.is_active = 1';
AND (LOWER(TRIM(LEADING "0" FROM from_ver.version)) = ?
OR pup.from_version_id = 9999999)
AND pup.is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$version['version_id'], $current_sw_version]);
$upgrade_path = $stmt->fetch(PDO::FETCH_ASSOC);
if ($upgrade_path) {
//Valid upgrade path found FROM current version
//Valid upgrade path found FROM current version or wildcard
$show_version = true;
$final_price = $upgrade_path['price'] ?? '0.00';
$final_currency = $upgrade_path['currency'] ?? '';
$decision_reason = 'Showing - found upgrade path FROM current (' . $current_sw_version . ') with price: ' . $final_price . ' ' . $final_currency;
$decision_reason = 'Showing - found upgrade path FROM current (' . $current_sw_version . ') or wildcard with price: ' . $final_price . ' ' . $final_currency;
} else {
$decision_reason = 'Skipped - has upgrade paths but none FROM current version (' . $current_sw_version . ')';
$decision_reason = 'Skipped - has upgrade paths but none FROM current version (' . $current_sw_version . ') or wildcard';
}
//If no path from current version exists, don't show (show_version stays false)
//If no path from current version or wildcard exists, don't show (show_version stays false)
}
}
}
@@ -310,7 +415,7 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
}
}
$output[] = [
$entry = [
"productcode" => $productcode,
"name" => $version['name'] ?? '',
"version" => $version['version'],
@@ -324,8 +429,11 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
"source_type" => '',
"price" => $final_price,
"currency" => $final_currency,
"is_current" => $is_current
"is_current" => $is_current,
"dealer_info" => $dealer_info
];
$output[] = $entry;
}
if (debug) {
@@ -360,6 +468,16 @@ if (isset($criterias['sn']) && $criterias['sn'] != ''){
];
}
// Sort output: is_current = true first, then by price low to high
usort($output, function($a, $b) {
// First priority: is_current (true comes before false)
if ($a['is_current'] !== $b['is_current']) {
return $b['is_current'] - $a['is_current'];
}
// Second priority: price (low to high)
return floatval($a['price']) - floatval($b['price']);
});
$messages = $output;
if (debug && !empty($output)) {

View File

@@ -19,7 +19,7 @@ if ($stmt->rowCount() == 1) {
//Define User data
$partnerhierarchy = $user_data['partnerhierarchy'];
$permission = userRights($user_data['view']);
$profile= getProfile($user_data['settings'],$permission);
$profile= getUserPermissions($pdo, $user_data['id']); //getProfile($user_data['settings'],$permission);
$username = $user_data['username'];
$useremail = $user_data['email'];
$servicekey = $user_data['service'];

View File

@@ -0,0 +1,70 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// User Role Assignments
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//------------------------------------------
//NEW ARRAY
//------------------------------------------
$criterias = [];
$user_permissions = [];
//------------------------------------------
//Check for $_GET variables and build up clause
//------------------------------------------
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
}
}
$user_key = $criterias['userkey'] ?? null;
if (!$user_key) {
http_response_code(400);
exit(json_encode(['error_code' => 'API_INPUT_1','error' => 'user_key is required']));
}
//GET USER_DATA
$stmt = $pdo->prepare('SELECT * FROM users WHERE userkey = ?');
$stmt->execute([$user_key]);
if ($stmt->rowCount() == 1) {
//Get results
$user_data = $stmt->fetch();
//GET DATA
$user_permissions['id'] = $user_data['id'];
$user_permissions['email'] = $user_data['email'];
$user_permissions['partnerhierarchy'] = $user_data['partnerhierarchy']; //clean;
$user_permissions['permission'] = userRights($user_data['view']);
$user_permissions['profile'] = getProfile($user_data['settings'],userRights($user_data['view']));
//NEW DATA REPLACING PROFILE AND LATER PERMISSION ABOVE
$user_permissions['permissions'] = getUserPermissions($pdo, $user_data['id']);
if (!$user_permissions['permissions']) {
http_response_code(404);
exit(json_encode(['error_code' => 'API_NOT_FOUND','error' => 'No permissions found']));
}
//+++++++++++++++++++++++++++++++++++++++++++
//Return as JSON
//+++++++++++++++++++++++++++++++++++++++++++
echo json_encode($user_permissions);
}
else {
http_response_code(404);
exit(json_encode(['error_code' => 'API_NOT_FOUND','error' => 'User not found']));
}
?>

View File

@@ -0,0 +1,128 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// User Role Assignments
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//------------------------------------------
//NEW ARRAY
//------------------------------------------
$criterias = [];
$clause = '';
//------------------------------------------
//Check for $_GET variables and build up clause
//------------------------------------------
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'rowid') {
//build up search by ID
$clause .= ' AND ura.rowID = :'.$v[0];
}
elseif ($v[0] == 'role_id') {
//build up search by role_id
$clause .= ' AND ura.role_id = :'.$v[0];
}
elseif ($v[0] == 'user_id') {
//build up search by user_id
$clause .= ' AND ura.user_id = :'.$v[0];
}
elseif ($v[0] == 'status') {
//Update status based on status
$clause .= ' AND ura.is_active = :'.$v[0];
}
else {
//create clause
$clause .= ' AND ura.'.$v[0].' = :'.$v[0];
}
}
}
//Build WHERE clause
$whereclause = '';
if ($clause != ''){
$whereclause = 'WHERE '.substr($clause, 4);
}
if (isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM user_role_assignments ura '.$whereclause;
}
else {
//SQL with joined tables for names
$sql = 'SELECT ura.*,
u.username,
u.email,
r.name as role_name,
r.description as role_description
FROM user_role_assignments ura
LEFT JOIN users u ON ura.user_id = u.id
LEFT JOIN user_roles r ON ura.role_id = r.rowID
'.$whereclause.'
ORDER BY u.username ASC';
}
$stmt = $pdo->prepare($sql);
//------------------------------------------
//Bind to query
//------------------------------------------
if (!empty($criterias)){
foreach ($criterias as $key => $value){
$key_condition = ':'.$key;
if (str_contains($sql, $key_condition)){
if ($key == 'p'){
//Do nothing (bug)
}
else {
$stmt->bindValue($key, $value, PDO::PARAM_STR);
}
}
}
}
//------------------------------------------
// Debuglog
//------------------------------------------
if (debug){
$message = $date.';'.$sql.';'.$username;
debuglog($message);
}
//------------------------------------------
//Execute Query
//------------------------------------------
if(isset($criterias['totals']) && $criterias['totals']==''){
$stmt->execute();
$messages = $stmt->fetch();
$messages = $messages[0];
}
else {
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_EnCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages;
?>

167
api/v2/get/user_roles.php Normal file
View File

@@ -0,0 +1,167 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// User Roles
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//------------------------------------------
//NEW ARRAY
//------------------------------------------
$criterias = [];
$clause = '';
//------------------------------------------
//Check for $_GET variables and build up clause
//------------------------------------------
if(isset($get_content) && $get_content!=''){
//GET VARIABLES FROM URL
$requests = explode("&", $get_content);
//Check for keys and values
foreach ($requests as $y){
$v = explode("=", $y);
//INCLUDE VARIABLES IN ARRAY
$criterias[$v[0]] = $v[1];
if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='success_msg' || $v[0] =='sort' || $v[0] =='all'){
//do nothing
}
elseif ($v[0] == 'rowid') {
//build up search by ID
$clause .= ' AND r.rowID = :'.$v[0];
}
elseif ($v[0] == 'status') {
//Update status based on status
$clause .= ' AND r.is_active = :'.$v[0];
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND (r.name LIKE :'.$v[0].' OR r.description LIKE :'.$v[0].')';
}
elseif ($v[0] == 'name') {
//build up name search
$clause .= ' AND r.name = :'.$v[0];
}
else {
//create clause
$clause .= ' AND r.'.$v[0].' = :'.$v[0];
}
}
}
//Filter system roles for users without delete permission on user_roles
if (isAllowed('user_roles', $profile, $permission, 'D') !== 1) {
$clause .= ' AND r.is_system != 1';
}
//Build WHERE clause
$whereclause = '';
if ($clause != ''){
$whereclause = 'WHERE '.substr($clause, 4);
}
// GET SORT INDICATOR
$sort_indicator = $criterias['sort'] ?? '';
switch ($sort_indicator){
case 1:
$sort = ' r.name ASC ';
break;
case 2:
$sort = ' r.name DESC ';
break;
case 3:
$sort = ' r.created ASC ';
break;
case 4:
$sort = ' r.created DESC ';
break;
default:
$sort = ' r.rowID ';
break;
}
if (isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM user_roles r '.$whereclause;
}
elseif (isset($criterias['all']) && $criterias['all'] ==''){
//Return all records (no paging)
$sql = 'SELECT r.*,
(SELECT COUNT(*) FROM role_access_permissions WHERE role_id = r.rowID) as permission_count
FROM user_roles r '.$whereclause.' ORDER BY '.$sort;
}
else {
//SQL with permission count
$sql = 'SELECT r.*,
(SELECT COUNT(*) FROM role_access_permissions WHERE role_id = r.rowID) as permission_count
FROM user_roles r '.$whereclause.' ORDER BY '.$sort.' LIMIT :page,:num_rows';
}
$stmt = $pdo->prepare($sql);
//------------------------------------------
//Bind to query
//------------------------------------------
if (!empty($criterias)){
foreach ($criterias as $key => $value){
$key_condition = ':'.$key;
if (str_contains($sql, $key_condition)){
if ($key == 'search'){
$search_value = '%'.$value.'%';
$stmt->bindValue($key, $search_value, PDO::PARAM_STR);
}
elseif ($key == 'p'){
//Do nothing (bug)
}
else {
$stmt->bindValue($key, $value, PDO::PARAM_STR);
}
}
}
}
//------------------------------------------
// Debuglog
//------------------------------------------
if (debug){
$message = $date.';'.$sql.';'.$username;
debuglog($message);
}
//------------------------------------------
//Add paging details
//------------------------------------------
$page_rows = $page_rows_equipment ?? 20;
if(isset($criterias['totals']) && $criterias['totals']==''){
$stmt->execute();
$messages = $stmt->fetch();
$messages = $messages[0];
}
elseif(isset($criterias['all']) && $criterias['all']==''){
//Return all records (no paging)
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows, PDO::PARAM_INT);
$stmt->bindValue('num_rows', $page_rows, PDO::PARAM_INT);
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_EnCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages;
?>

BIN
api/v2/post/.DS_Store vendored

Binary file not shown.

View File

@@ -0,0 +1,79 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Access Elements
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//CONTENT FROM API (POST)
$post_content = json_decode($input,true);
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? '';
$command = ($id == '')? 'insert' : 'update';
if (isset($post_content['delete'])){$command = 'delete';}
$date = date('Y-m-d H:i:s');
//CREATE EMPTY STRINGS
$clause = '';
$clause_insert ='';
$input_insert = '';
$execute_input = [];
$criterias = [];
//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){
$post_content['updatedby'] = $username;
$post_content['updated'] = $date;
}
elseif ($command == 'insert'){
$post_content['created'] = $date;
$post_content['createdby'] = $username;
}
//CREAT NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){
foreach ($post_content as $key => $var){
if ($key == 'submit' || $key == 'rowID' || str_contains($key, 'old_')){
//do nothing
}
else {
$criterias[$key] = $var;
$clause .= ' , '.$key.' = ?';
$clause_insert .= ' , '.$key.'';
$input_insert .= ', ?';
$execute_input[]= $var;
}
}
}
//CLEAN UP INPUT
$clause = substr($clause, 2);
$clause_insert = substr($clause_insert, 2);
$input_insert = substr($input_insert, 1);
//QUERY AND VERIFY ALLOWED
if ($command == 'update' && isAllowed('access_element_manage',$profile,$permission,'U') === 1){
$sql = 'UPDATE access_elements SET '.$clause.' WHERE rowID = ?';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'insert' && isAllowed('access_element_manage',$profile,$permission,'C') === 1){
$sql = 'INSERT INTO access_elements ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'delete' && isAllowed('access_element_manage',$profile,$permission,'D') === 1){
//Delete role permissions using this access element first (foreign key constraint)
$stmt = $pdo->prepare('DELETE FROM role_access_permissions WHERE access_id = ?');
$stmt->execute([$id]);
//Delete access element
$stmt = $pdo->prepare('DELETE FROM access_elements WHERE rowID = ?');
$stmt->execute([$id]);
}
?>

View File

@@ -38,7 +38,7 @@ if ($id != ''){
$salesid_new = ((isset($post_content['salesid']) && $post_content['salesid'] != '' && $post_content['salesid'] != $accounthierarchy_old->salesid)? $post_content['salesid'] : $accounthierarchy_old->salesid);
$soldto_new = ((isset($post_content['soldto']) && $post_content['soldto'] != '' && $post_content['soldto'] != $accounthierarchy_old->soldto)? $post_content['soldto'] : $accounthierarchy_old->soldto);
if ($permission == 3 || $permission == 4){
if (getHierarchyLevel($partner) == 1 || getHierarchyLevel($partner) == 0){
//ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,

View File

@@ -58,7 +58,7 @@ if ($id != ''){
$shipto_new = ((isset($post_content['shipto']) && $post_content['shipto'] != '' && $post_content['shipto'] != $contract_old->shipto)? $post_content['shipto'] : $contract_old->shipto);
$location_new = ((isset($post_content['location']) && $post_content['location'] != '' && $post_content['location'] != $contract_old->location)? $post_content['location'] : $contract_old->location);
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -67,7 +67,7 @@ if ($id != ''){
"location"=>$location_new
);
}
elseif ($permission == 3) {
elseif (getHierarchyLevel($partner) == 1) {
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$contract_old->salesid,
@@ -120,7 +120,7 @@ if ($id != ''){
}
else {
//ID is empty => INSERT / NEW RECORD
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
$account = array(
"salesid"=>$post_content['salesid'],
"soldto"=>$post_content['soldto'],
@@ -128,7 +128,7 @@ else {
"location"=>$post_content['location']
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
$account = array(
"salesid"=>$partner->salesid,
"soldto"=>$post_content['soldto'],
@@ -161,7 +161,7 @@ if (isset($post_content['ignore_list'])){
$post_content['ignore_list'] = json_encode($post_content['ignore_list'], JSON_UNESCAPED_UNICODE);
//ONLY ADMINS ARE ALLOWED TO UPDATE IGNORE LIST
if ($permission != 3 && $permission != 4){
if (getHierarchyLevel($partner) != 1 && getHierarchyLevel($partner) != 0){
unset($post_content['ignore_list']);
}
}

View File

@@ -47,7 +47,7 @@ if ($id != ''){
$owner_equipment = (($equipment_data['createdby'] == $username)? 1 : 0);
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -57,7 +57,7 @@ if ($id != ''){
"section"=>$section_new
);
}
elseif ($permission == 3) {
elseif (getHierarchyLevel($partner) == 1) {
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$equipment_old->salesid,
@@ -79,7 +79,7 @@ if ($id != ''){
}
else {
//ID is empty => INSERT / NEW RECORD
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
$account = array(
"salesid"=>$post_content['salesid'],
"soldto"=>$post_content['soldto'],
@@ -89,7 +89,7 @@ else {
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
$account = array(
"salesid"=>$partner->salesid,
"soldto"=>$post_content['soldto'],
@@ -148,9 +148,9 @@ if ($command == 'update'){
//RESET WARRANTY AND SERVICE DATES WHEN STATUS IS CHANGED TO SEND(3)
if (isset($post_content['status']) && $post_content['status'] == 3 && $equipment_data['status'] != 3)
{
$post_content['service_date'] = $date;
$post_content['warranty_date'] = $date;
$post_content['service_date'] = date("Y-m-d", strtotime("+" . SERVICE_MONTHS . " months"));
$post_content['warranty_date'] = date("Y-m-d", strtotime("+" . WARRANTY_MONTHS . " months"));
$post_content['order_send_date'] = $date;
}
//UPDATE CHANGELOG BASED ON STATUS CHANGE
if (isset($post_content['status']) && $post_content['status'] != $equipment_data['status'])
@@ -188,8 +188,15 @@ elseif ($command == 'insert'){
$post_content['created'] = $date;
$post_content['createdby'] = $username;
$post_content['accounthierarchy'] = $accounthierarchy;
$post_content['service_date'] = $date;
$post_content['warranty_date'] = $date;
$post_content['service_date'] = date("Y-m-d", strtotime("+" . SERVICE_MONTHS . " months"));
$post_content['warranty_date'] = date("Y-m-d", strtotime("+" . WARRANTY_MONTHS . " months"));
if (isset($post_content['status']) && $post_content['status'] == 3)
{
$post_content['order_send_date'] = $date;
}
}
else {
//do nothing

View File

@@ -1,5 +1,6 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// History
//------------------------------------------
@@ -23,7 +24,11 @@ function checkSerial($serialinput){
}
//CHECK IF SN AND PAYLOAD IS SEND => FROM EXTERNAL APPS
if (isset($post_content['sn']) && isset($post_content['payload'])){
if (isset($post_content['sn']) && (isset($post_content['payload']) || isset($post_content['testdetails']))){
if (!isset($post_content['payload'])) {
$post_content['payload'] = $post_content['testdetails'];
}
if (!empty($post_content['sn']) && !empty($post_content['payload'])) {
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -39,12 +44,16 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
$updateObject_visual = 0; //update visual inspection object
$sendServiceReport = 0; //send service report via email
$transfercartest = 0; //Update cartest table with incoming data
$create_software_license = 0; //Create software license
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
//SET DEFAULT PARAMETERS
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
$user = $username;
$account = $partnerhierarchy; //string
$current_date = date("Y-m-d");
$service_date = date("Y-m-d", strtotime("+" . SERVICE_MONTHS . " months"));
$warranty_date = date("Y-m-d", strtotime("+" . WARRANTY_MONTHS . " months"));
$order_send_date = date("Y-m-d");
$input_type = $post_content['type'];
$testdetails = json_encode($post_content['payload']);
$serial = $post_content['sn'];
@@ -141,12 +150,21 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
$transfercartest = 1;
break;
case 12: //customer_consent
$historytype = 'Customer_consent';
$create_software_license = 1;
break;
case 'firmware': //update from Portal
$historytype = $HistoryType_2;
$equipmentUpdate = 1;
$servicetoolHistoryUpdate = 1;
$sn_service = $post_content['sn_service'];
break;
case 'customer': //update from Portal
$historytype = 'Customer';
break;
default:
$historytype = 'Other';
@@ -155,14 +173,14 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Connect to DB
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Get whereclause based on serialnumber
$whereclause = checkSerial($serial);
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
//CHECK if EQUIPMENT EXISTS
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
$sql = "SELECT count(rowID) as total, rowID FROM equipment $whereclause";
$sql = "SELECT count(rowID) as total, rowID, hw_version FROM equipment $whereclause";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$total = $stmt->fetchAll(PDO::FETCH_ASSOC);
@@ -173,9 +191,9 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
// Create equipment when not exist +++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
if ($equipmentCreate == 1 && $total_equipment == 0){
$sql = 'INSERT INTO equipment (productrowid,created,createdby,status,accounthierarchy,serialnumber,service_date,warranty_date) VALUES (?,?,?,?,?,?,?,?)';
$sql = 'INSERT INTO equipment (productrowid,created,createdby,status,accounthierarchy,serialnumber,service_date,warranty_date,order_send_date) VALUES (?,?,?,?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$productrowid,$date,$user,$status0,$account,$serial,$current_date,$current_date]);
$stmt->execute([$productrowid,$date,$user,$status0,$account,$serial,$service_date,$warranty_date,$order_send_date]);
$rowID = $pdo->lastInsertId();
}
@@ -209,9 +227,8 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
if ($equipmentUpdate == 1){
//get HW + SW from PortalAPI
if ($post_content['type'] == 'firmware'){
$test = json_decode($post_content['payload']);
$hw_version = $test->HW;
$sw_version = $test->HEX_FW;
$hw_version = $post_content['payload']['HW'];
$sw_version = $post_content['payload']['HEX_FW'];
}
else {
//GET HW + SW from object
@@ -297,7 +314,7 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
//Update Equipment record
$sql = "UPDATE equipment SET service_date = ? $whereclause";
$stmt = $pdo->prepare($sql);
$stmt->execute([$current_date]);
$stmt->execute([$service_date]);
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -349,6 +366,50 @@ if (isset($post_content['sn']) && isset($post_content['payload'])){
if ($transfercartest == 1){
convertCartest();
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
// create software license ++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
if ($create_software_license == 1){
// Generate unique license key
$license_key = generateUniqueLicenseKey();
$sw_version_consent = strtolower($post_content['testdetails']['logdetails']['FW'] ?? '');// version_id
$eq_version_hw = strtolower($rowID['hw_version'] ?? '');
//GET VERSION_ID FROM VERSION TABLE
$sql = 'SELECT rowID FROM products_software_versions WHERE version = ? and hw_version = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sw_version_consent, $eq_version_hw]);
$version_row = $stmt->fetch(PDO::FETCH_ASSOC);
//GET VERSION_ID or use WILDCARD
$sw_version_consent = $version_row['rowID'] ?? '9999999';
// Create license
$sql = 'INSERT INTO products_software_licenses
(version_id, license_type, license_key, status, starts_at, expires_at, transaction_id, accounthierarchy,created, createdby)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
$sw_version_consent,
1, // license_type (1 = upgrade)
$license_key,
1, // status = active
date('Y-m-d H:i:s'),
'2099-12-31 23:59:59', // effectively permanent
'Customer_consent',
$account,
date('Y-m-d H:i:s'),
$user
]);
// Update equipment.sw_version_license
$sql = 'UPDATE equipment SET sw_version_license = ? WHERE rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$license_key, $rowID]);
}
}
else
{

View File

@@ -0,0 +1,93 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Marketing Files Delete
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//CONTENT FROM API (POST)
$post_content = json_decode($input,true);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'');
$file_id = $post_content['file_id'] ?? '';
if (empty($file_id)) {
echo json_encode(['error' => 'File ID is required']);
exit;
}
//QUERY AND VERIFY ALLOWED
if (isAllowed('marketing',$profile,$permission,'D') === 1){
// Get file information for cleanup
$file_sql = 'SELECT * FROM marketing_files WHERE id = ? AND accounthierarchy LIKE ?';
$stmt = $pdo->prepare($file_sql);
$stmt->execute([$file_id, '%' . $partner->soldto . '%']);
$file_info = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$file_info) {
echo json_encode(['error' => 'File not found or access denied']);
exit;
}
try {
$pdo->beginTransaction();
// Remove file tags
$delete_tags_sql = 'DELETE FROM marketing_file_tags WHERE file_id = ?';
$stmt = $pdo->prepare($delete_tags_sql);
$stmt->execute([$file_id]);
// Delete file record
$delete_file_sql = 'DELETE FROM marketing_files WHERE id = ? AND accounthierarchy LIKE ?';
$stmt = $pdo->prepare($delete_file_sql);
$stmt->execute([$file_id, '%' . $partner->soldto . '%']);
// Delete physical files
$base_path = dirname(__FILE__, 4) . "/";
$main_file = $base_path . $file_info['file_path'];
$thumbnail_file = $file_info['thumbnail_path'] ? $base_path . $file_info['thumbnail_path'] : null;
$files_deleted = [];
$files_failed = [];
if (file_exists($main_file)) {
if (unlink($main_file)) {
$files_deleted[] = $file_info['file_path'];
} else {
$files_failed[] = $file_info['file_path'];
}
}
if ($thumbnail_file && file_exists($thumbnail_file)) {
if (unlink($thumbnail_file)) {
$files_deleted[] = $file_info['thumbnail_path'];
} else {
$files_failed[] = $file_info['thumbnail_path'];
}
}
$pdo->commit();
echo json_encode([
'success' => true,
'message' => 'File deleted successfully',
'files_deleted' => $files_deleted,
'files_failed' => $files_failed
]);
} catch (Exception $e) {
$pdo->rollback();
echo json_encode(['error' => 'Failed to delete file: ' . $e->getMessage()]);
}
} else {
echo json_encode(['error' => 'Insufficient permissions']);
}
?>

View File

@@ -0,0 +1,105 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Marketing Folders
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//CONTENT FROM API (POST)
$post_content = json_decode($input,true);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'');
//BUILD UP PARTNERHIERARCHY FROM USER
$partner_hierarchy = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);
$id = $post_content['id'] ?? ''; //check for rowID
$command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT
if (isset($post_content['delete'])){$command = 'delete';} //change command to delete
$date = date('Y-m-d H:i:s');
//CREATE EMPTY STRINGS
$clause = '';
$clause_insert ='';
$input_insert = '';
if ($command == 'update'){
$post_content['updatedby'] = $username;
$post_content['updated'] = $date;
}
if ($command == 'insert'){
$post_content['createdby'] = $username;
$post_content['accounthierarchy'] = $partner_hierarchy;
}
//CREATE NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){
foreach ($post_content as $key => $var){
if ($key == 'submit' || $key == 'id' || $key == 'delete'){
//do nothing
}
else {
// Handle empty parent_id as NULL for foreign key constraint
if ($key == 'parent_id' && $var === '') {
$var = null;
}
$criterias[$key] = $var;
$clause .= ' , '.$key.' = ?';
$clause_insert .= ' , '.$key.'';
$input_insert .= ', ?'; // ? for each insert item
$execute_input[]= $var; // Build array for input
}
}
}
//CLEAN UP INPUT
$clause = substr($clause, 2); //Clean clause - remove first comma
$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma
$input_insert = substr($input_insert, 1); //Clean clause - remove first comma
//QUERY AND VERIFY ALLOWED
if ($command == 'update' && isAllowed('marketing',$profile,$permission,'U') === 1){
$sql = 'UPDATE marketing_folders SET '.$clause.' WHERE id = ? '.$whereclause.'';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
echo json_encode(['success' => true, 'message' => 'Folder updated successfully']);
}
elseif ($command == 'insert' && isAllowed('marketing',$profile,$permission,'C') === 1){
$sql = 'INSERT INTO marketing_folders ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
$folder_id = $pdo->lastInsertId();
echo json_encode(['success' => true, 'rowID' => $folder_id, 'message' => 'Folder created successfully']);
}
elseif ($command == 'delete' && isAllowed('marketing',$profile,$permission,'D') === 1){
// Check if folder has subfolders
$subfolder_sql = 'SELECT COUNT(*) as count FROM marketing_folders WHERE parent_id = ? AND accounthierarchy LIKE ?';
$stmt = $pdo->prepare($subfolder_sql);
$stmt->execute([$id, '%' . $partner->soldto . '%']);
$subfolder_count = $stmt->fetch()['count'];
// Check if folder has files
$files_sql = 'SELECT COUNT(*) as count FROM marketing_files WHERE folder_id = ? AND accounthierarchy LIKE ?';
$stmt = $pdo->prepare($files_sql);
$stmt->execute([$id, '%' . $partner->soldto . '%']);
$files_count = $stmt->fetch()['count'];
if ($subfolder_count > 0 || $files_count > 0) {
echo json_encode(['error' => 'Cannot delete folder that contains subfolders or files']);
} else {
$stmt = $pdo->prepare('DELETE FROM marketing_folders WHERE id = ? '.$whereclause.'');
$stmt->execute([ $id ]);
echo json_encode(['success' => true, 'message' => 'Folder deleted successfully']);
}
} else {
echo json_encode(['error' => 'Insufficient permissions or invalid operation']);
}
?>

View File

@@ -0,0 +1,94 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Marketing Update
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'');
//QUERY AND VERIFY ALLOWED
if (isAllowed('marketing',$profile,$permission,'U') === 1){
// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$file_id = $input['file_id'] ?? '';
if (empty($file_id)) {
echo json_encode(['success' => false, 'error' => 'File ID is required']);
exit;
}
try {
// First verify the file exists and user has access
$check_sql = 'SELECT id FROM `marketing_files` WHERE `id` = ?';
$check_stmt = $pdo->prepare($check_sql);
$check_stmt->execute([$file_id]);
if ($check_stmt->rowCount() === 0) {
echo json_encode(['success' => false, 'error' => 'File not found or access denied']);
exit;
}
// Build dynamic UPDATE query for only changed fields
$update_fields = [];
$update_params = [];
if (isset($input['title'])) {
$update_fields[] = '`title` = ?';
$update_params[] = $input['title'];
}
if (isset($input['folder_id'])) {
$update_fields[] = '`folder_id` = ?';
$update_params[] = $input['folder_id'] ?: null;
}
// Always update updatedby if there are changes
if (!empty($update_fields)) {
$update_fields[] = '`updatedby` = ?';
$update_params[] = $username;
$update_params[] = $file_id;
$update_sql = 'UPDATE `marketing_files` SET ' . implode(', ', $update_fields) . ' WHERE `id` = ?';
$stmt = $pdo->prepare($update_sql);
$stmt->execute($update_params);
}
// Update tags only if provided
if (isset($input['tags'])) {
// Remove existing tags
$pdo->prepare('DELETE FROM `marketing_file_tags` WHERE `file_id` = ?')->execute([$file_id]);
// Parse and insert new tags
$tags_string = $input['tags'];
$tags_array = array_filter(array_map('trim', explode(',', $tags_string)));
if (!empty($tags_array)) {
$tag_sql = 'INSERT IGNORE INTO `marketing_tags` (`tag_name`) VALUES (?)';
$tag_stmt = $pdo->prepare($tag_sql);
$file_tag_sql = 'INSERT INTO `marketing_file_tags` (`file_id`, `tag_id`) SELECT ?, id FROM marketing_tags WHERE tag_name = ?';
$file_tag_stmt = $pdo->prepare($file_tag_sql);
foreach ($tags_array as $tag) {
$tag_stmt->execute([$tag]);
$file_tag_stmt->execute([$file_id, $tag]);
}
}
}
echo json_encode(['success' => true, 'message' => 'File updated successfully']);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => 'Update failed: ' . $e->getMessage()]);
}
} else {
echo json_encode(['success' => false, 'error' => 'Insufficient permissions']);
}
?>

View File

@@ -0,0 +1,336 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Marketing Upload
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'');
//BUILD UP PARTNERHIERARCHY FROM USER
$partner_hierarchy = $condition;
//QUERY AND VERIFY ALLOWED
if (isAllowed('marketing',$profile,$permission,'C') === 1){
if (!isset($_FILES['file'])) {
echo json_encode(['success' => false, 'error' => 'No file uploaded']);
exit;
}
$file = $_FILES['file'];
$folder_id = $_POST['folder_id'] ?? '';
$tags = isset($_POST['tags']) ? json_decode($_POST['tags'], true) : [];
$title = $_POST['title'] ?? pathinfo($file['name'], PATHINFO_FILENAME);
// Validate file type
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'mp4', 'mov', 'avi'];
$filename = $file['name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowedTypes)) {
echo json_encode(['success' => false, 'error' => 'Invalid file type. Allowed: ' . implode(', ', $allowedTypes)]);
exit;
}
$imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$isImage = in_array($ext, $imageTypes);
// For images over 10MB, automatically compress
if ($isImage && $file['size'] > 10000000) {
$compressed = compressImage($file['tmp_name'], $ext, 10000000);
if ($compressed === false) {
echo json_encode(['success' => false, 'error' => 'Failed to compress large image. Please reduce file size manually.']);
exit;
}
// Update file size after compression
$file['size'] = filesize($file['tmp_name']);
}
// Non-images must be under 10MB
if (!$isImage && $file['size'] > 25000000) {
echo json_encode(['success' => false, 'error' => 'File too large. Maximum size is 25MB.']);
exit;
}
// Create unique filename
$unique_filename = uniqid() . '_' . time() . '.' . $ext;
$target_dir = dirname(__FILE__, 4) . "/marketing/uploads/";
$target_file = $target_dir . $unique_filename;
$logical_path = "marketing/uploads/" . $unique_filename;
// Ensure upload directory exists
if (!file_exists($target_dir)) {
mkdir($target_dir, 0755, true);
}
if (move_uploaded_file($file['tmp_name'], $target_file)) {
// Generate thumbnail
$thumbnail_path = null;
$thumb_dir = $target_dir . "thumbs/";
if (!file_exists($thumb_dir)) {
mkdir($thumb_dir, 0755, true);
}
// Generate thumbnail for images
if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
$thumbnail_file = $thumb_dir . $unique_filename;
if (generateThumbnail($target_file, $thumbnail_file, 200, 200)) {
$thumbnail_path = "marketing/uploads/thumbs/" . $unique_filename;
}
}
// Generate thumbnail for videos
elseif (in_array($ext, ['mp4', 'mov', 'avi'])) {
$thumbnail_filename = pathinfo($unique_filename, PATHINFO_FILENAME) . '.jpg';
$thumbnail_file = $thumb_dir . $thumbnail_filename;
if (generateVideoThumbnail($target_file, $thumbnail_file)) {
$thumbnail_path = "marketing/uploads/thumbs/" . $thumbnail_filename;
}
}
// Insert into database
$insert_sql = 'INSERT INTO `marketing_files` (`title`, `original_filename`, `file_path`, `thumbnail_path`, `file_type`, `file_size`, `folder_id`, `tags`, `createdby`, `accounthierarchy`) VALUES (?,?,?,?,?,?,?,?,?,?)';
$stmt = $pdo->prepare($insert_sql);
$stmt->execute([
$title,
$filename,
$logical_path,
$thumbnail_path,
$ext,
$file['size'],
$folder_id,
json_encode($tags),
$username,
$partner_hierarchy
]);
$file_id = $pdo->lastInsertId();
// Insert tags into separate table
if (!empty($tags)) {
$tag_sql = 'INSERT IGNORE INTO `marketing_tags` (`tag_name`) VALUES (?)';
$tag_stmt = $pdo->prepare($tag_sql);
$file_tag_sql = 'INSERT INTO `marketing_file_tags` (`file_id`, `tag_id`) SELECT ?, id FROM marketing_tags WHERE tag_name = ?';
$file_tag_stmt = $pdo->prepare($file_tag_sql);
foreach ($tags as $tag) {
$tag_stmt->execute([trim($tag)]);
$file_tag_stmt->execute([$file_id, trim($tag)]);
}
}
echo json_encode([
'success' => true,
'file_id' => $file_id,
'path' => $logical_path,
'thumbnail' => $thumbnail_path,
'message' => 'File uploaded successfully'
]);
} else {
echo json_encode(['success' => false, 'error' => 'Failed to move uploaded file']);
}
} else {
echo json_encode(['success' => false, 'error' => 'Insufficient permissions']);
}
// Function to compress large images
function compressImage($source, $ext, $maxSize) {
$info = @getimagesize($source);
if ($info === false) return false;
$mime = $info['mime'];
// Load image
switch ($mime) {
case 'image/jpeg':
$image = @imagecreatefromjpeg($source);
break;
case 'image/png':
$image = @imagecreatefrompng($source);
break;
case 'image/gif':
$image = @imagecreatefromgif($source);
break;
case 'image/webp':
$image = @imagecreatefromwebp($source);
break;
default:
return false;
}
if ($image === false) return false;
$width = imagesx($image);
$height = imagesy($image);
// Start with 90% quality and reduce dimensions if needed
$quality = 90;
$scale = 1.0;
$tempFile = $source . '.tmp';
// Try progressive compression
while (true) {
// Calculate new dimensions
$newWidth = (int)($width * $scale);
$newHeight = (int)($height * $scale);
// Create resized image
$resized = imagecreatetruecolor($newWidth, $newHeight);
// Preserve transparency for PNG/GIF
if ($mime === 'image/png' || $mime === 'image/gif') {
imagealphablending($resized, false);
imagesavealpha($resized, true);
$transparent = imagecolorallocatealpha($resized, 255, 255, 255, 127);
imagefilledrectangle($resized, 0, 0, $newWidth, $newHeight, $transparent);
}
imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Save with current quality
if ($ext === 'jpg' || $ext === 'jpeg') {
imagejpeg($resized, $tempFile, $quality);
} elseif ($ext === 'png') {
// PNG compression level (0-9, where 9 is best compression)
$pngQuality = (int)((100 - $quality) / 11);
imagepng($resized, $tempFile, $pngQuality);
} elseif ($ext === 'webp') {
imagewebp($resized, $tempFile, $quality);
} else {
imagegif($resized, $tempFile);
}
imagedestroy($resized);
$fileSize = filesize($tempFile);
// If file is small enough, use it
if ($fileSize <= $maxSize) {
imagedestroy($image);
rename($tempFile, $source);
return true;
}
// If we've reduced too much, give up
if ($quality < 50 && $scale < 0.5) {
imagedestroy($image);
@unlink($tempFile);
return false;
}
// Reduce quality or scale
if ($quality > 50) {
$quality -= 10;
} else {
$scale -= 0.1;
}
}
}
// Function to generate thumbnail
function generateThumbnail($source, $destination, $width, $height) {
$info = getimagesize($source);
if ($info === false) return false;
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($source);
break;
case 'image/png':
$image = imagecreatefrompng($source);
break;
case 'image/gif':
$image = imagecreatefromgif($source);
break;
case 'image/webp':
$image = imagecreatefromwebp($source);
break;
default:
return false;
}
if ($image === false) return false;
$original_width = imagesx($image);
$original_height = imagesy($image);
// Calculate aspect ratio
$aspect_ratio = $original_width / $original_height;
if ($width / $height > $aspect_ratio) {
$new_width = $height * $aspect_ratio;
$new_height = $height;
} else {
$new_height = $width / $aspect_ratio;
$new_width = $width;
}
$thumbnail = imagecreatetruecolor($new_width, $new_height);
// Preserve transparency
imagealphablending($thumbnail, false);
imagesavealpha($thumbnail, true);
$transparent = imagecolorallocatealpha($thumbnail, 255, 255, 255, 127);
imagefilledrectangle($thumbnail, 0, 0, $new_width, $new_height, $transparent);
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);
// Save thumbnail
switch ($mime) {
case 'image/jpeg':
$result = imagejpeg($thumbnail, $destination, 85);
break;
case 'image/png':
$result = imagepng($thumbnail, $destination, 8);
break;
case 'image/gif':
$result = imagegif($thumbnail, $destination);
break;
case 'image/webp':
$result = imagewebp($thumbnail, $destination, 85);
break;
default:
$result = false;
}
imagedestroy($image);
imagedestroy($thumbnail);
return $result;
}
// Function to generate video thumbnail
function generateVideoThumbnail($source, $destination) {
// Check if ffmpeg is available
$ffmpeg = trim(shell_exec('which ffmpeg 2>/dev/null'));
if (empty($ffmpeg)) {
return false;
}
// Generate thumbnail from video at 1 second mark
// -i: input file
// -ss: seek to 1 second
// -vframes 1: extract one frame
// -vf: scale to 200x200 maintaining aspect ratio
$command = sprintf(
'%s -i %s -ss 00:00:01 -vframes 1 -vf "scale=200:200:force_original_aspect_ratio=decrease" %s 2>&1',
escapeshellarg($ffmpeg),
escapeshellarg($source),
escapeshellarg($destination)
);
exec($command, $output, $return_code);
return $return_code === 0 && file_exists($destination);
}
?>

View File

@@ -1,12 +1,9 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
defined($security_key) or exit;
//------------------------------------------
// Payment Creation (for Software Upgrades)
//------------------------------------------
// This endpoint creates a Mollie payment and stores transaction data
// This endpoint creates a payment (Mollie or PayPal) and stores transaction data
//Connect to DB
$pdo = dbConnect($dbname);
@@ -25,6 +22,14 @@ if (empty($post_content['serial_number']) || empty($post_content['version_id']))
$serial_number = $post_content['serial_number'];
$version_id = $post_content['version_id'];
$user_data = $post_content['user_data'] ?? [];
// Read payment_provider from top level first, then fallback to user_data
$payment_provider = $post_content['payment_provider'] ?? $user_data['payment_provider'] ?? 'mollie';
// Extract tax information from user_data (sent from frontend)
$item_price = $user_data['item_price'] ?? null; // Price without VAT
$tax_amount = $user_data['tax_amount'] ?? 0; // VAT amount
$payment_amount = $user_data['payment_amount'] ?? null; // Total including VAT
$vat_number = $user_data['vat_number'] ?? null; // VAT number
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 1: Get equipment data from serial_number
@@ -42,7 +47,8 @@ if (!$equipment) {
}
$equipment_id = $equipment['rowID'];
$current_sw_version = trim(strtolower(ltrim($equipment['sw_version'], '0')));
// Normalize software version for comparison (lowercase, trim leading zeros) - same as software_update.php line 96
$current_sw_version = strtolower(ltrim($equipment['sw_version'], '0'));
$sw_version_license = $equipment['sw_version_license'] ?? null;
$hw_version = $equipment['hw_version'] ?? '';
@@ -77,10 +83,13 @@ $path_count_result = $stmt->fetch(PDO::FETCH_ASSOC);
$has_upgrade_paths = ($path_count_result['path_count'] > 0);
if (!$has_upgrade_paths) {
// No upgrade paths defined = FREE (lines 240-242 in software_update.php)
// No upgrade paths defined = FREE (lines 328-331 in software_update.php)
$final_price = '0.00';
if (debug) {
debuglog("DEBUG: No upgrade paths defined for version_id $version_id - upgrade is FREE");
}
} else {
// Check for valid upgrade path FROM current version
// Check for valid upgrade path FROM current version (same logic as software_update.php lines 335-353)
$sql = 'SELECT pup.price, pup.currency
FROM products_software_upgrade_paths pup
JOIN products_software_versions from_ver ON pup.from_version_id = from_ver.rowID
@@ -91,14 +100,28 @@ if (!$has_upgrade_paths) {
$stmt->execute([$version_id, $current_sw_version]);
$upgrade_path = $stmt->fetch(PDO::FETCH_ASSOC);
if (debug) {
debuglog("DEBUG: Looking for upgrade path TO version_id=$version_id FROM current_sw_version='$current_sw_version'");
debuglog("DEBUG: Upgrade path result: " . json_encode($upgrade_path));
}
if ($upgrade_path) {
$final_price = $upgrade_path['price'] ?? '0.00';
$final_currency = $upgrade_path['currency'] ?? 'EUR';
if (debug) {
debuglog("DEBUG: Found upgrade path - price: $final_price $final_currency");
}
} else {
// No upgrade path FROM current version
if (debug) {
debuglog("ERROR: No valid upgrade path from current version '$current_sw_version' to version_id $version_id");
}
http_response_code(400);
echo json_encode(['error' => 'No valid upgrade path from current version'], JSON_UNESCAPED_UNICODE);
echo json_encode([
'error' => 'No valid upgrade path from current version',
'current_version' => $current_sw_version,
'target_version_id' => $version_id
], JSON_UNESCAPED_UNICODE);
exit;
}
}
@@ -137,67 +160,159 @@ if ($final_price <= 0) {
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 6: DEBUG MODE - Log but continue to real Mollie
// STEP 6: DEBUG MODE - Log
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
if (debug) {
debuglog("DEBUG MODE: Creating real Mollie payment for testing");
debuglog("DEBUG MODE: Creating $payment_provider payment for testing");
debuglog("DEBUG: Serial Number: $serial_number, Version ID: $version_id, Price: $final_price");
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 7: Call Mollie API to create payment
// STEP 7: Create payment based on provider
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
try {
// Initialize Mollie
require dirname(__FILE__, 4).'/initialize.php';
// Use payment_amount (with tax) if provided, otherwise use final_price
$amount_to_charge = $payment_amount ? (float)$payment_amount : (float)$final_price;
// Format price for Mollie (must be string with 2 decimals)
$formatted_price = number_format((float)$final_price, 2, '.', '');
// Format price (must be string with 2 decimals)
$formatted_price = number_format($amount_to_charge, 2, '.', '');
if (debug) {
debuglog("DEBUG: Item Price (excl. VAT): " . ($item_price ?? $final_price));
debuglog("DEBUG: Tax Amount: " . $tax_amount);
debuglog("DEBUG: Total Amount (incl. VAT): " . $amount_to_charge);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 7A: Generate transaction ID BEFORE creating Mollie payment
// STEP 7A: Generate transaction ID BEFORE creating payment
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// Generate unique transaction ID (same as placeorder.php)
$txn_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5));
// Build webhook URL and redirect URL with actual transaction ID
// Build URLs
$protocol = 'https';
$hostname = $_SERVER['SERVER_NAME'];
$path = '/';
$webhook_url = "{$protocol}://{$hostname}{$path}webhook_mollie.php";
$redirect_url = "{$protocol}://{$hostname}{$path}?page=softwaretool&payment_return=1&order_id={$txn_id}";
if (debug) {
debuglog("DEBUG: Transaction ID: {$txn_id}");
debuglog("DEBUG: redirectUrl being sent to Mollie: " . $redirect_url);
debuglog("DEBUG: Redirect URL: " . $redirect_url);
}
// Create payment with Mollie
$payment = $mollie->payments->create([
'amount' => [
'currency' => $final_currency ?: 'EUR',
'value' => "{$formatted_price}"
],
'description' => "Software upgrade Order #{$txn_id}",
'redirectUrl' => "{$redirect_url}",
'webhookUrl' => "{$webhook_url}",
'metadata' => [
'order_id' => $txn_id,
'serial_number' => $serial_number,
'version_id' => $version_id,
'equipment_id' => $equipment_id
]
]);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// Create payment based on selected provider
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
if ($payment_provider === 'paypal') {
//==========================================
// PAYPAL PAYMENT CREATION
//==========================================
$cancel_url = "{$protocol}://{$hostname}{$path}?page=softwaretool&payment_return=cancelled&order_id={$txn_id}";
// Get PayPal access token
$access_token = getPayPalAccessToken();
$mollie_payment_id = $payment->id;
$checkout_url = $payment->getCheckoutUrl();
// Create PayPal order
$order_data = [
'intent' => 'CAPTURE',
'purchase_units' => [[
'custom_id' => $txn_id,
'description' => "Software upgrade Order #{$txn_id}",
'amount' => [
'currency_code' => $final_currency ?: 'EUR',
'value' => $formatted_price
],
'payee' => [
'email_address' => email
]
]],
'application_context' => [
'return_url' => $redirect_url,
'cancel_url' => $cancel_url,
'brand_name' => site_name,
'user_action' => 'PAY_NOW'
]
];
$ch = curl_init(PAYPAL_URL . '/v2/checkout/orders');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($order_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $access_token
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code != 200 && $http_code != 201) {
debuglog("PayPal API Error: HTTP $http_code - Response: $response");
throw new Exception("PayPal order creation failed: HTTP $http_code");
}
$paypal_order = json_decode($response, true);
$payment_id = $paypal_order['id'] ?? null;
// Extract approval URL
$checkout_url = '';
foreach ($paypal_order['links'] ?? [] as $link) {
if ($link['rel'] === 'approve') {
$checkout_url = $link['href'];
break;
}
}
if (!$checkout_url) {
throw new Exception("No approval URL received from PayPal");
}
$payment_method_id = 3; // PayPal
$payment_metadata = 'paypal_order_id';
} else {
//==========================================
// MOLLIE PAYMENT CREATION
//==========================================
// Initialize Mollie
require dirname(__FILE__, 4).'/initialize.php';
$webhook_url = "{$protocol}://{$hostname}{$path}webhook_mollie.php";
// Create payment with Mollie
$payment = $mollie->payments->create([
'amount' => [
'currency' => $final_currency ?: 'EUR',
'value' => "{$formatted_price}"
],
'description' => "Software upgrade Order #{$txn_id}",
'redirectUrl' => "{$redirect_url}",
'webhookUrl' => "{$webhook_url}",
'metadata' => [
'order_id' => $txn_id,
'serial_number' => $serial_number,
'version_id' => $version_id,
'equipment_id' => $equipment_id
]
]);
$payment_id = $payment->id;
$checkout_url = $payment->getCheckoutUrl();
if (debug) {
debuglog("DEBUG: Mollie payment created successfully");
debuglog("DEBUG: Payment ID: $payment_id");
debuglog("DEBUG: Redirect URL sent: $redirect_url");
debuglog("DEBUG: Checkout URL: $checkout_url");
}
$payment_method_id = 1; // Mollie
$payment_metadata = 'mollie_payment_id';
}
if (debug) {
debuglog("DEBUG: Mollie payment created successfully");
debuglog("DEBUG: Payment ID: $mollie_payment_id");
debuglog("DEBUG: Redirect URL sent: $redirect_url");
debuglog("DEBUG: Redirect URL from Mollie object: " . $payment->redirectUrl);
debuglog("DEBUG: Full payment object: " . json_encode($payment));
debuglog("DEBUG: Payment created via $payment_provider");
debuglog("DEBUG: Payment ID: $payment_id");
debuglog("DEBUG: Checkout URL: $checkout_url");
}
@@ -213,13 +328,14 @@ try {
// BUILD UP PARTNERHIERARCHY FROM USER
$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);
$sql = 'INSERT INTO transactions (txn_id, payment_amount, payment_status, payer_email, first_name, last_name,
address_street, address_city, address_state, address_zip, address_country, account_id, payment_method, accounthierarchy, created)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$sql = 'INSERT INTO transactions (txn_id, payment_amount, tax_amount, payment_status, payer_email, first_name, last_name,
address_street, address_city, address_state, address_zip, address_country, account_id, payment_method, accounthierarchy, created, vat_number)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
$txn_id, // Use generated transaction ID, not Mollie payment ID
$final_price,
$txn_id,
$amount_to_charge, // Total amount including tax
$tax_amount, // Tax amount
0, // 0 = pending
$user_data['email'] ?? '',
$first_name,
@@ -230,9 +346,10 @@ try {
$user_data['postal'] ?? '',
$user_data['country'] ?? '',
$serial_number,
0, // payment method
$payment_method_id, // 0 = Mollie, 1 = PayPal
$partner_product,
date('Y-m-d H:i:s')
date('Y-m-d H:i:s'),
$vat_number
]);
// Get the database ID
@@ -245,16 +362,19 @@ try {
'serial_number' => $serial_number,
'equipment_id' => $equipment_id,
'hw_version' => $hw_version,
'mollie_payment_id' => $mollie_payment_id // Store Mollie payment ID in options
$payment_metadata => $payment_id // Store payment provider ID
], JSON_UNESCAPED_UNICODE);
// Use item_price (without VAT) if provided, otherwise use final_price
$item_price_to_store = $item_price ? (float)$item_price : (float)$final_price;
$sql = 'INSERT INTO transactions_items (txn_id, item_id, item_price, item_quantity, item_options, created)
VALUES (?, ?, ?, ?, ?, ?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([
$transaction_id, // Use database transaction ID (not txn_id string, not mollie_payment_id)
$transaction_id,
$version_id,
$final_price,
$item_price_to_store, // Price without VAT
1,
$item_options,
date('Y-m-d H:i:s')
@@ -265,7 +385,7 @@ try {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
$messages = json_encode([
'checkout_url' => $checkout_url,
'payment_id' => $mollie_payment_id
'payment_id' => $payment_id
], JSON_UNESCAPED_UNICODE);
echo $messages;
@@ -275,4 +395,27 @@ try {
exit;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// Helper function to get PayPal access token
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
function getPayPalAccessToken() {
$ch = curl_init(PAYPAL_URL . '/v1/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_USERPWD, PAYPAL_CLIENT_ID . ':' . PAYPAL_CLIENT_SECRET);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code != 200) {
throw new Exception("Failed to get PayPal access token: HTTP $http_code");
}
$result = json_decode($response, true);
return $result['access_token'] ?? '';
}
?>

View File

@@ -46,7 +46,8 @@ if (isset($post_content['cart']) && isset($post_content['checkout_input']) && is
'address_state' => $post_content['customer_details']['address_state'] ?? '',
'address_zip' => $post_content['customer_details']['address_zip'] ?? '',
'address_country' => $post_content['customer_details']['address_country'] ?? '',
'address_phone' => $post_content['customer_details']['address_phone'] ?? ''
'address_phone' => $post_content['customer_details']['address_phone'] ?? '',
'vat_number' => $post_content['customer_details']['vat_number'] ?? ''
];
//Initialize calculator
@@ -75,7 +76,7 @@ if (isset($post_content['cart']) && isset($post_content['checkout_input']) && is
$txn_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5));
// Insert transaction header
$stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, address_phone, account_id, payment_method, shipping_method, shipping_amount, discount_amount, discount_code, tax_amount,accounthierarchy) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
$stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, address_phone, account_id, payment_method, shipping_method, shipping_amount, discount_amount, discount_code, tax_amount,accounthierarchy, vat_number) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
$stmt->execute([
$txn_id,
$total,
@@ -96,7 +97,8 @@ if (isset($post_content['cart']) && isset($post_content['checkout_input']) && is
$discounttotal,
$checkout_input['discount_code'],
$taxtotal,
$partner_product
$partner_product,
$customer_details['vat_number']
]);
// Get order ID
$transaction_id = $pdo->lastInsertId();

View File

@@ -22,7 +22,7 @@ $command = ($id == '')? 'insert' : 'update'; //IF rowID = empty then INSERT
if (isset($post_content['delete'])){$command = 'delete';} //change command to delete
// Check for bulk creation
$is_bulk = isset($post_content['bulk']) && $post_content['bulk'] === true;
$is_bulk = isset($post_content['bulk']) && ($post_content['bulk'] === "true" || $post_content['bulk'] === true);
$date = date('Y-m-d H:i:s');
@@ -37,12 +37,24 @@ $input_insert = '';
if ($command == 'insert' && $is_bulk && isAllowed('products_software_licenses',$profile,$permission,'C') === 1){
$version_id = $post_content['version_id'] ?? '';
$serials = $post_content['serials'] ?? [];
$serials_input = $post_content['serials'] ?? '';
// Convert comma-separated string to array and trim whitespace
if (is_string($serials_input)) {
$serials = array_map('trim', explode(',', $serials_input));
} elseif (is_array($serials_input)) {
$serials = $serials_input;
} else {
$serials = [];
}
$transaction_id = $post_content['transaction_id'] ?? '';
$license_type = $post_content['license_type'] ?? 0;
$status = $post_content['status'] ?? 0;
$status = $post_content['status'] ?? 1;
$starts_at = $post_content['starts_at'] ?? date('Y-m-d H:i:s');
$expires_at = $post_content['expires_at'] ?? '2099-12-31 23:59:59'; // effectively permanent
if (empty($version_id) || empty($serials) || !is_array($serials)) {
if (empty($version_id) || empty($serials)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid parameters for bulk creation']);
exit;
@@ -51,8 +63,8 @@ if ($command == 'insert' && $is_bulk && isAllowed('products_software_licenses',$
$accounthierarchy = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);
// Prepare statement for bulk insert
$sql = 'INSERT INTO products_software_licenses (version_id, license_key, license_type, status, transaction_id, accounthierarchy, created, createdby)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
$sql = 'INSERT INTO products_software_licenses (version_id, license_key, license_type, status, starts_at, expires_at, transaction_id, accounthierarchy, created, createdby)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $pdo->prepare($sql);
$created_count = 0;
@@ -60,13 +72,7 @@ if ($command == 'insert' && $is_bulk && isAllowed('products_software_licenses',$
if (empty($serial)) continue;
// Generate UUID for license key
$license_key = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
$license_key = generateUniqueLicenseKey();
try {
$stmt->execute([
@@ -74,6 +80,8 @@ if ($command == 'insert' && $is_bulk && isAllowed('products_software_licenses',$
$license_key,
$license_type,
$status,
$starts_at,
$expires_at,
$transaction_id,
$accounthierarchy,
$date,
@@ -81,9 +89,9 @@ if ($command == 'insert' && $is_bulk && isAllowed('products_software_licenses',$
]);
// Assign license to equipment if serial number exists
$eq_sql = 'UPDATE equipment SET sw_version_license = ? WHERE serialnumber = ? AND accounthierarchy LIKE ?';
$eq_sql = 'UPDATE equipment SET sw_version_license = ? WHERE serialnumber = ? ';
$eq_stmt = $pdo->prepare($eq_sql);
$eq_stmt->execute([$license_key, $serial, '%'.$partner->soldto.'%']);
$eq_stmt->execute([$license_key, $serial]);
$created_count++;
} catch (Exception $e) {
@@ -104,17 +112,8 @@ if ($command == 'update'){
$post_content['updatedby'] = $username;
}
elseif ($command == 'insert'){
// Generate UUID for license key if not provided
if (empty($post_content['license_key'])) {
$post_content['license_key'] = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
// Generate UUID for license key
$post_content['license_key'] = generateUniqueLicenseKey();
$post_content['created'] = $date;
$post_content['createdby'] = $username;
$post_content['accounthierarchy'] = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);

View File

@@ -14,7 +14,7 @@ $post_content = json_decode($input,true);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclauselvl2("software_upgrade_paths",$permission,$partner,'');
list($whereclause,$condition) = getWhereclauselvl2("",$permission,$partner,'');
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID

View File

@@ -0,0 +1,124 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Report Builder - POST Endpoints
//------------------------------------------
// Set content type to JSON
header('Content-Type: application/json');
// Connect to DB
$pdo = dbConnect($dbname);
// Parse input data
$data = json_decode($input, true);
$action = strtolower($data['action'] ?? '');
/**
* Security check: Only allow SELECT queries
*/
function isSelectQuery($query) {
$query = trim($query);
$query = preg_replace('/\s+/', ' ', $query); // Normalize whitespace
// Only allow SELECT queries
if (!preg_match('/^SELECT\s/i', $query)) {
return false;
}
// Block dangerous keywords that could be used for injection
$dangerousPatterns = [
'/;\s*DROP\s/i',
'/;\s*DELETE\s/i',
'/;\s*UPDATE\s/i',
'/;\s*INSERT\s/i',
'/;\s*CREATE\s/i',
'/;\s*ALTER\s/i',
'/;\s*TRUNCATE\s/i',
'/INTO\s+OUTFILE\s/i',
'/LOAD_FILE\s*\(/i',
'/SLEEP\s*\(/i',
'/BENCHMARK\s*\(/i',
];
foreach ($dangerousPatterns as $pattern) {
if (preg_match($pattern, $query)) {
return false;
}
}
return true;
}
/**
* Execute a SELECT query
*/
if ($action === 'executequery') {
$query = $data['query'] ?? '';
if (empty($query)) {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Query parameter is required'
], JSON_UNESCAPED_UNICODE);
}
// Security check: only allow SELECT queries
elseif (!isSelectQuery($query)) {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Only SELECT queries are allowed'
], JSON_UNESCAPED_UNICODE);
} else {
try {
// Execute the query
$stmt = $pdo->query($query);
// Fetch all results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get row count
$rowCount = count($results);
// Limit results to prevent memory issues
$maxResults = 5000;
if ($rowCount > $maxResults) {
$results = array_slice($results, 0, $maxResults);
$message = "Query executed successfully. Showing first $maxResults of $rowCount rows.";
} else {
$message = "Query executed successfully. $rowCount rows returned.";
}
$messages = json_encode([
'success' => true,
'results' => $results,
'rowCount' => $rowCount,
'message' => $message
], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Query execution failed: ' . $e->getMessage()
], JSON_UNESCAPED_UNICODE);
}
}
}
/**
* Invalid or missing action
*/
else {
http_response_code(400);
$messages = json_encode([
'success' => false,
'message' => 'Invalid or missing action parameter'
], JSON_UNESCAPED_UNICODE);
}
// Send results
echo $messages;
?>

View File

@@ -0,0 +1,75 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Role Access Permissions
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//CONTENT FROM API (POST)
$post_content = json_decode($input,true);
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? '';
$command = ($id == '')? 'insert' : 'update';
if (isset($post_content['delete'])){$command = 'delete';}
$date = date('Y-m-d H:i:s');
//CREATE EMPTY STRINGS
$clause = '';
$clause_insert ='';
$input_insert = '';
$execute_input = [];
$criterias = [];
//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){
$post_content['updatedby'] = $username;
$post_content['updated'] = $date;
}
elseif ($command == 'insert'){
$post_content['created'] = $date;
$post_content['createdby'] = $username;
}
//CREAT NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){
foreach ($post_content as $key => $var){
if ($key == 'submit' || $key == 'rowID' || str_contains($key, 'old_')){
//do nothing
}
else {
$criterias[$key] = $var;
$clause .= ' , '.$key.' = ?';
$clause_insert .= ' , '.$key.'';
$input_insert .= ', ?';
$execute_input[]= $var;
}
}
}
//CLEAN UP INPUT
$clause = substr($clause, 2);
$clause_insert = substr($clause_insert, 2);
$input_insert = substr($input_insert, 1);
//QUERY AND VERIFY ALLOWED
if ($command == 'update' && isAllowed('user_role_manage',$profile,$permission,'U') === 1){
$sql = 'UPDATE role_access_permissions SET '.$clause.' WHERE rowID = ?';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'insert' && isAllowed('user_role_manage',$profile,$permission,'C') === 1){
$sql = 'INSERT INTO role_access_permissions ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'delete' && isAllowed('user_role_manage',$profile,$permission,'D') === 1){
//Delete permission
$stmt = $pdo->prepare('DELETE FROM role_access_permissions WHERE rowID = ?');
$stmt->execute([$id]);
}
?>

View File

@@ -0,0 +1,141 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// User Role Assignments
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//CONTENT FROM API (POST)
$post_content = json_decode($input,true);
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? '';
$date = date('Y-m-d H:i:s');
//------------------------------------------
// BATCH UPDATE - Update all roles for a user
//------------------------------------------
if (isset($post_content['batch_update']) && isset($post_content['user_id']) && isAllowed('user_manage',$profile,$permission,'U') === 1){
$user_id = $post_content['user_id'];
$selected_roles = $post_content['roles'] ?? [];
//Get currently assigned active roles
$stmt = $pdo->prepare('SELECT role_id, rowID FROM user_role_assignments WHERE user_id = ? AND is_active = 1');
$stmt->execute([$user_id]);
$current_roles = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$current_roles[$row['role_id']] = $row['rowID'];
}
//Remove roles that are no longer selected (soft delete)
foreach ($current_roles as $role_id => $assignment_id){
if (!in_array($role_id, $selected_roles)){
$stmt = $pdo->prepare('UPDATE user_role_assignments SET is_active = 0, updatedby = ?, updated = ? WHERE rowID = ?');
$stmt->execute([$username, $date, $assignment_id]);
}
}
//Add new roles that are selected but not currently assigned
foreach ($selected_roles as $role_id){
if (!array_key_exists($role_id, $current_roles)){
//Check if this user-role combination existed before (inactive)
$stmt = $pdo->prepare('SELECT rowID FROM user_role_assignments WHERE user_id = ? AND role_id = ? AND is_active = 0 LIMIT 1');
$stmt->execute([$user_id, $role_id]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);
if ($existing){
//Reactivate existing assignment
$stmt = $pdo->prepare('UPDATE user_role_assignments SET is_active = 1, assigned_by = ?, assigned_at = ?, updatedby = ?, updated = ? WHERE rowID = ?');
$stmt->execute([$username, $date, $username, $date, $existing['rowID']]);
} else {
//Create new assignment
$stmt = $pdo->prepare('INSERT INTO user_role_assignments (user_id, role_id, is_active, assigned_by, assigned_at, created, createdby) VALUES (?, ?, 1, ?, ?, ?, ?)');
$stmt->execute([$user_id, $role_id, $username, $date, $date, $userkey]);
}
}
}
}
//------------------------------------------
// SINGLE OPERATIONS (for backward compatibility or direct API calls)
//------------------------------------------
else {
$command = ($id == '')? 'insert' : 'update';
if (isset($post_content['delete'])){$command = 'delete';}
//CREATE EMPTY STRINGS
$clause = '';
$clause_insert ='';
$input_insert = '';
$execute_input = [];
$criterias = [];
//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){
$post_content['updatedby'] = $username;
$post_content['updated'] = $date;
}
elseif ($command == 'insert'){
$post_content['created'] = $date;
$post_content['createdby'] = $username;
$post_content['assigned_by'] = $username;
$post_content['assigned_at'] = $date;
}
//CREAT NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){
foreach ($post_content as $key => $var){
if ($key == 'submit' || $key == 'rowID' || $key == 'delete' || $key == 'batch_update' || str_contains($key, 'old_')){
//do nothing
}
else {
$criterias[$key] = $var;
$clause .= ' , '.$key.' = ?';
$clause_insert .= ' , '.$key.'';
$input_insert .= ', ?';
$execute_input[]= $var;
}
}
}
//CLEAN UP INPUT
$clause = substr($clause, 2);
$clause_insert = substr($clause_insert, 2);
$input_insert = substr($input_insert, 1);
//QUERY AND VERIFY ALLOWED
if ($command == 'update' && isAllowed('user_manage',$profile,$permission,'U') === 1){
$sql = 'UPDATE user_role_assignments SET '.$clause.' WHERE rowID = ?';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'insert' && isAllowed('user_manage',$profile,$permission,'C') === 1){
//Check if this user-role combination already exists (including inactive ones)
$stmt = $pdo->prepare('SELECT rowID, is_active FROM user_role_assignments WHERE user_id = ? AND role_id = ? LIMIT 1');
$stmt->execute([$post_content['user_id'], $post_content['role_id']]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);
if ($existing){
//If exists but inactive, reactivate it
if ($existing['is_active'] == 0){
$stmt = $pdo->prepare('UPDATE user_role_assignments SET is_active = 1, assigned_by = ?, assigned_at = ?, updatedby = ?, updated = ? WHERE rowID = ?');
$stmt->execute([$username, $date, $username, $date, $existing['rowID']]);
}
//If already active, do nothing (or could throw an error)
} else {
//Insert new assignment
$sql = 'INSERT INTO user_role_assignments ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
}
elseif ($command == 'delete' && isAllowed('user_manage',$profile,$permission,'D') === 1){
//Soft delete by setting is_active to 0
$stmt = $pdo->prepare('UPDATE user_role_assignments SET is_active = 0, updatedby = ?, updated = ? WHERE rowID = ?');
$stmt->execute([$username, $date, $id]);
}
}
?>

123
api/v2/post/user_roles.php Normal file
View File

@@ -0,0 +1,123 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// User Roles
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//CONTENT FROM API (POST)
$post_content = json_decode($input,true);
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? '';
$command = ($id == '')? 'insert' : 'update';
if (isset($post_content['delete'])){$command = 'delete';}
$date = date('Y-m-d H:i:s');
//CREATE EMPTY STRINGS
$clause = '';
$clause_insert ='';
$input_insert = '';
$execute_input = [];
$criterias = [];
//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){
$post_content['updatedby'] = $username;
$post_content['updated'] = $date;
}
elseif ($command == 'insert'){
$post_content['created'] = $date;
$post_content['createdby'] = $username;
}
//CREAT NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){
foreach ($post_content as $key => $var){
if ($key == 'submit' || $key == 'rowID' || $key == 'permissions' || str_contains($key, 'old_')){
//do nothing
}
else {
$criterias[$key] = $var;
$clause .= ' , '.$key.' = ?';
$clause_insert .= ' , '.$key.'';
$input_insert .= ', ?';
$execute_input[]= $var;
}
}
}
//CLEAN UP INPUT
$clause = substr($clause, 2);
$clause_insert = substr($clause_insert, 2);
$input_insert = substr($input_insert, 1);
//QUERY AND VERIFY ALLOWED
if ($command == 'update' && isAllowed('user_role_manage',$profile,$permission,'U') === 1){
$sql = 'UPDATE user_roles SET '.$clause.' WHERE rowID = ?';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
//Handle permissions update
if (isset($post_content['permissions'])){
//First delete all existing permissions for this role
$stmt = $pdo->prepare('DELETE FROM role_access_permissions WHERE role_id = ?');
$stmt->execute([$id]);
//Insert new permissions
foreach ($post_content['permissions'] as $access_id => $perms){
$can_create = isset($perms['can_create']) ? 1 : 0;
$can_read = isset($perms['can_read']) ? 1 : 0;
$can_update = isset($perms['can_update']) ? 1 : 0;
$can_delete = isset($perms['can_delete']) ? 1 : 0;
//Only insert if at least one permission is set
if ($can_create || $can_read || $can_update || $can_delete){
$stmt = $pdo->prepare('INSERT INTO role_access_permissions (role_id, access_id, can_create, can_read, can_update, can_delete, created, createdby) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->execute([$id, $access_id, $can_create, $can_read, $can_update, $can_delete, $date, $userkey]);
}
}
}
}
elseif ($command == 'insert' && isAllowed('user_role_manage',$profile,$permission,'C') === 1){
$sql = 'INSERT INTO user_roles ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
//Get the new role ID
$new_role_id = $pdo->lastInsertId();
//Handle permissions for new role
if (isset($post_content['permissions'])){
foreach ($post_content['permissions'] as $access_id => $perms){
$can_create = isset($perms['can_create']) ? 1 : 0;
$can_read = isset($perms['can_read']) ? 1 : 0;
$can_update = isset($perms['can_update']) ? 1 : 0;
$can_delete = isset($perms['can_delete']) ? 1 : 0;
//Only insert if at least one permission is set
if ($can_create || $can_read || $can_update || $can_delete){
$stmt = $pdo->prepare('INSERT INTO role_access_permissions (role_id, access_id, can_create, can_read, can_update, can_delete, created, createdby) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->execute([$new_role_id, $access_id, $can_create, $can_read, $can_update, $can_delete, $date, $userkey]);
}
}
}
}
elseif ($command == 'delete' && isAllowed('user_role_manage',$profile,$permission,'D') === 1){
//Delete role permissions first (foreign key constraint)
$stmt = $pdo->prepare('DELETE FROM role_access_permissions WHERE role_id = ?');
$stmt->execute([$id]);
//Delete user role assignments
$stmt = $pdo->prepare('DELETE FROM user_role_assignments WHERE role_id = ?');
$stmt->execute([$id]);
//Delete role
$stmt = $pdo->prepare('DELETE FROM user_roles WHERE rowID = ?');
$stmt->execute([$id]);
}
?>

View File

@@ -44,12 +44,13 @@ $user_name_old = $user_data['username'];
$view_old = $user_data['view'];
$partnerhierarchy_old = json_decode($user_data['partnerhierarchy']);
$salesid_new = ((isset($post_content['salesid']) && $post_content['salesid'] != '' && $post_content['salesid'] != $partnerhierarchy_old->salesid)? $post_content['salesid'] : $partnerhierarchy_old->salesid);
$soldto_new = ((isset($post_content['soldto']) && $post_content['soldto'] != '' && $post_content['soldto'] != $partnerhierarchy_old->soldto)? $post_content['soldto'] : $partnerhierarchy_old->soldto);
$shipto_new = ((isset($post_content['shipto']) && $post_content['shipto'] != '' && $post_content['shipto'] != $partnerhierarchy_old->shipto)? $post_content['shipto'] : $partnerhierarchy_old->shipto);
$location_new = ((isset($post_content['location']) && $post_content['location'] != '' && $post_content['location'] != $partnerhierarchy_old->location)? $post_content['location'] : $partnerhierarchy_old->location);
// Allow clearing values by checking if key exists (even if empty)
$salesid_new = (array_key_exists('salesid', $post_content)) ? $post_content['salesid'] : ($partnerhierarchy_old->salesid ?? '');
$soldto_new = (array_key_exists('soldto', $post_content)) ? $post_content['soldto'] : ($partnerhierarchy_old->soldto ?? '');
$shipto_new = (array_key_exists('shipto', $post_content)) ? $post_content['shipto'] : ($partnerhierarchy_old->shipto ?? '');
$location_new = (array_key_exists('location', $post_content)) ? $post_content['location'] : ($partnerhierarchy_old->location ?? '');
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$salesid_new,
@@ -57,7 +58,7 @@ $location_new = ((isset($post_content['location']) && $post_content['location']
"shipto"=>$shipto_new,
"location"=>$location_new
);
}elseif ($permission == 3) {
}elseif (getHierarchyLevel($partner) == 1) {
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$partner->salesid,
@@ -76,7 +77,7 @@ $location_new = ((isset($post_content['location']) && $post_content['location']
}
} elseif ($command == 'insert') {
//ID is empty => INSERT / NEW RECORD
if ($permission == 4){
if (getHierarchyLevel($partner) == 0){
//ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
$account = array(
"salesid"=>$post_content['salesid'],
@@ -85,7 +86,7 @@ $location_new = ((isset($post_content['location']) && $post_content['location']
"location"=>$post_content['location']
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
//ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
$account = array(
"salesid"=>$partner->salesid,
@@ -153,12 +154,15 @@ else {
//+++++++++++++++++++++++++++++++++++++++++++++
//RESET VIEW/PERMISSION BASED ON USER PERMISSION
//+++++++++++++++++++++++++++++++++++++++++++++
$hierarchy_level = getHierarchyLevel($partner);
if($post_content['view']){
switch ($permission) {
case '4':
switch ($hierarchy_level) {
case '0':
//ADMIN+ no override
break;
case '3':
case '1':
//ADMINS cannot set ADMIN+ => reset to admin
$post_content['view'] = ($post_content['view'] == 5) ? 4 : $post_content['view'];
break;