109 Commits

Author SHA1 Message Date
“VeLiTi”
3131c2c5b2 Refactor invoice PDF generation and VAT validation
- Updated PDF template to display a fixed software code instead of "SOFTWARE".
- Changed VAT label to include tax label dynamically and set to 0% for certain conditions.
- Enhanced JavaScript for VAT number validation with asynchronous checks against the VIES database.
- Implemented debounce for VAT number input to optimize validation calls.
- Updated country settings to include country codes for VAT validation.
- Modified email sending functions in webhook handlers to use dynamic attachment names for invoices.
2026-02-06 16:02:56 +01:00
“VeLiTi”
4b83f596f1 Refactor RBAC migration scripts and update configuration handling
- Removed old migration scripts for profiles and users to RBAC.
- Updated config redirector to utilize environment variables for configuration loading.
- Added .gitignore files to firmware, log, and marketing directories to prevent unnecessary file tracking.
- Introduced new configuration files for acceptance, development, and production environments with relevant settings.
- Enhanced settings files to include exception lists, security keys, and database settings.
2026-02-06 13:34:54 +01:00
“VeLiTi”
4564a4a04b Add session regeneration after token refresh to enhance security 2026-02-05 16:38:19 +01:00
“VeLiTi”
d7b9b91bb6 Refactor authorization and token refresh logic; update tax handling and invoice generation
- Changed variable name from `$stmt_service` to `$stmt_refreshkey` for clarity in `authorization.php` and `token_refresh.php`.
- Added null coalescing operator to ensure criteria are set to an empty string if not provided in `products_software_versions.php`.
- Modified SQL script to add `eu` column to `taxes` table and update tax rates based on EU membership.
- Enhanced invoice generation logic in `functions.php` to include VAT notes based on customer country and VAT number.
- Updated email and PDF templates to display VAT notes and percentages correctly.
- Adjusted JavaScript tax calculation logic to handle VAT based on country and VAT number.
- Fixed API URL in `index.php` for token refresh endpoint.
- Updated countries data structure in `countries.php` to include EU membership status.
2026-02-05 15:26:41 +01:00
“VeLiTi”
c4cb99b945 Implement token refresh logic and add refreshkey to user management 2026-02-05 14:00:36 +01:00
“VeLiTi”
b34733f9b7 Update invoice header and footer images for improved branding 2026-02-05 11:48:31 +01:00
“VeLiTi”
e85794c580 Update invoice templates to use a consistent invoice identification number format 2026-02-05 10:27:47 +01:00
“VeLiTi”
ee426cf5ea Enhance partner dropdowns to include authorization permissions across various management pages. Implement hardware version checks with warning modals for restricted versions. Update translations for hardware compatibility notices in multiple languages. Refactor SQL and PHP files to improve code clarity and maintainability. 2026-02-05 10:10:26 +01:00
“VeLiTi”
5223f6bdfd Implement downgrade prevention for paid software versions and update invoice templates with new contact details 2026-02-03 12:46:59 +01:00
“VeLiTi”
e97d2e5ef2 Refactor partner dropdowns to utilize authorization permissions across various management pages. Enhance invoice creation in webhooks to include account hierarchy. Add marketing system migration script for transitioning files to database structure. 2026-02-03 09:10:33 +01:00
“VeLiTi”
0648b69eff Add configuration for warranty, payment options, and bookkeeping integration
- Defined constants for warranty months, eligibility window, and service months.
- Enabled automatic invoice forwarding to bookkeeping software with email configuration.
- Integrated payment options for Mollie and PayPal, including API keys and webhook settings.
- Disabled pay on delivery option.
2026-02-03 08:55:52 +01:00
“VeLiTi”
2427d40273 Update salesid and soldto inclusion based on hierarchy level visibility in mass update form 2026-01-30 10:56:34 +01:00
“VeLiTi”
162933affa Refactor geolocation queries to use AND conditions for better accuracy. Update permission checks for equipment management to utilize unified 'equipment' scope. Enhance user role assignment logic to ensure correct username usage. Improve session error handling in login and index files for clearer user feedback. 2026-01-30 10:02:45 +01:00
“VeLiTi”
b3327f21ed Refactor user permission handling to utilize hierarchy levels across user credential retrieval and role management. Update permission checks in user_roles.php and enhance session management in index.php for improved security and consistency. 2026-01-30 09:17:54 +01:00
“VeLiTi”
8df518d0a2 Refactor permission checks to utilize hierarchy levels for access control in equipment, partner, user, and mass update pages. Update conditions to validate permissions based on user hierarchy instead of fixed permission values. 2026-01-29 20:13:48 +01:00
“VeLiTi”
3043076dba Refactor user role permission checks to utilize a unified 'user' scope for access control. Update user management permissions in user.php and users.php for consistency. Enhance listPartner function to apply hierarchy-based restrictions for partner retrieval. 2026-01-29 20:01:46 +01:00
“VeLiTi”
2dd054d145 fix scripts.js 2026-01-29 19:32:23 +01:00
“VeLiTi”
90472e3673 Enhance payment processing by adding VAT number handling and updating transaction retrieval logic. Refactor user role migration script for improved role assignments and streamline software tool functionality with maintenance mode checks and UI updates. 2026-01-29 19:25:13 +01:00
“VeLiTi”
0723df4516 Refactor permission handling to utilize hierarchy levels for access control across multiple API endpoints, enhancing permission validation logic in contracts, history, application, and user management. 2026-01-29 10:58:03 +01:00
“VeLiTi”
0b090699b8 Refactor permission checks in multiple files to ensure correct access control for communications, users, downloads, and translations. Updated conditions to validate permissions based on user roles. 2026-01-28 14:38:08 +01:00
“VeLiTi”
9e5f5581be Refactor permission checks across multiple files to utilize isAllowed function for better access control management. Updated hierarchy level checks in account, contracts, equipments, partners, users, and API endpoints to streamline permission validation. Enhanced download options visibility based on user permissions in various reports and management pages. Improved modal behavior and auto-installation process in software tool after payment success. Added new helper functions for building dynamic where clauses based on user hierarchy levels. 2026-01-28 14:32:49 +01:00
“VeLiTi”
f7733b4113 Add VAT number handling in order processing and invoice templates 2026-01-27 18:36:21 +01:00
“VeLiTi”
f7a91737bc Implement RBAC migration and role management enhancements
- Added AJAX functionality to fetch role permissions for copying.
- Introduced system role management with permission checks for updates.
- Implemented role deletion with confirmation modal and backend handling.
- Enhanced user role assignment migration scripts to transition from legacy profiles to RBAC.
- Created SQL migration scripts for user roles and permissions mapping.
- Updated user interface to support new role management features including copy permissions and system role indicators.
2026-01-27 15:10:21 +01:00
“VeLiTi”
aeda4e4cb9 Refactor user permissions handling and enhance menu functionality with collapsible headers 2026-01-21 12:48:46 +01:00
“VeLiTi”
18469fe958 Refactor authorization checks to use 'permissions' instead of 'profile' in multiple files
- Updated authorization checks in product management, product attributes, configurations, software, and user management files to use 'permissions' for consistency.
- Ensured that all relevant pages correctly check user permissions for read, update, delete, and create actions.
- Adjusted session variable references to align with the new permissions structure across various modules.
2026-01-20 15:00:00 +01:00
“VeLiTi”
24481279d5 Refactor user session handling and permissions management
- Updated session variables to use 'authorization' array instead of 'username' for user identification across multiple files.
- Introduced a new function `getUserPermissions` to consolidate user permissions retrieval based on assigned roles.
- Modified API calls to use the new authorization structure and updated endpoints to v2.
- Enhanced language support by adding 'PL' to the list of supported languages.
- Cleaned up redundant code and improved session management during user login and registration processes.
- Added a new API endpoint for fetching user permissions based on user ID.
2026-01-19 15:29:16 +01:00
“VeLiTi”
782050c3ca Add user role management functionality with CRUD operations and permissions handling
- Created user_role.php for viewing and editing user roles and their permissions.
- Implemented inline editing for role details and permissions.
- Added user_role_manage.php for creating and managing user roles.
- Introduced user_roles.php for listing all user roles with pagination and filtering options.
- Integrated API calls for fetching and updating role data and permissions.
- Enhanced user interface with success messages and navigation controls.
2026-01-19 11:16:54 +01:00
“VeLiTi”
3db13b9ebf feat: Enhance software tool with country selection and tax calculation
- Added a helper function to generate country select options in software tool.
- Updated user info modal and payment modal to use country dropdowns instead of text inputs.
- Implemented tax calculation based on selected country in payment modal.
- Improved software options loading behavior in debug mode.
- Enhanced description formatting in payment modal.
- Added log modal for equipment updates with a link to view logs.
- Introduced a new countries settings file with tax rates for various countries.
- Minor adjustments to various PHP files for better handling of equipment and payment processes.
2026-01-16 16:01:31 +01:00
“VeLiTi”
7aebb762d3 Refactor API endpoints and update invoice generation
- Updated API calls in equipment.php, equipment_manage.php, and equipments_mass_update.php to use v2 endpoints.
- Changed payload decoding from decode_payload to json_decode for consistency.
- Enhanced invoice generation in factuur.php and webhook files to use a new email template and PDF structure.
- Added new email and PDF templates for invoices to improve formatting and readability.
- Improved marketing folder handling in marketing.php with better payload management.
- Updated CSS for marketing to enhance UI interactions.
- Added JavaScript checks for browser compatibility in softwaretool.php.
- Adjusted user permissions in settingsprofiles.php to reflect new features.
2026-01-14 13:31:22 +01:00
“VeLiTi”
a0e1d386ad Finetuning software updates, general UI improvements 2026-01-13 14:35:16 +01:00
“VeLiTi”
0d3724395a feat: Enhance print functionality and add success modal for mass updates 2026-01-13 09:55:31 +01:00
“VeLiTi”
884d2a3366 Enhance product links and translations; update styles and add registration modal
- Updated product links in rma.php and rma_manage.php to include icons for better UX.
- Improved German, Spanish, Dutch, Polish, Portuguese, and US translations with new phrases for software licenses and user information prompts.
- Refactored CSS to remove redundant styles and added new styles for a registration modal, enhancing the overall UI.
- Introduced JavaScript variables for user information prompts in softwaretool.php for better localization support.
2026-01-12 15:59:46 +01:00
“VeLiTi”
be6f73b19c feat: Add edit functionality for marketing files and update handling 2026-01-12 10:51:55 +01:00
“VeLiTi”
2520fb2b75 Add PayPal webhook handler and marketing styles
- Implemented PayPal webhook for handling payment notifications, including signature verification and transaction updates.
- Created invoice generation and license management for software upgrades upon successful payment.
- Added comprehensive logging for debugging purposes.
- Introduced new CSS styles for the marketing file management system, including layout, toolbar, breadcrumb navigation, search filters, and file management UI components.
2026-01-09 15:19:28 +01:00
“VeLiTi”
08263c7933 feat: Implement invoice generation and emailing functionality
- Added invoice generation logic using DomPDF.
- Integrated invoice data retrieval from the API.
- Implemented language determination for invoices based on customer data.
- Added options to email invoices to customers and admin.
- Included HTML output option for direct viewing in the browser.
- Ensured proper redirection and error handling throughout the process.
2026-01-07 14:36:48 +01:00
“VeLiTi”
543f0b3cac feat: Add software licenses management page and update payment handling
- Introduced a new licenses management page with functionality to create, update, and view software licenses.
- Updated payment return handling in softwaretool.php to check payment status from the database and display appropriate modals for success, pending, and failure states.
- Enhanced webhook_mollie.php to log webhook calls, handle payment status updates directly in the database, and generate invoices based on payment status.
- Improved CSS styles for better alignment of buttons and modal components.
- Added JavaScript for modal interactions and bulk license creation functionality.
2025-12-24 14:07:28 +01:00
“VeLiTi”
0f968aac14 Add Mollie API integration and webhook for software upgrade payments
- Introduced the `CaBundle.php` class for managing CA certificates.
- Updated `installed.json` and `installed.php` to include the new `composer/ca-bundle` dependency.
- Added `platform_check.php` to enforce PHP version requirements.
- Created `initialize.php` for initializing the Mollie API client with the API key.
- Implemented `webhook_mollie.php` to handle webhook callbacks for software upgrade payments, including transaction status updates and invoice generation.
- Integrated DomPDF for generating invoices and sending them via email.
2025-12-21 14:44:37 +01:00
“VeLiTi”
653e33d7e9 Add software tool functionality with device connection and upgrade options
- Implemented the software tool page with user interface for connecting devices.
- Added functionality to display connection status and software upgrade options.
- Included a help modal with step-by-step instructions for users.
- Integrated error handling and user permission checks.
- Enhanced user experience with dynamic content updates and visual feedback.
2025-12-21 14:16:55 +01:00
“VeLiTi”
e57e0edbc4 Refactor profile definitions and views for improved organization and consistency 2025-12-16 16:20:28 +01:00
“VeLiTi”
3693b52886 Refactor software version update logic into a reusable function; enhance UI for file uploads and table responsiveness 2025-12-16 16:18:24 +01:00
“VeLiTi”
a9f623cf22 Add software availability check API and enhance profile management features 2025-12-16 14:53:20 +01:00
“VeLiTi”
a329cec1a6 Refactor code structure for improved readability and maintainability; removed redundant code blocks and optimized function calls. 2025-12-16 13:04:50 +01:00
“VeLiTi”
fc13fec9c9 Adjust main padding-top for improved layout consistency 2025-12-16 11:43:31 +01:00
“VeLiTi”
364ee773e4 Enhance UI and functionality across multiple pages
- Added filter panels and search functionality to media, orders, partners, pricelists, products, products attributes, software versions, translations, and users pages.
- Implemented security checks for create, update, and delete permissions on various pages.
- Updated CSS styles for improved layout and responsiveness, including new styles for filter panels and buttons.
- Refactored existing forms to utilize the new filter panel design for a more consistent user experience.
- Adjusted API versioning in servicereport and servicereports pages for better compatibility.
- Improved button icons for filter actions and form submissions for better user interaction.
2025-12-16 11:39:14 +01:00
“VeLiTi”
ec20d44267 Refactor UI elements for consistency and clarity
- Updated action buttons across multiple files to use icons (e.g., "Save" to "💾+", "Delete" to "X").
- Replaced "Cancel" button text with a left arrow (←) for a more intuitive navigation experience.
- Removed unnecessary action columns from tables to streamline the interface.
- Enhanced table rows to be clickable for better user interaction, redirecting to relevant management pages.
- Adjusted font sizes and styles in CSS for improved readability and aesthetics.
- Standardized back button functionality to use a left arrow across various pages.
2025-12-15 17:08:44 +01:00
“VeLiTi”
bdb460c046 Add API endpoints and management pages for software versions and upgrade paths
- Implemented API endpoint for managing software versions in `products_software_versions.php`.
- Created management page for software version assignments in `products_software_assignments.php`.
- Developed upgrade paths management functionality in `products_software_upgrade_paths_manage.php`.
- Enhanced software version details page in `products_software_version.php`.
- Added form handling and validation for software version creation and updates in `products_software_version_manage.php`.
- Introduced pagination and filtering for software versions in `products_software_versions.php`.
- Implemented success message handling for CRUD operations across various pages.
2025-12-15 14:52:50 +01:00
“VeLiTi”
2b42013e23 Removed initial software_upgrade 2025-12-12 10:54:45 +01:00
“VeLiTi”
c39a5ca648 Refactor software version queries to use 'rowID' instead of 'id' for consistency across the application 2025-12-11 15:45:14 +01:00
“VeLiTi”
9673d9be7b Implement Software Upgrade Management API and Frontend Functionality
- Added software.php for managing software versions, including download and purchase actions.
- Created upgrade_paths.php for handling upgrade paths management.
- Developed user_licenses.php for managing user licenses.
- Introduced version_access_rules.php for managing access rules for software versions.
- Implemented frontend functions in functions.js for interacting with the software upgrade API.
- Added version_access.php for user access validation and license management.
- Created upgrades.php for displaying available upgrades and handling user interactions.
- Enhanced UI with responsive design and progress indicators for downloads and purchases.
2025-12-11 15:32:18 +01:00
“VeLiTi”
e732c91362 Implement catalog to meta feed transformation with variant extraction and output functions 2025-12-10 14:03:16 +01:00
“VeLiTi”
04b9814c07 Enhance logging functionality across multiple scripts, enabling debug mode checks and detailed communication logs for serial connections and firmware updates. 2025-11-14 16:38:05 +01:00
“VeLiTi”
bd27bab30f Enhance logging functionality in API and UI components
- Implemented detailed logging for USB serial communication in readdevice.js.
- Added log file management features in logfile.php, including deletion and selection of log files.
- Created a new communication log API endpoint in com_log.php to store USB communication data.
- Improved user interface for log file selection and added confirmation for log deletion.
2025-11-14 14:04:46 +01:00
“VeLiTi”
3c99272f5f Marketing and PL translation 2025-10-16 09:46:56 +02:00
“VeLiTi”
f8e089ffcd Update for BeWellWell my account en media_upload 2025-08-29 15:01:30 +02:00
“VeLiTi”
010b23b0e5 Hardening 2025-08-20 19:24:03 +02:00
“VeLiTi”
41200633cb CMXX - mailer 2025-05-12 14:50:27 +02:00
“VeLiTi”
929fb89e3d CMXX - repair commit 2025-05-09 14:51:41 +02:00
“VeLiTi”
c20d2d9c6e CMXX - Mailer update 2025-05-09 14:18:06 +02:00
“VeLiTi”
da78217dd9 CMXX - dealers 2025-05-08 13:42:19 +02:00
“VeLiTi”
c3e5873912 CMXX - Dealers 2025-04-13 17:16:12 +02:00
“VeLiTi”
cb18443af9 CMXX - Dealers 2025-04-07 20:25:37 +02:00
“VeLiTi”
6f938302ff CMXX - Update manage history 2025-04-06 13:41:18 +02:00
“VeLiTi”
6bea6ef975 CMXX - Custom mail 2025-03-31 16:33:35 +02:00
“VeLiTi”
6f35e75198 CMXX - Custom folder profile and settings update 2025-03-31 16:10:52 +02:00
“VeLiTi”
2245297a7d CMXX - Custom folder 2025-03-31 15:48:42 +02:00
“VeLiTi”
8e0a21f80b CMXX - equipment_manage products bugfix 2025-03-31 11:56:24 +02:00
“VeLiTi”
469cd01108 CMXX - Track HW + SW updates by users 2025-03-31 11:01:06 +02:00
“VeLiTi”
f716511a5d CMXX - Bugfix equipments 2025-03-31 10:52:15 +02:00
“VeLiTi”
94cb6fadf4 CMXX - Update soveliti login/reset 2025-03-27 14:48:07 +01:00
“VeLiTi”
0432d7fa47 cmxx - Improved login 2025-03-27 13:55:02 +01:00
“VeLiTi”
6fd22ede84 CMXX - Translations, Service report improvements and API security 2025-03-25 15:41:53 +01:00
“VeLiTi”
12abe8cb8a CMXX - Bugfix partnerID 2025-03-21 13:59:39 +01:00
“VeLiTi”
dda27fd577 CMXX - Improved software_update 2025-03-18 11:00:08 +01:00
“VeLiTi”
7d61f2d9cc CMXX - Multisite styling reset 2025-03-14 09:57:03 +01:00
“VeLiTi”
42ab835bf4 CMXX - Multisite style 2025-03-13 15:10:02 +01:00
“VeLiTi”
7ccc4a5e7a CMXX - Multisite style 2025-03-13 15:10:00 +01:00
“VeLiTi”
578f7c1ce2 CMXX - Multisite style soveliti 2025-03-13 12:43:34 +01:00
“VeLiTi”
5557f6d270 CMXX - Mutlisite update 2025-03-13 12:41:11 +01:00
“VeLiTi”
75d9aa722a CMXX - Multisite settings 2025-03-13 12:32:57 +01:00
“VeLiTi”
116cdcd745 CMXX - Multisite config 2025-03-13 12:25:59 +01:00
“VeLiTi”
0d6f75704b CMXX - Multisite setup 2025-03-13 12:07:18 +01:00
“VeLiTi”
0b78fa4827 CM93 - mass update mandatory items 2025-03-12 16:03:57 +01:00
“VeLiTi”
a8563dc28d CM94 - Build popup after 25min idle 2025-03-12 15:32:46 +01:00
“VeLiTi”
b812647b60 CM97 - Add billing_plan 2025-03-12 15:23:03 +01:00
“VeLiTi”
ecc045f98a CMXX - Firmware update improvements 2025-03-12 12:40:35 +01:00
“VeLiTi”
faf5a5156b CMXX - First candidate 2025-03-05 20:45:35 +01:00
“VeLiTi”
3a52632d61 CMXX - Product query updates 2025-02-25 11:10:00 +01:00
“VeLiTi”
bc7e83efe9 CMXX - Changed consumer_identity to identity 2025-02-23 15:25:06 +01:00
“VeLiTi”
3182cb0b3c CMXX - Consumer identity 2025-02-22 23:45:27 +01:00
“VeLiTi”
8dd7023310 CMXX - Update whereclause get/post 2025-02-21 17:48:51 +01:00
“VeLiTi”
d5826fccdb CMXX - Uploader tool 2025-02-21 17:10:15 +01:00
“VeLiTi”
9e7cbc3115 CMXX - Improved menu handling 2025-02-20 17:26:38 +01:00
“VeLiTi”
92b47c3da3 CMXX - Updated salesid for admin 2025-02-20 13:59:28 +01:00
“VeLiTi”
4c6ed0d203 CMXX - Improved whereclause 2025-02-20 13:35:59 +01:00
“VeLiTi”
3aaa6c6680 CMXX - Checkout and Placeorder 2025-02-17 19:01:04 +01:00
“VeLiTi”
2072250072 CMXX - Products_media 2025-02-06 18:46:33 +01:00
“VeLiTi”
07b5578895 CMXX - Shopping_cart + local fonts 2025-02-06 11:47:53 +01:00
“VeLiTi”
0172f8405a CMXX - Added categories filter for commerce 2025-02-04 11:46:14 +01:00
“VeLiTi”
59c23bf46c CMXX - Categories and filters 2025-02-03 11:28:05 +01:00
“VeLiTi”
754359f6b6 CMXX - Categories and catalog enhancements 2025-01-31 17:03:31 +01:00
“VeLiTi”
a669b2fadf CMXX - Catalog API 2025-01-30 09:28:50 +01:00
“VeLiTi”
661783270a CMXX - Pricelists 2025-01-23 12:54:16 +01:00
“VeLiTi”
53686b3c33 CMXX - Pricelists view 2025-01-16 19:48:49 +01:00
“VeLiTi”
d76c9ad9fd CMXX - Pricelists 2025-01-16 19:47:08 +01:00
“VeLiTi”
2dc2100269 CMXX - Media 2025-01-16 17:13:42 +01:00
“VeLiTi”
05b0c2bdb1 CMXX - Product attributes and initial multi languagal product support 2025-01-14 14:40:01 +01:00
“VeLiTi”
906ce7b843 CMXX - Initial product attributes 2025-01-09 15:40:59 +01:00
“VeLiTi”
e3d2b4e768 CMXX - Translations - updates 2025-01-09 14:45:23 +01:00
“VeLiTi”
30b60c8652 CMXX - Initial translation engine 2025-01-08 13:20:09 +01:00
612 changed files with 98614 additions and 10552 deletions

BIN
.DS_Store vendored

Binary file not shown.

20
.gitignore vendored
View File

@@ -1,11 +1,9 @@
dev.php
test.php
migration.php
log_21.txt
log_22.txt
marketing/
firmware/
log/
assets/images/products/
settings/config.php
settings/settings.php
.htaccess
migration.sql
.DS_Store
api/.DS_Store
api/v1/.DS_Store
api/v2/.DS_Store
api/.DS_Store
assets/.DS_Store
assets/images/.DS_Store

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"php.version": "8.4"
}

188
access_element.php Normal file
View File

@@ -0,0 +1,188 @@
<?php
defined(page_security_key) or exit;
if (debug && debug_id == $_SESSION['authorization']['id']){
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
}
include_once './assets/functions.php';
include_once './settings/settings_redirector.php';
//SET ORIGIN FOR NAVIGATION
$_SESSION['prev_origin_access_element'] = $_SERVER['REQUEST_URI'];
$page = 'access_element';
//Check if allowed
if (isAllowed($page,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 0){
header('location: index.php');
exit;
}
//PAGE Security
$page_manage = 'access_element_manage';
$update_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$update_allowed_edit = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$delete_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'D');
$create_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'C');
//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
//CALL TO API FOR General information
$api_url = '/v2/access_elements/'.$GET_VALUES;
$responses = ioServer($api_url,'');
//Decode Payload
if (!empty($responses)){$responses = json_decode($responses);}else{$responses = null;}
$responses = $responses[0];
$element_id = $responses->rowID;
//CALL TO API FOR Roles using this access element
$api_url = '/v2/role_access_permissions/access_id='.$element_id;
$role_permissions = ioServer($api_url,'');
//Decode Payload
if (!empty($role_permissions)){$role_permissions = json_decode($role_permissions);}else{$role_permissions = null;}
//------------------------------
//Variables
//------------------------------
$status_text = ($responses->is_active == 1) ? ($enabled ?? 'Active') : ($disabled ?? 'Inactive');
$status_class = ($responses->is_active == 1) ? 'id1' : 'id0';
// Handle success messages
if (isset($_GET['success_msg'])) {
if ($_GET['success_msg'] == 1) {
$success_msg = ($message_access_1 ?? 'Access element created successfully');
}
if ($_GET['success_msg'] == 2) {
$success_msg = ($message_access_2 ?? 'Access element updated successfully');
}
if ($_GET['success_msg'] == 3) {
$success_msg = ($message_access_3 ?? 'Access element deleted successfully');
}
}
template_header(($access_element_title ?? 'Access Element'), 'access_element', 'view');
$view = '
<div class="content-title responsive-flex-wrap responsive-pad-bot-3">
<h2 class="responsive-width-100">'.($view_access_h2 ?? 'Access Element').' - '.$responses->access_name.'</h2>
<a href="index.php?page='.$_SESSION['origin'].'&p='.$_SESSION['p'].$_SESSION['status'].$_SESSION['sort'].$_SESSION['search'].'" class="btn alt mar-right-2">←</a>
';
if ($update_allowed_edit === 1){
$view .= '<a href="index.php?page=access_element_manage&rowID='.$responses->rowID.'" class="btn">✏️</a>';
}
$view .= '</div>';
if (isset($success_msg)){
$view .= ' <div class="msg success">
<i class="fas fa-check-circle"></i>
<p>'.$success_msg.'</p>
<i class="fas fa-times"></i>
</div>';
}
$view .= '<div class="content-block-wrapper">';
// Access Element Information Block
$view .= ' <div class="content-block order-details">
<div class="block-header">
<i class="fa-solid fa-circle-info"></i>'.($view_access_information ?? 'Access Element Information').'
</div>
<div class="order-detail">
<h3>'.($general_status ?? 'Status').'</h3>
<p><span class="status '.$status_class.'">'.$status_text.'</span></p>
</div>
<div class="order-detail">
<h3>'.($access_element_name ?? 'Name').'</h3>
<p>'.$responses->access_name.'</p>
</div>
<div class="order-detail">
<h3>'.($access_element_path ?? 'Path').'</h3>
<p>'.$responses->access_path.'</p>
</div>
<div class="order-detail">
<h3>'.($access_element_group ?? 'Group').'</h3>
<p>'.($responses->access_group ?? '-').'</p>
</div>
<div class="order-detail">
<h3>'.($role_description ?? 'Description').'</h3>
<p>'.($responses->description ?? '-').'</p>
</div>
</div>
';
$view .= '</div>'; // Close content-block-wrapper
// Roles Using This Access Element
$view .= '<div class="content-block">
<div class="block-header">
<i class="fa-solid fa-user-shield fa-sm"></i>'.($view_access_roles ?? 'Roles Using This Element').'
</div>
<div class="table">
<table>
<thead>
<tr>
<th>'.($role_name ?? 'Role Name').'</th>
<th>'.($permission_create ?? 'C').'</th>
<th>'.($permission_read ?? 'R').'</th>
<th>'.($permission_update ?? 'U').'</th>
<th>'.($permission_delete ?? 'D').'</th>
</tr>
</thead>
<tbody>';
if (!empty($role_permissions)){
foreach ($role_permissions as $role_perm){
$can_create = ($role_perm->can_create == 1) ? '<i class="fa-solid fa-check" style="color:green;"></i>' : '<i class="fa-solid fa-times" style="color:red;"></i>';
$can_read = ($role_perm->can_read == 1) ? '<i class="fa-solid fa-check" style="color:green;"></i>' : '<i class="fa-solid fa-times" style="color:red;"></i>';
$can_update = ($role_perm->can_update == 1) ? '<i class="fa-solid fa-check" style="color:green;"></i>' : '<i class="fa-solid fa-times" style="color:red;"></i>';
$can_delete = ($role_perm->can_delete == 1) ? '<i class="fa-solid fa-check" style="color:green;"></i>' : '<i class="fa-solid fa-times" style="color:red;"></i>';
$view .= '<tr onclick="window.location.href=\'index.php?page=user_role&rowID='.$role_perm->role_id.'\'" style="cursor: pointer;">
<td>'.$role_perm->role_name.'</td>
<td>'.$can_create.'</td>
<td>'.$can_read.'</td>
<td>'.$can_update.'</td>
<td>'.$can_delete.'</td>
</tr>';
}
} else {
$view .= '<tr>
<td colspan="5" style="text-align:center;">'.($no_roles_using ?? 'No roles are using this access element').'</td>
</tr>';
}
$view .= ' </tbody>
</table>
</div>
</div>
';
// Metadata Block
$view .= '<div class="content-block">
<div class="block-header">
<i class="fa-solid fa-bars fa-sm"></i>'.($tab3 ?? 'Details').'
</div>
<div class="table order-table">
<table>
<tr>
<td style="width:25%;">'.($general_created ?? 'Created').'</td>
<td>'.getRelativeTime($responses->created).'</td>
</tr>
<tr>
<td style="width:25%;">'.($general_updated ?? 'Updated').'</td>
<td>'.getRelativeTime($responses->updated).'</td>
</tr>
</table>
</div>
</div>
';
//OUTPUT
echo $view;
template_footer()
?>

168
access_element_manage.php Normal file
View File

@@ -0,0 +1,168 @@
<?php
defined(page_security_key) or exit;
if (debug && debug_id == $_SESSION['authorization']['id']){
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
}
include_once './assets/functions.php';
include_once './settings/settings_redirector.php';
$page = 'access_element_manage';
//Check if allowed
if (isAllowed($page,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 0){
header('location: index.php');
exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'C');
// Default input values
$element = [
'rowID' => '',
'access_name' => '',
'access_path' => '',
'access_group' => '',
'description' => '',
'is_active' => 1,
'created' => '',
'createdby' => $_SESSION['authorization']['clientID'],
'updated' => '',
'updatedby' => ''
];
$element_ID = $_GET['rowID'] ?? '';
if ($element_ID !=''){
$url = 'index.php?page=access_element&rowID='.$element_ID.'';
} else {
$url = 'index.php?page=access_elements';
}
if (isset($_GET['rowID'])) {
// ID param exists, edit an existing element
//CALL TO API
$api_url = '/v2/access_elements/rowID='.$element_ID;
$responses = ioServer($api_url,'');
//Decode Payload
if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = null;}
$element = $responses[0];
if ($update_allowed === 1){
if (isset($_POST['submit'])) {
//GET ALL POST DATA
$data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
//API call
$responses = ioServer('/v2/access_elements', $data);
if ($responses === 'NOK'){
} else {
header('Location: index.php?page=access_element&rowID='.$element_ID.'&success_msg=2');
exit;
}
}
}
if ($delete_allowed === 1){
if (isset($_POST['delete'])) {
//GET ALL POST DATA
$data = json_encode($_POST , JSON_UNESCAPED_UNICODE);
//API call
$responses = ioServer('/v2/access_elements', $data);
// Redirect and delete element
if ($responses === 'NOK'){
} else {
header('Location: index.php?page=access_elements&success_msg=3');
exit;
}
}
}
} else {
// Create a new element
if (isset($_POST['submit']) && $create_allowed === 1) {
//GET ALL POST DATA
$data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
//API call
$responses = ioServer('/v2/access_elements', $data);
if ($responses === 'NOK'){
} else {
header('Location: index.php?page=access_elements&success_msg=1');
exit;
}
}
}
template_header(($access_element_title ?? 'Access Element'), 'access_element', 'manage');
$label_h2 = (($element_ID !='')? ($manage_access_h2 ?? 'Edit Access Element') : ($button_create_access ?? 'Create Access Element'));
$view ='
<form action="" method="post">
<div class="content-title responsive-flex-wrap responsive-pad-bot-3">
<h2 class="responsive-width-100">'.$label_h2.'</h2>
<a href="'.$url.'" class="btn alt mar-right-2">←</a>
';
if ($delete_allowed === 1 && $element_ID != ''){
$view .= '<input type="submit" name="delete" value="X" class="btn red mar-right-2" onclick="return confirm(\''.($confirm_delete_access ?? 'Are you sure you want to delete this access element?').'\')">';
}
if ($update_allowed === 1 || ($create_allowed === 1 && $element_ID == '')){
$view .= '<input type="submit" name="submit" value="💾" class="btn">';
}
$view .= '</div>';
$view .= '<div class="tabs">
<a href="#" class="active">'.($tab1 ?? 'General').'</a>
</div>
<div class="content-block tab-content active">
<div class="form responsive-width-100">
<label for="is_active">'.($general_status ?? 'Status').'</label>
<select id="is_active" name="is_active">
<option value="1" '.($element['is_active']==1?' selected':'').'>'.($enabled ?? 'Active').'</option>
<option value="0" '.($element['is_active']==0?' selected':'').'>'.($disabled ?? 'Inactive').'</option>
</select>
<label for="access_name">'.($access_element_name ?? 'Name').' <i class="required">*</i></label>
<input id="access_name" type="text" name="access_name" placeholder="'.($access_element_name ?? 'Name').'" value="'.$element['access_name'].'" required>
<label for="access_path">'.($access_element_path ?? 'Path').' <i class="required">*</i></label>
<input id="access_path" type="text" name="access_path" placeholder="'.($access_element_path_placeholder ?? 'e.g., equipments, equipment_manage').'" value="'.$element['access_path'].'" required>
<label for="access_group">'.($access_element_group ?? 'Group').'</label>
<input id="access_group" type="text" name="access_group" placeholder="'.($access_element_group_placeholder ?? 'e.g., Views, API, Admin').'" value="'.($element['access_group'] ?? '').'">
<label for="description">'.($role_description ?? 'Description').'</label>
<textarea id="description" name="description" placeholder="'.($role_description ?? 'Description').'" style="height: 100px;">'.$element['description'].'</textarea>
<input type="hidden" name="rowID" value="'.$element_ID.'">
</div>
</div>';
//DISPLAY TAB 2 - Metadata
if ($element_ID != ''){
$view .= '<div class="tabs">
<a href="#">'.($tab3 ?? 'Details').'</a>
</div>
<div class="content-block tab-content">
<div class="form responsive-width-100">
<label for="created">'.($general_created ?? 'Created').'</label>
<input id="created" type="text" name="" placeholder="'.($general_created ?? 'Created').'" value="'.$element['created'].'" readonly>
<label for="createdby">'.($general_createdby ?? 'Created By').'</label>
<input id="createdby" type="text" name="" placeholder="'.($general_createdby ?? 'Created By').'" value="'.$element['createdby'].'" readonly>
<label for="updated">'.($general_updated ?? 'Updated').'</label>
<input id="updated" type="text" name="" placeholder="'.($general_updated ?? 'Updated').'" value="'.$element['updated'].'" readonly>
<label for="updatedby">'.($general_updatedby ?? 'Updated By').'</label>
<input id="updatedby" type="text" name="" placeholder="'.($general_updatedby ?? 'Updated By').'" value="'.$element['updatedby'].'" readonly>
</div>
</div>';
}
$view .= '</form>';
//Output
echo $view;
template_footer()?>

317
access_elements.php Normal file
View File

@@ -0,0 +1,317 @@
<?php
defined(page_security_key) or exit;
if (debug && debug_id == $_SESSION['authorization']['id']){
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
}
include_once './assets/functions.php';
include_once './settings/settings_redirector.php';
//SET PAGE ORIGIN FOR NAVIGATION AND SECURITY
$prev_page = $_SESSION['prev_origin'] ?? '';
$page = $_SESSION['origin'] = 'access_elements';
//create backbutton to prev_origin
$back_btn_orgin = ($prev_page != '')? '<a href="'.$prev_page.'" class="btn alt mar-right-2">←</a>':'';
//Check if allowed
if (isAllowed($page,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 0){
header('location: index.php');
exit;
}
//PAGE Security
$page_manage = 'access_element_manage';
$update_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$delete_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'D');
$create_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'C');
// Function to scan project for new PHP files and add to access_elements
function scan_and_update_access_elements() {
$new_elements = [];
$base_path = dirname(__FILE__);
// Scan root PHP files (excluding index, login, logout)
$root_files = glob($base_path . '/*.php');
foreach ($root_files as $file) {
$filename = basename($file, '.php');
if (!in_array($filename, ['index', 'login', 'logout'])) {
// Only add if not already in array (first occurrence wins)
if (!isset($new_elements[$filename])) {
$new_elements[$filename] = [
'name' => ucwords(str_replace('_', ' ', $filename)),
'path' => $filename,
'group' => 'Views',
'description' => 'Auto-scanned: ' . $filename
];
}
}
}
// Scan API v2 get folder - only add if not already found in root
$get_files = glob($base_path . '/api/v2/get/*.php');
foreach ($get_files as $file) {
$filename = basename($file, '.php');
if (!isset($new_elements[$filename])) {
$new_elements[$filename] = [
'name' => ucwords(str_replace('_', ' ', $filename)),
'path' => $filename,
'group' => 'API',
'description' => 'Auto-scanned: ' . $filename
];
}
}
// Scan API v2 post folder - only add if not already found
$post_files = glob($base_path . '/api/v2/post/*.php');
foreach ($post_files as $file) {
$filename = basename($file, '.php');
if (!isset($new_elements[$filename])) {
$new_elements[$filename] = [
'name' => ucwords(str_replace('_', ' ', $filename)),
'path' => $filename,
'group' => 'API',
'description' => 'Auto-scanned: ' . $filename
];
}
}
// Get existing access elements from API
$api_url = '/v2/access_elements/';
$existing = ioServer($api_url, '');
$existing_paths = [];
if (!empty($existing)) {
$existing_data = json_decode($existing);
foreach ($existing_data as $element) {
$existing_paths[] = $element->access_path;
}
}
// Filter out elements that already exist
$elements_to_add = [];
foreach ($new_elements as $path => $element) {
if (!in_array($path, $existing_paths)) {
$elements_to_add[] = $element;
}
}
// Add new elements via API
$added_count = 0;
foreach ($elements_to_add as $element) {
$data = json_encode([
'access_name' => $element['name'],
'access_path' => $element['path'],
'access_group' => $element['group'],
'description' => $element['description'],
'is_active' => 1
], JSON_UNESCAPED_UNICODE);
$response = ioServer('/v2/access_elements', $data);
if ($response !== 'NOK') {
$added_count++;
}
}
return $added_count;
}
// Handle scan request
if (isset($_POST['scan_elements']) && $create_allowed === 1) {
$added_count = scan_and_update_access_elements();
header('Location: index.php?page=access_elements&elements_added=' . $added_count);
exit;
}
//GET PARAMETERS && STORE in SESSION for FURTHER USE/NAVIGATION
$pagination_page = $_SESSION['p'] = isset($_GET['p']) ? $_GET['p'] : 1;
$status = $_SESSION['status'] = isset($_GET['status']) ? '&status='.$_GET['status'] : '';
$sort = $_SESSION['sort'] = isset($_GET['sort']) ? '&sort='.$_GET['sort'] : '';
$search = $_SESSION['search'] = isset($_GET['search']) ? '&search='.$_GET['search'] : '';
//GET PARAMETERS FOR FILTERS
$filter = urlGETdetailsFilter($_GET) ?? '';
// Determine the URL
$url = 'index.php?page=access_elements'.$status.$search.$sort;
//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
//CALL TO API
$api_url = '/v2/access_elements/'.$GET_VALUES;
$responses = ioServer($api_url,'');
//Decode Payload
if (!empty($responses)){$responses = json_decode($responses);}else{$responses = null;}
//Return QueryTotal from API
$total_url = ((!empty($GET_VALUES) && $GET_VALUES !='') ? '&totals=' : 'totals=' );
$api_url = '/v2/access_elements/'.$GET_VALUES.$total_url;
$query_total = ioServer($api_url,'');
//Decode Payload
if (!empty($query_total)){$query_total = json_decode($query_total);}else{$query_total = null;}
// Handle success messages
if (isset($_GET['success_msg'])) {
if ($_GET['success_msg'] == 1) {
$success_msg = ($message_access_1 ?? 'Access element created successfully');
}
if ($_GET['success_msg'] == 2) {
$success_msg = ($message_access_2 ?? 'Access element updated successfully');
}
if ($_GET['success_msg'] == 3) {
$success_msg = ($message_access_3 ?? 'Access element deleted successfully');
}
}
// Handle elements added message from scan
if (isset($_GET['elements_added'])) {
$added_count = (int)$_GET['elements_added'];
if ($added_count > 0) {
$success_msg = $added_count . ' ' . ($message_elements_added ?? 'new access elements added');
} else {
$success_msg = ($message_no_new_elements ?? 'No new elements found. All elements are up to date.');
}
}
template_header(($access_elements_title ?? 'Access Elements'), 'access_elements','view');
$view = '
<div class="content-title">
<div class="title">
<i class="fa-solid fa-lock"></i>
<div class="txt">
<h2>'.($access_elements_h2 ?? 'Access Elements').' ('.$query_total.')</h2>
<p>'.($access_elements_p ?? 'Manage system access elements and paths').'</p>
</div>
</div>
<div class="title-actions">
'.$back_btn_orgin;
// Scan button - only show if user has create permission
if ($create_allowed === 1){
$view .= '
<form action="" method="post" style="display:inline;">
<button type="submit" name="scan_elements" class="btn alt" title="'.($scan_elements_title ?? 'Scan for new files').'">
<i class="fa-solid fa-sync-alt"></i>
</button>
</form>';
$view .= '<a href="index.php?page=access_element_manage" class="btn">+</a>';
}
$view .= '<button id="filter-toggle" class="btn alt" onclick="toggleFilters()">
<i class="fa-solid fa-search"></i>
</button>
</div>
</div>';
if (isset($success_msg)){
$view .= ' <div class="msg success">
<i class="fas fa-check-circle"></i>
<p>'.$success_msg.'</p>
<i class="fas fa-times"></i>
</div>';
}
$view .= '
<div id="filter-panel" class="filter-panel" style="display: none;">
<div class="filter-content">
<form action="" method="get">
'.$filter.'
<div class="filter-row">
<div class="filter-group">
<select name="status">
<option value="" disabled selected>'.($general_status ?? 'Status').'</option>
<option value="1"'.(isset($_GET['status']) && $_GET['status']==1?' selected':'').'>'.($enabled ?? 'Active').'</option>
<option value="0"'.(isset($_GET['status']) && $_GET['status']==0?' selected':'').'>'.($disabled ?? 'Inactive').'</option>
</select>
</div>
<div class="filter-group">
<select name="sort">
<option value="" disabled selected>'.($general_sort ?? 'Sort').'</option>
<option value="1"'.(isset($_GET['sort']) && $_GET['sort']==1?' selected':'').'>'.($access_element_name ?? 'Name').' '.($general_sort_type_1 ?? 'ASC').'</option>
<option value="2"'.(isset($_GET['sort']) && $_GET['sort']==2?' selected':'').'>'.($access_element_name ?? 'Name').' '.($general_sort_type_2 ?? 'DESC').'</option>
<option value="3"'.(isset($_GET['sort']) && $_GET['sort']==3?' selected':'').'>'.($access_element_path ?? 'Path').' '.($general_sort_type_1 ?? 'ASC').'</option>
<option value="4"'.(isset($_GET['sort']) && $_GET['sort']==4?' selected':'').'>'.($access_element_path ?? 'Path').' '.($general_sort_type_2 ?? 'DESC').'</option>
</select>
</div>
<div class="filter-group search-group">
<input type="text" name="search" placeholder="'.($access_search ?? 'Search access elements...').'" value="">
</div>
</div>
<div class="filter-actions">
<button type="submit" class="btn"><i class="fas fa-level-down-alt fa-rotate-90"></i></button>
<a class="btn alt" href="index.php?page=access_elements">X</a>
</div>
</form>
</div>
</div>
';
$view .= '
<div class="content-block">
<div class="table">
<table class="sortable">
<thead>
<tr>
<th>'.($access_element_name ?? 'Name').'</th>
<th>'.($access_element_path ?? 'Path').'</th>
<th>'.($access_element_group ?? 'Group').'</th>
<th class="responsive-hidden">'.($role_description ?? 'Description').'</th>
<th>'.($general_status ?? 'Status').'</th>
<th class="responsive-hidden">'.($general_created ?? 'Created').'</th>
</tr>
</thead>
<tbody>
';
if (empty($responses)){
$view .= '
<tr>
<td colspan="6" style="text-align:center;">'.($message_no_access_elements ?? 'No access elements found').'</td>
</tr>';
}
foreach ($responses as $response){
//Translate status INT to STR
$status_text = ($response->is_active == 1) ? ($enabled ?? 'Active') : ($disabled ?? 'Inactive');
$status_class = ($response->is_active == 1) ? 'id1' : 'id0';
$view .= '<tr onclick="window.location.href=\'index.php?page=access_element&rowID='.$response->rowID.'\'" style="cursor: pointer;">
<td>'.$response->access_name.'</td>
<td>'.$response->access_path.'</td>
<td>'.($response->access_group ?? '-').'</td>
<td class="responsive-hidden">'.($response->description ?? '-').'</td>
<td><span class="status '.$status_class.'">'.$status_text.'</span></td>
<td class="responsive-hidden">'.getRelativeTime($response->created).'</td>
</tr>
';
}
$view .= '
</tbody>
</table>
</div>
</div>
';
$page_rows = $page_rows_equipment ?? 20;
$view.='<div class="pagination">';
if ($pagination_page > 1) {
$page = $pagination_page-1;
$view .= '<a href="'.$url.'&p=1">'.($general_first ?? 'First').'</a>';
$view .= '<a href="'.$url.'&p='.$page.'">'.($general_prev ?? 'Prev').'</a>';
}
$totals = ceil($query_total / $page_rows) == 0 ? 1 : ceil($query_total / $page_rows);
$view .= '<span> '.($general_page ?? 'Page ').$pagination_page.($general_page_of ?? ' of ').$totals.'</span>';
if ($pagination_page * $page_rows < $query_total){
$page = $pagination_page+1;
$view .= '<a href="'.$url.'&p='.$page.'">'.($general_next ?? 'Next').'</a>';
$view .= '<a href="'.$url.'&p='.$totals.'">'.($general_last ?? 'Last').'</a>';
}
$view .= '</div>';
//OUTPUT
echo $view;
template_footer();
?>

View File

@@ -1,29 +1,29 @@
<?php
defined(page_security_key) or exit;
if (debug && debug_id == $_SESSION['id']){
if (debug && debug_id == $_SESSION['authorization']['id']){
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
}
include_once './assets/functions.php';
include_once './settings/settings.php';
include_once './settings/settings_redirector.php';
//SET ORIGIN FOR NAVIGATION
$_SESSION['prev_origin'] = $_SERVER['REQUEST_URI'];
$page = $_SESSION['origin'] = 'account';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
if (isAllowed($page,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 0){
header('location: index.php');
exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');
$healthindex_allowed = isAllowed('report_healthindex' ,$_SESSION['profile'],$_SESSION['permission'],'R');
$update_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'C');
$healthindex_allowed = isAllowed('report_healthindex' ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R');
//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
@@ -56,10 +56,10 @@ template_header('Account', 'account', 'view');
$view = '
<div class="content-title responsive-flex-wrap responsive-pad-bot-3">
<h2 class="responsive-width-100">'.$account_h2.' - '.$_GET['rowID'].'</h2>
<a href="index.php?page=accounts" class="btn alt mar-right-2">'.$button_cancel.'</a>
<a href="index.php?page=accounts" class="btn alt mar-right-2"></a>
';
if ($update_allowed === 1){
$view .= '<a href="index.php?page=account_manage&rowID='.$_GET['rowID'].'" class="btn">Edit</a>';
$view .= '<a href="index.php?page=account_manage&rowID='.$_GET['rowID'].'" class="btn">✏️</a>';
}
$view .= '</div>';
@@ -239,13 +239,13 @@ $soldto_id = explode("-",$account_hierarchy->soldto) ?? '';
//DISPLAY RELATED COMMUNICATION RECORDS
$view_communication = '';
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
if (isAllowed('communications',$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 1){
$view_communication = ' <a href="index.php?page=communications&partnerid='.$soldto_id[0].'" class="btn">'.$button_partner_assigned_communication.'</a>';
}
//DISPLAY RELATED USERS
$view_users ='';
if ($_SESSION['permission'] == 3 || $_SESSION['permission'] == 4){
if (isAllowed('users',$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 1){
$view_users = ' <a href="index.php?page=users&partnerid='.$soldto_id[0].'" class="btn">'.$button_partner_assigned_users.'</a>';
}

View File

@@ -3,14 +3,14 @@ defined(page_security_key) or exit;
$page = 'account';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
if (isAllowed($page,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 0){
header('location: index.php');
exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');
$update_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'C');
// Default input product values
$account = [
@@ -43,7 +43,7 @@ $account = [
'loghandleraccount' => ''
],
'created' => $date,
'createdby' => $_SESSION['username'],
'createdby' => $_SESSION['authorization']['clientID'],
'accounthierarchy' => [
'salesid' => '',
'soldto' => ''
@@ -133,26 +133,21 @@ $view ='
<form action="" method="post">
<div class="content-title responsive-flex-wrap responsive-pad-bot-3">
<h2 class="responsive-width-100"><?=$page?>'.$account_h2.'</h2>
<a href="'.$url .'" class="btn alt mar-right-2">'.$button_cancel.'</a>
<a href="'.$url .'" class="btn alt mar-right-2"></a>
';
if ($delete_allowed === 1){
$view .= '<input type="submit" name="delete" value="Delete" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this account?\')">';
$view .= '<input type="submit" name="delete" value="X" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this account?\')">';
}
if ($update_allowed === 1){
$view .= '<input type="submit" name="submit" value="Save" class="btn">';
$view .= '<input type="submit" name="submit" value="💾" class="btn">';
}
$view .= '</div>';
$view .= '<div class="tabs">
<a href="#" class="active">'.$view_account_information.'</a>
<a href="#">'.$view_account_contact.'</a>
<a href="#">'.$account_billing.'</a>
<a href="#">'.$account_shipping.'</a>
<a href="#">'.$tab3.'</a>
</div>
';
</div>';
//Define Permission & Profile
$view .= '<div class="content-block tab-content active">
@@ -186,8 +181,10 @@ $view .= '<div class="content-block tab-content active">
</div>
</div>';
$view .= '<div class="content-block tab-content">
$view .= '<div class="tabs">
<a href="#">'.$view_account_contact.'</a>
</div>
<div class="content-block tab-content">
<div class="form responsive-width-100">
<label for="">'.$account_contactfirstname.'</label>
<input name="accountdetails[contactfirstname]" type="text" value="'.$accountdetails->contactfirstname.'">
@@ -206,8 +203,10 @@ $view .= '<div class="content-block tab-content">
</div>
</div>';
$view .= '<div class="content-block tab-content">
$view .= '<div class="tabs">
<a href="#">'.$account_billing.'</a>
</div>
<div class="content-block tab-content">
<div class="form responsive-width-100">
<label for="">'.$account_billstreetadress.'</label>
<input name="accountdetails[billstreetadress]" type="text" value="'.$accountdetails->billstreetadress.'">
@@ -231,7 +230,10 @@ $view .= '<div class="content-block tab-content">
</div>
</div>';
$view .= '<div class="content-block tab-content">
$view .= '<div class="tabs">
<a href="#">'.$account_shipping.'</a>
</div>
<div class="content-block tab-content">
<div class="form responsive-width-100">
<label for="">'.$account_streetadress.'</label>
<input name="accountdetails[streetadress]" type="text" value="'.$accountdetails->streetadress.'">
@@ -269,11 +271,13 @@ $view .= '<div class="content-block tab-content">
//Dropdown
$partner_data = json_decode($_SESSION['partnerhierarchy']);
$soldto_dropdown = listPartner('soldto',$_SESSION['permission'],$accounthierarchy->soldto);
$partner_data = json_decode($_SESSION['authorization']['partnerhierarchy']);
$soldto_dropdown = listPartner('soldto',$accounthierarchy->soldto,'',$_SESSION['authorization']['permission']);
$view .= '<div class="content-block tab-content">
$view .= '<div class="tabs">
<a href="#">'.$tab3.'</a>
</div>
<div class="content-block tab-content">
<div class="form responsive-width-100">
<label for="">'.$general_salesid.'</label>
<input name="salesid" type="text" value="'.$partner_data->salesid.'">

View File

@@ -1,23 +1,29 @@
<?php
defined(page_security_key) or exit;
if (debug && debug_id == $_SESSION['id']){
if (debug && debug_id == $_SESSION['authorization']['id']){
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
}
include_once './assets/functions.php';
include_once './settings/settings.php';
include_once './settings/settings_redirector.php';
//SET ORIGIN FOR NAVIGATION
$_SESSION['prev_origin'] = '';
$page = 'accounts';
//Check if allowed
if (isAllowed('accounts',$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
if (isAllowed($page,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'R') === 0){
header('location: index.php');
exit;
}
//PAGE Security
$page_manage = 'account_manage';
$update_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'U');
$delete_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'D');
$create_allowed = isAllowed($page_manage ,$_SESSION['authorization']['permissions'],$_SESSION['authorization']['permission'],'C');
//GET PARAMETERS
$pagination_page = isset($_GET['p']) ? $_GET['p'] : 1;
@@ -62,6 +68,16 @@ $view = '
<p>'.$account_p .'</p>
</div>
</div>
<div class="title-actions">';
if ($create_allowed === 1){
$view .= '<a href="index.php?page=account_manage" class="btn">+</a>';
}
$view .= '<button id="filter-toggle" class="btn alt" onclick="toggleFilters()">
<i class="fa-solid fa-search"></i>
</button>
</div>
</div>';
if (isset($success_msg)){
@@ -71,30 +87,33 @@ $view .= ' <div class="msg success">
<i class="fas fa-times"></i>
</div>';
}
$view .= '
<div class="content-header responsive-flex-column pad-top-5">
<a href="index.php?page=account_manage" class="btn">'.$button_create_account.'</a>
<form action="" method="get">
<input type="hidden" name="page" value="accounts">
<div class="filters">
<a href="#"><i class="fa-solid fa-filter"></i>'.$general_filters.'</a>
<div class="list">
<select name="status">
<option value="" disabled selected>'.$account_status.'</option>
<option value="0">'.$accountstatus_0.'</option>
<option value="1">'.$accountstatus_1.'</option>
<option value="2">'.$accountstatus_2.'</option>
</select>
<button type="submit">'.$button_apply.'</button>
<div id="filter-panel" class="filter-panel" style="display: none;">
<div class="filter-content">
<form action="" method="get">
<input type="hidden" name="page" value="accounts">
<div class="filter-row">
<div class="filter-group">
<select name="status">
<option value="" disabled selected>'.$account_status.'</option>
<option value="0">'.$accountstatus_0.'</option>
<option value="1">'.$accountstatus_1.'</option>
<option value="2">'.$accountstatus_2.'</option>
</select>
</div>
<div class="filter-group search-group">
<input type="text" name="search" placeholder="'.$account_search.'" value="">
</div>
</div>
</div>
<div class="search">
<label for="search">
<input id="search" type="text" name="search" placeholder="'.$account_search.'" value="" class="responsive-width-100">
<i class="fas fa-search"></i>
</label>
</div>
</form>
<div class="filter-actions">
<button type="submit" class="btn"><i class="fas fa-level-down-alt fa-rotate-90"></i></button>
<a class="btn alt" href="index.php?page=accounts">'.$general_filters_clear.'</a>
</div>
</form>
</div>
</div>
';
@@ -107,7 +126,6 @@ $view .= '
<th>'.$account_id.'</th>
<th>'.$account_status.'</th>
<th>'.$account_name.'</th>
<th>'.$general_actions.'</th>
</tr>
</thead>
<tbody>
@@ -125,11 +143,10 @@ $view .= '
$account_details = json_decode($response->accountdetails);
$view .= '
<tr>
<tr onclick="window.location.href=\'index.php?page=account&rowID='.$response->rowID.'\'" style="cursor: pointer;">
<td>'.$response->rowID.'</td>
<td>'.(($response->status == 'Customer')? '<span class="status enabled">'.$response->status:'<span class="status">'.$response->status).'</td>
<td>'.$account_details->billcompany.'</td>
<td><a href="index.php?page=account&rowID='.$response->rowID.'" class="btn_link">'.$general_view .'</a></td>
</tr>
';
}

95
api.php
View File

@@ -1,6 +1,7 @@
<?php
define('secure_34563$52', true);
//------------------------------------------
// Get DATA from API
//------------------------------------------
@@ -13,8 +14,72 @@ $input = stream_get_contents($post_data_curl);
// Include functions
//------------------------------------------
require_once './assets/functions.php';
include './settings/settings.php';
include './settings/config.php';
include './settings/settings_redirector.php';
include './settings/config_redirector.php';
if (debug){
set_error_handler(function($errno, $errstr, $errfile, $errline) {
debuglog("PHP ERROR [$errno]: $errstr in $errfile on line $errline");
return false; // Let PHP handle as usual (optional)
});
set_exception_handler(function($exception) {
debuglog("PHP EXCEPTION: " . $exception->getMessage() . " in " . $exception->getFile() . " on line " . $exception->getLine());
});
}
//------------------------------------------
// Header security - enabled via config
//------------------------------------------
if (header_security){
// Array of allowed domain patterns (without the protocol part)
$allowedDomainPatterns = [
'vanbeers.tv',
'soveliti.nl',
'veliti.nl',
'gewoonlekkerspaans.nl'
];
// Get the origin from the request headers
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
// Set CORS headers if origin is allowed
if (isOriginAllowed($origin, $allowedDomainPatterns)) {
header("Access-Control-Allow-Origin: $origin");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
//header("Access-Control-Allow-Credentials: true"); // Include if needed
}
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
// Return early with 204 No Content for preflight requests
http_response_code(204);
exit;
}
// Strict security headers
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Content-Security-Policy: default-src \'none\'');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('Referrer-Policy: strict-origin-when-cross-origin');
// Validate Content-Type
if (!str_contains($_SERVER['CONTENT_TYPE'] ?? '', 'application/json')) {
http_response_code(400);
exit(json_encode(['error' => 'Invalid Content-Type']));
}
// Validate request size
$maxRequestSize = 5 * 1024 * 1024; // 5MB in bytes
if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $maxRequestSize) {
http_response_code(413);
exit(json_encode(['error' => 'Request too large']));
}
}
//------------------------------------------
// Retrieve API version and Collection
@@ -69,7 +134,7 @@ if($is_jwt_valid && str_contains($version, 'v')) {
//------------------------------------------
// Check for maintenance mode, exclude debug user
//------------------------------------------
if(maintenance_mode == false|| debug_id == $user_data['id']){
if(maintenance_mode == false || debug_id == $user_data['id']){
//------------------------------------------
// Build up version and check if file is available
@@ -96,6 +161,28 @@ if($is_jwt_valid && str_contains($version, 'v')) {
//------------------------------------------
//CHECK IF USER IS ALLOWED TO CALL SPECIFIC API
//------------------------------------------
//------------------------------------------
// First check if endPoint is fileUpload
//------------------------------------------
$fileUploadEndpoints = [
'media_upload',
'marketing_upload'
];
$isFileUploadEndpoint = in_array($collection, $fileUploadEndpoints);
$hasValidFileData = !empty($_FILES) && $_SERVER['REQUEST_METHOD'] ==='POST';
if ($isFileUploadEndpoint && $hasValidFileData) {
$input = $_POST;
}
//------------------------------------------
// END check if endPoint is fileUpload
//------------------------------------------
debuglog("API call: collection=$collection, input_empty=" . (empty($input) ? 'true' : 'false') . ", file_exists=" . (file_exists($api_file) ? 'true' : 'false'));
if (isAllowed($collection,$profile,$permission,'R') === 1 && empty($input) && file_exists($api_file)){
include_once $api_file;
@@ -103,7 +190,7 @@ if($is_jwt_valid && str_contains($version, 'v')) {
elseif (isAllowed($collection,$profile,$permission,'U') === 1 && !empty($input) && file_exists($api_file_post)){
include_once $api_file_post;
}
}
else
{
//------------------------------------------

BIN
api/.DS_Store vendored

Binary file not shown.

BIN
api/v0/.DS_Store vendored

Binary file not shown.

View File

@@ -60,12 +60,12 @@ if (!empty($username) && !empty($password)) {
}
else
{
http_response_code(203);
http_response_code(403);
}
}
}
else {
http_response_code(203);
http_response_code(403);
}
$conn->close();
}

View File

@@ -216,12 +216,12 @@ case 'firmwareUpdate':
if (isset($_GET['sn']) && $_GET['sn'] != '' && isset($_GET['hw_version']) && $_GET['hw_version'] != '' && isset($_GET['sw_version']) && $_GET['sw_version'] != '') {
include './settings/settings.php';
include './settings/settings_redirector.php';
//Clean input data
$hw_device_send = strip_tags(trim($_GET['hw_version']));
$sw_device_send = strip_tags(trim($_GET['sw_version']));
//Check exceptions
if (in_array($_GET['sn'],$serialnumber_exceptions)){
//Serialnumber found in exceptions include exception file

View File

@@ -14,14 +14,14 @@ $stmt->execute([$userkey, $userkey]);
$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'];
$partner = json_decode($partnerhierarchy);
$language = $user_data['language'];
$clientsecret = $user_data['userkey'];
$permission = getHierarchyLevel($partner); //upgrade from userrights(view)
//Update Lastlogin
$logindate = date('Y-m-d H:i:s');

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();
}
@@ -229,21 +231,31 @@ if (!empty($post_content['sn']) && !empty($post_content['testdetails'])) {
}
else {
//GET HW + SW from object
$hw_version = $post_content['testdetails']['logdetails']['HW'];
$sw_version = $post_content['testdetails']['logdetails']['HEX_FW'];
$hw_version = $post_content['testdetails']['logdetails']['HW'] ?? '';
$fw_version = $post_content['testdetails']['logdetails']['FW'] ?? '';
$sw_version = $post_content['testdetails']['logdetails']['HEX_FW'] ?? '';
//GET COMMITCODE
$commitCode = compareCommitCodes($sw_version,$fw_version);
//IF COMMITCODE IS EMPTY THEN RETURN HEX_FW
$sw_version = ($commitCode != '' || !empty($commitCode)) ? $commitCode : $sw_version;
}
//check SW_VERSION for filetype
//check SW_VERSION for filetype HEX_FW can contain extension
$version_file_type = strtolower(substr($sw_version, -4)); // filetype
if ($version_file_type[0] == '.'){
$sw_version = substr($sw_version, 0, -4);
}
// Translate hardware version to standardized format
$translated_hw_version = translateDeviceHardwareVersion($hw_version);
//Update Equipment record
$sql = "UPDATE equipment SET hw_version = ?, sw_version = ? $whereclause";
$stmt = $pdo->prepare($sql);
$stmt->execute([$hw_version,$sw_version]);
$stmt->execute([$translated_hw_version,$sw_version]);
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Update equipment status ++++++++++++++++++++++++++
@@ -301,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

@@ -37,7 +37,8 @@ if ($stmt->rowCount() == 1) {
$stmt = $pdo->prepare($sql);
$stmt->execute([$resetkey,$user_data['id']]);
//STEP 2- Send to user
include_once './assets/mail/email_template_reset.php';
$mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php' : './assets/mail/email_template_reset.php');
include_once $mail_location;
send_mail($user_data['email'],$subject,$message,'','');
//STEP 3- Update Login count
$login_attempt = $user_data['login_count'] + 1;

View File

@@ -12,20 +12,8 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//NEW ARRAY
$criterias = [];

View File

@@ -29,24 +29,7 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//------------------------------------------
//default whereclause
//------------------------------------------
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like "'.$condition.'"';
break;
default:
$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.'"';
break;
}
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
//------------------------------------------
//NEW ARRAY
@@ -196,16 +179,17 @@ switch ($action) {
case 'geolocation':
if ($whereclause == ''){
$whereclause = 'WHERE geolocation is not null OR geolocation != "["",""]"';
$whereclause = 'WHERE geolocation is not null AND geolocation != \'["",""]\'';
} else {
$whereclause .= ' AND geolocation is not null OR geolocation != "["",""]';
$whereclause .= ' AND geolocation is not null AND geolocation != \'["",""]\'';
}
$sql = 'SELECT distinct(geolocation) FROM equipment e '.$whereclause.'';
break;
case 'report_usage_servicereports':
$sql = 'SELECT YEAR(h.created) AS year, QUARTER(h.created) AS quarter, MONTH(h.created) as month, count(h.rowID) AS count FROM equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID where h.type = "ServiceReport" AND NOT e.productrowid = "31" GROUP BY YEAR(h.created), QUARTER(h.created), MONTH(h.created)';
$exclusion = ' AND NOT e.serialnumber = "22050695" AND NOT e.serialnumber = "22020439" AND NOT e.serialnumber = "23060550" AND NOT e.serialnumber = "22020444" ';
$sql = 'SELECT YEAR(h.created) AS year, QUARTER(h.created) AS quarter, MONTH(h.created) as month, count(h.rowID) AS count FROM equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID where h.type = "ServiceReport" AND NOT e.productrowid = "31" '.$exclusion.' GROUP BY YEAR(h.created), QUARTER(h.created), MONTH(h.created)';
break;
case 'contract_usage_servicereports':

View File

@@ -12,24 +12,8 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//NEW ARRAY
$criterias = [];

View File

@@ -12,20 +12,7 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE salesID like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclauselvl2('communications',$permission,$partner,'get');
//NEW ARRAY
$criterias = [];

View File

@@ -17,18 +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':
$whereclause = 'WHERE u.view IN (4,5)';
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = 'WHERE c.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 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

@@ -15,24 +15,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//------------------------------------------
//NEW ARRAY
//------------------------------------------

View File

@@ -16,24 +16,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//------------------------------------------
//NEW ARRAY
//------------------------------------------
@@ -272,7 +256,7 @@ else {
}
//SQL for Paging
$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 '.$sort.' LIMIT :page,:num_products';
$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';
}
$stmt = $pdo->prepare($sql);

View File

@@ -14,22 +14,30 @@ 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':
$whereclause = '';
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$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 = '';
@@ -67,7 +75,7 @@ if(isset($get_content) && $get_content!=''){
//Filter out only relevant servicereports
$filter_key_1 = '"%serialnumber%"';
$filter_key_2 = '"ServiceReport"';
$clause .= ' AND h.type = '.$filter_key_2.' AND h.description like '.$filter_key_1;
$clause .= ' AND h.type = '.$filter_key_2.' AND e.productrowid = "31" AND h.description like '.$filter_key_1;
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];

View File

@@ -12,20 +12,7 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE salesID like :condition';
break;
}
list($whereclause,$condition) = getWhereclauselvl2('partners',$permission,$partner,'get');
//NEW ARRAY
$criterias = [];

View File

@@ -14,18 +14,7 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//NEW ARRAY
$criterias = [];

View File

@@ -14,18 +14,7 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//NEW ARRAY
$criterias = [];
@@ -57,7 +46,8 @@ if(isset($get_content) && $get_content!=''){
$clause .= ' AND e.serialnumber = :'.$v[0];
}
elseif ($v[0] == 'hw_version') {
//build up search
//build up search - translate hardware version for comparison
$criterias[$v[0]] = translateDeviceHardwareVersion($criterias[$v[0]]);
$clause .= ' AND ps.hw_version = :'.$v[0];
}
elseif ($v[0] == 'status') {
@@ -163,9 +153,11 @@ if (!isset($criterias['productrowid']) && isset($criterias['sn']) && $criterias[
//check if current version is send and update the equipment record
if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
// Translate hardware version to standardized format
$translated_hw_version = translateDeviceHardwareVersion($criterias['hw_version']);
$sql = 'UPDATE equipment SET hw_version = ?, updatedby = ? WHERE serialnumber = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['hw_version'],$username,$criterias['sn']]);
$stmt->execute([$translated_hw_version,$username,$criterias['sn']]);
}
//GET PRODUCTCODE, SW_VERSION_UPGRADE, HW_VERSION from equipment SN

View File

@@ -14,19 +14,6 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like "'.$condition.'"';
break;
}
//NEW ARRAY
$criterias = [];
$clause = '';
@@ -63,7 +50,10 @@ if(isset($get_content) && $get_content!=''){
if (isset($criterias['productrowid']) && $criterias['productrowid'] != ''){
//CHECK IF ALLOWED TO CRUD VERSIONS
$sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'";
list($whereclause2,$condition) = getWhereclause('',$permission,$partner,'get');
$sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause2.'";
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['productrowid']]);
$product_data = $stmt->fetch();

View File

@@ -12,24 +12,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('profile',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE partnerhierarchy like :condition ';
break;
default:
$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 partnerhierarchy like :condition ';
break;
}
//NEW ARRAY
$criterias = [];
$clause = '';

View File

@@ -16,14 +16,14 @@ if ($stmt->rowCount() == 1) {
$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'];
$language = $user_data['language'];
$partner = json_decode($partnerhierarchy);
$clientsecret = $user_data['userkey'];
$permission = getHierarchyLevel($partner); //upgrade from userrights(view)
//Update Lastlogin
$logindate = date('Y-m-d H:i:s');

View File

@@ -12,24 +12,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('profile',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE partnerhierarchy like :condition ';
break;
default:
$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 partnerhierarchy like :condition ';
break;
}
//NEW ARRAY
$criterias = [];
$clause = '';

View File

@@ -13,21 +13,9 @@ $post_content = json_decode(decode_payload($input),true);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause to check if data is owned buy user
$whereclause = '';
//default whereclause
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID
@@ -52,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,18 +27,25 @@ 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':
$whereclause .= '';
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$whereclause = ' e.accounthierarchy like "'.$condition.'" AND ';
break;
case '2':
$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;
@@ -84,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

@@ -14,20 +14,8 @@ $post_content = json_decode(decode_payload($input),true);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID

View File

@@ -16,22 +16,7 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
default:
$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 = ' AND accounthierarchy like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID
@@ -73,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,
@@ -82,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,
@@ -135,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'],
@@ -143,7 +128,7 @@ else {
"location"=>$post_content['location']
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
$account = array(
"salesid"=>$partner->salesid,
"soldto"=>$post_content['soldto'],
@@ -175,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

@@ -16,22 +16,7 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
default:
$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 = ' AND accounthierarchy like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID
@@ -62,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,
@@ -72,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,
@@ -94,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'],
@@ -104,7 +89,7 @@ else {
);
}
elseif ($permission == 3){
elseif (getHierarchyLevel($partner) == 1){
$account = array(
"salesid"=>$partner->salesid,
"soldto"=>$post_content['soldto'],
@@ -177,6 +162,16 @@ if ($command == 'update'){
{
changelog($dbname,'equipment',$equipment_data['rowID'],'order_ref',$post_content['order_ref'],$username);
}
//UPDATE CHANGELOG BASED ON hw_version CHANGE
if (isset($post_content['hw_version']) && $post_content['hw_version'] != $equipment_data['hw_version'])
{
changelog($dbname,'equipment',$equipment_data['rowID'],'hw_version',$post_content['hw_version'],$username);
}
//UPDATE CHANGELOG BASED ON sw_version CHANGE
if (isset($post_content['sw_version']) && $post_content['sw_version'] != $equipment_data['sw_version'])
{
changelog($dbname,'equipment',$equipment_data['rowID'],'sw_version',$post_content['sw_version'],$username);
}
$post_content['accounthierarchy'] = $accounthierarchy;
@@ -222,18 +217,18 @@ $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('equipment_manage',$profile,$permission,'U') === 1 || isAllowed('equipments_mass_update',$profile,$permission,'U') === 1 || $owner_equipment === 1)){
if ($command == 'update' && (isAllowed('equipment',$profile,$permission,'U') === 1 || isAllowed('equipments_mass_update',$profile,$permission,'U') === 1 || $owner_equipment === 1)){
$sql = 'UPDATE equipment SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'insert' && isAllowed('equipment_manage',$profile,$permission,'C') === 1){
elseif ($command == 'insert' && isAllowed('equipment',$profile,$permission,'C') === 1){
$sql = 'INSERT INTO equipment ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
}
elseif ($command == 'delete' && (isAllowed('equipment_manage',$profile,$permission,'D') === 1 || $owner_equipment === 1)){
elseif ($command == 'delete' && (isAllowed('equipment',$profile,$permission,'D') === 1 || $owner_equipment === 1)){
//delete equipment
$stmt = $pdo->prepare('DELETE FROM equipment WHERE rowID = ? '.$whereclause.'');
$stmt->execute([ $id ]);

View File

@@ -14,20 +14,7 @@ $post_content = json_decode(decode_payload($input),true);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause to check if data is owned by user
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND salesID like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclauselvl2('partners',$permission,$partner,'');
//SET PARAMETERS FOR QUERY
$id = $post_content['partnerID'] ?? ''; //check for rowID
@@ -54,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,
@@ -69,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

@@ -14,20 +14,8 @@ $post_content = json_decode(decode_payload($input),true);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID
@@ -53,12 +41,30 @@ elseif ($command == 'insert'){
$post_content['created'] = $date;
$post_content['createdby'] = $username;
$post_content['accounthierarchy'] = $partner_product;
}
else {
//do nothing
}
//CREAT NEW ARRAY AND MAP TO CLAUSE
//CHECK IF CATEGORIES ARE SEND AND UPDATE
if (isset($post_content['categories'])){
if ($command != 'insert'){
//CHANGE OR DELETE SO PRODUCT_ID IS AVAILABLE IN CALL
$api_url = '/v2/products_categories/';
$data = json_encode(array("categories" => $post_content['categories'], "product_id" => $id), JSON_UNESCAPED_UNICODE);
$responses = ioApiv2($api_url,$data,$clientsecret);
} else {
//INSERT Product ROWID NOT AVAILABLE YET. store $post_content['categories'] in different variable.
$categories = $post_content['categories'];
}
//REMOVE CATERGORIES FROM POST_CONTENT ARRAY
unset($post_content['categories']);
}
//CREATe NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){
foreach ($post_content as $key => $var){
if ($key == 'submit' || $key == 'rowID'){
@@ -90,6 +96,11 @@ elseif ($command == 'insert' && isAllowed('products',$profile,$permission,'C') =
$sql = 'INSERT INTO products ('.$clause_insert.') VALUES ('.$input_insert.')';
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
$api_url = '/v2/products_categories/';
$data = json_encode(array("categories" => $categories, "product_id" => $id), JSON_UNESCAPED_UNICODE);
$responses = ioApiv2($api_url,$data,$clientsecret);
}
elseif ($command == 'delete' && isAllowed('products',$profile,$permission,'D') === 1){
$stmt = $pdo->prepare('DELETE FROM products WHERE rowID = ? '.$whereclause.'');

View File

@@ -14,20 +14,8 @@ $post_content = json_decode(decode_payload($input),true);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//ENSURE PRODUCTROWID IS SEND
if (isset($post_content['productrowid']) && $post_content['productrowid'] != ''){
@@ -54,33 +42,6 @@ if (isset($post_content['productrowid']) && $post_content['productrowid'] != '')
if ($command == 'insert'){
if(isset($post_content['software'])){
//CHECK FOR FILETYPE
$version = $post_content['software'];
$version_file_type = strtolower(substr($version, -4)); // filetype
//CHECK IF FILETYPE IS ADDED
if ($version_file_type[0] == '.'){
//BASED ON FILE TYPE DO THE FOLLOWING
switch ($version_file_type) {
case '.hex':
//USE FULL NAME EXCLUDING
$version = substr($version, 0, -4);
break;
default:
if (($pos = strpos($version, "_")) !== FALSE) {
$version = substr($version, $pos+1);
$version = substr($version, 0, -4); //remove filetype
}
break;
}
}
//SET CORRECT VERSION
$post_content['version'] = $version;
}
$post_content['latest'] = 1; //New software is always latest
$post_content['created'] = $date;
$post_content['createdby'] = $username;
@@ -120,7 +81,7 @@ if (isset($post_content['productrowid']) && $post_content['productrowid'] != '')
$stmt->execute([$post_content['productrowid'], $hw_eq_version ]);
}
$sql = 'UPDATE products_software SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
$sql = 'UPDATE products_software SET '.$clause.' WHERE rowID = ? ';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
@@ -141,7 +102,7 @@ if (isset($post_content['productrowid']) && $post_content['productrowid'] != '')
elseif ($command == 'delete' && isAllowed('products_software',$profile,$permission,'D') === 1){
//GET FILENAME AND REMOVE FROM SERVER
$sql = 'SELECT * FROM products_software WHERE rowID = ? '.$whereclause.'';
$sql = 'SELECT * FROM products_software WHERE rowID = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
//Get results
@@ -154,7 +115,7 @@ if (isset($post_content['productrowid']) && $post_content['productrowid'] != '')
unlink($software_file);
}
}
$stmt = $pdo->prepare('DELETE FROM products_software WHERE rowID = ? '.$whereclause.'');
$stmt = $pdo->prepare('DELETE FROM products_software WHERE rowID = ? ');
$stmt->execute([ $id ]);
//Add deletion to changelog

View File

@@ -14,20 +14,8 @@ $post_content = json_decode(decode_payload($input),true);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//ENSURE PRODUCTROWID IS SEND
if (isset($post_content['productrowid']) && $post_content['productrowid'] != ''){
@@ -80,7 +68,7 @@ if (isset($post_content['productrowid']) && $post_content['productrowid'] != '')
//QUERY AND VERIFY ALLOWED
if ($command == 'update' && isAllowed('products_versions',$profile,$permission,'U') === 1){
$sql = 'UPDATE products_versions SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
$sql = 'UPDATE products_versions SET '.$clause.' WHERE rowID = ? ';
$execute_input[] = $id;
$stmt = $pdo->prepare($sql);
$stmt->execute($execute_input);
@@ -91,7 +79,7 @@ if (isset($post_content['productrowid']) && $post_content['productrowid'] != '')
$stmt->execute($execute_input);
}
elseif ($command == 'delete' && isAllowed('products_versions',$profile,$permission,'D') === 1){
$stmt = $pdo->prepare('DELETE FROM products_versions WHERE rowID = ? '.$whereclause.'');
$stmt = $pdo->prepare('DELETE FROM products_versions WHERE rowID = ? ');
$stmt->execute([ $id ]);
//Add deletion to changelog

View File

@@ -42,7 +42,8 @@ $owner_user = (($user_data['username'] == $username)? 1 : 0);
$stmt = $pdo->prepare($sql);
$stmt->execute([$resetkey,$username,$id]);
//STEP 3 - Send to user
include_once './assets/mail/email_template_reset.php';
$mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php' : './assets/mail/email_template_reset.php');
include_once $mail_location;
send_mail($user_data['email'],$subject,$message,'','');
}
}

View File

@@ -15,24 +15,8 @@ $owner_user = 0;
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause to check if data is owned by user
$whereclause = '';
list($whereclause,$condition) = getWhereclause('profile',$permission,$partner,'');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND partnerhierarchy like "'.$condition.'"';
break;
default:
$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 = ' AND partnerhierarchy like "'.$condition.'"';
break;
}
//SET PARAMETERS FOR QUERY
$id = (isset($post_content['id'])) ? $post_content['id']: ''; //check for rowID
@@ -66,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,
@@ -74,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,
@@ -93,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'],
@@ -102,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,
@@ -136,7 +120,9 @@ $location_new = (($post_content['location'] != '' && $post_content['location'] !
$stmt = $pdo->prepare($sql);
$stmt->execute([$resetkey,$username,$id]);
//STEP 3 - Send to user
include_once './assets/mail/email_template_reset.php';
$mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php' : './assets/mail/email_template_reset.php');
include_once $mail_location;
send_mail($user_data['email'],$subject,$message,'','');
}
@@ -254,7 +240,8 @@ elseif ($command == 'insert' && isAllowed('user',$profile,$permission,'C') === 1
$stmt->execute($execute_input);
//STEP 2- Send to user
include_once './assets/mail/email_template_new.php';
$mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_new.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_new.php' : './assets/mail/email_template_new.php');
include_once $mail_location;
send_mail($post_content['email'],$subject,$message,'','');
} else {
//Encrypt results

BIN
api/v2/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -38,7 +38,8 @@ if ($stmt->rowCount() == 1) {
$stmt = $pdo->prepare($sql);
$stmt->execute([$resetkey,$user_data['id']]);
//STEP 2- Send to user
include_once './assets/mail/email_template_reset.php';
$mail_location = (file_exists($_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php') ? $_SERVER['DOCUMENT_ROOT'].'/custom/'.$domain.'/mail/email_template_reset.php' : './assets/mail/email_template_reset.php');
include_once $mail_location;
send_mail($user_data['email'],$subject,$message,'','');
//STEP 3- Update Login count
$login_attempt = $user_data['login_count'] + 1;
@@ -69,6 +70,11 @@ if ($stmt->rowCount() == 1) {
$stmt_service->execute([$user_data['service'], $user_data['id']]);
}
$user_data['refreshkey'] = bin2hex(random_bytes(25));
$sql_refreshkey = 'UPDATE users SET refreshkey = ? WHERE id = ?';
$stmt_refreshkey = $pdo->prepare($sql_refreshkey);
$stmt_refreshkey->execute([$user_data['refreshkey'], $user_data['id']]);
$token = createCommunicationToken($user_data['userkey']);
//RETURN JWT AND CLIENTSECRET
@@ -76,7 +82,9 @@ if ($stmt->rowCount() == 1) {
'clientID' => $user_data['username'],
'token' => $token,
'token_valid' => date('Y-m-d H:i:s',time() + 1800),
'userkey' => $user_data['userkey']
'userkey' => $user_data['userkey'],
'refreshkey' => $user_data['refreshkey'],
'language' => $user_data['language']
);
//Reset login count after succesfull attempt

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

@@ -12,20 +12,8 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = ' AND accounthierarchy like "'.$condition.'"';
break;
}
//NEW ARRAY
$criterias = [];

View File

@@ -29,24 +29,7 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//------------------------------------------
//default whereclause
//------------------------------------------
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like "'.$condition.'"';
break;
default:
$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.'"';
break;
}
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
//------------------------------------------
//NEW ARRAY
@@ -196,9 +179,9 @@ switch ($action) {
case 'geolocation':
if ($whereclause == ''){
$whereclause = 'WHERE geolocation is not null OR geolocation != "["",""]"';
$whereclause = 'WHERE geolocation is not null AND geolocation != \'["",""]\'';
} else {
$whereclause .= ' AND geolocation is not null OR geolocation != "["",""]';
$whereclause .= ' AND geolocation is not null AND geolocation != \'["",""]\'';
}
$sql = 'SELECT distinct(geolocation) FROM equipment e '.$whereclause.'';

150
api/v2/get/appointment.php Normal file
View File

@@ -0,0 +1,150 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Appointments
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//NEW ARRAY
$criterias = [];
//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];
}
}
//GET SLOTS PER DEALER
if(isset($criterias['action']) && $criterias['action'] == 'get_slots' && isset($criterias['dealer_id']) && isset($criterias['year']) && isset($criterias['month'])){
//DECODE DEALER_ID
$dealer_id = decodeUuid($criterias['dealer_id']);
$year = (int)$criterias['year'];
$month = (int)$criterias['month'];
// Get the number of days in the month
$num_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
//GET OPENING_HOURS
$sql_opening_hours = 'SELECT opening_hours FROM dealers WHERE rowID = ?';
$stmt = $pdo->prepare($sql_opening_hours);
$stmt->execute([$dealer_id]);
$opening_hours = $stmt->fetch(PDO::FETCH_ASSOC);
$opening_hours = json_decode($opening_hours['opening_hours'],true);
if (empty($opening_hours)){
// Define opening hours
$opening_hours = [
1 => ['start' => '09:00', 'end' => '17:00'], // Monday
2 => ['start' => '09:00', 'end' => '17:00'], // Tuesday
3 => ['start' => '09:00', 'end' => '17:00'], // Wednesday
4 => ['start' => '09:00', 'end' => '17:00'], // Thursday
5 => ['start' => '09:00', 'end' => '17:00'], // Friday
6 => ['start' => '09:00', 'end' => '17:00'], // Saturday
7 => null // Sunday - Closed
];
} else {
// Convert all string "null" values to actual null
foreach ($opening_hours as $day => $hours) {
if ($hours === "null") {
$opening_hours[$day] = null;
}
}
}
// Initialize an array to store the available slots for the entire month
$all_available_slots = [];
// Initialize a counter for the slot IDs
$id_counter = 1;
// Iterate over each day in the month
for ($day = 1; $day <= $num_days; $day++) {
// Create a full date string
$full_date = sprintf("%04d-%02d-%02d", $year, $month, $day);
// Determine the day of the week (1 = Monday, 7 = Sunday)
$day_of_week = date('N', strtotime($full_date));
// Check if the day is open
if ($opening_hours[$day_of_week] === null) {
continue; // Skip closed days (Sunday)
}
// Get existing booked/unavailable slots for the day
$booked_slots_sql = "SELECT start_time, end_time FROM appointment_slots
WHERE DATE(start_time) = ? AND dealer_id = ? AND is_available = false";
$stmt = $pdo->prepare($booked_slots_sql);
$stmt->execute([$full_date, $dealer_id]);
$booked_result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Store booked slots for the day
$booked_slots = [];
foreach ($booked_result as $row){
$booked_slots[] = [
'start' => substr($row['start_time'], 11, 5),
'end' => substr($row['end_time'], 11, 5)
];
}
// Generate all possible slots for the day
$start_time = new DateTime($full_date . ' ' . $opening_hours[$day_of_week]['start']);
$end_time = new DateTime($full_date . ' ' . $opening_hours[$day_of_week]['end']);
$interval = new DateInterval('PT1H');
// Iterate through each hour and check availability
while ($start_time < $end_time) {
$slot_end = clone $start_time;
$slot_end->add($interval);
// Check if this slot is booked
$is_available = true;
foreach ($booked_slots as $booked) {
$booked_start = new DateTime($full_date . ' ' . $booked['start']);
$booked_end = new DateTime($full_date . ' ' . $booked['end']);
if (($start_time >= $booked_start && $start_time < $booked_end) ||
($slot_end > $booked_start && $slot_end <= $booked_end)) {
$is_available = false;
break;
}
}
// If the slot is available, add it to the list
if ($is_available) {
$all_available_slots[] = [
'id' => $id_counter++,
'start_time' => $start_time->format('Y-m-d H:i:s'),
'end_time' => $slot_end->format('Y-m-d H:i:s')
];
}
$start_time->add($interval);
}
}
$messages = $all_available_slots;
} else {
$messages =['success' => false, 'slots' => ''];
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

View File

@@ -12,24 +12,8 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//NEW ARRAY
$criterias = [];

245
api/v2/get/catalog.php Normal file
View File

@@ -0,0 +1,245 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//------------------------------------------
// Catalog
//------------------------------------------
//------------------------------------------
//Create Catalog
//------------------------------------------
$catalog = []; // Main catalog array
//NEW ARRAY
$criterias = [];
$filter = '';
//Check for $_GET variables and build $_GET
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] ?? true;
if ($v[0] == 'category'){
//------------------------------------------
//IF CATEGORY IS RECEIVED ONLY GET RELATED PRODUCTS
//------------------------------------------
$url_input = '';
//Get all the related products from the database
$cat_products = ioAPIv2('/v2/products_categories/list=filter&category_id='.$v[1],'',$clientsecret);
$cat_products = json_decode($cat_products,true);
foreach($cat_products as $cat_product_id){
$url_input .= $cat_product_id['product_id'].',';
}
$filter .= '&product_id='.substr($url_input,0,-1);
}
elseif ($v[0] == 'product_id'){
$filter .= '&product_id='.$v[1];
}
}
}
//------------------------------------------
//GET ACTIVE AND SALES RELATED PRODUCTS
//------------------------------------------
//GET PRODUCTS
$api_url = '/v2/products/salesflag=1&status=1'.$filter;
$products = ioApi($api_url,'',$clientsecret);
$products = json_decode($products,true);
foreach ($products as $product) {
//------------------------------------------
// Create product entry in catalog if it doesn't exist
//------------------------------------------
if (!isset($catalog[$product['rowID']])) {
$catalog[$product['rowID']] = $product;
$catalog[$product['rowID']]['versions'] = []; // Changed to versions array
}
//------------------------------------------
//Check for configurations and add to product
//------------------------------------------
if (isset($product['configurable']) && $product['configurable'] == 1){
//GET ACTIVE CONFIGURATIONS ITEMS BASED ON ACTIVE VERSIONS
$api_url = '/v2/products_configurations/status=1&version_status=1&productrowid='.$product['rowID'] ;
$product_config = ioApi($api_url,'',$clientsecret);
$product_config = json_decode($product_config,true);
//------------------------------------------
// Group configurations by version
//------------------------------------------
$version_configurations = [];
foreach ($product_config as $item) {
if ($item['productrowid'] == $product['rowID']) {
// Initialize version array if it doesn't exist
if (!isset($version_configurations[$item['version']])) {
$version_configurations[$item['version']] = [
'version_id' => $item['version'],
'config_setting' => $item['config'],
'main_option_for_display' => $item['measurement'] ?? '',
'configurations' => []
];
}
if ($item['type'] == 'product') {
$version_configurations[$item['version']]['configurations'][] = $item;
}
if ($item['type'] == 'group') {
$api_url = '/v2/products_attributes_items/item_status=1&list=catalog&group_id='.$item['assignment'];
$attributes = ioApi($api_url,'',$clientsecret);
$attributes = json_decode($attributes,true);
// Add attributes to the group item
$item['attributes'] = $attributes;
$version_configurations[$item['version']]['configurations'][] = $item;
}
}
}
// Add all version configurations to the catalog
$catalog[$product['rowID']]['versions'] = array_values($version_configurations);
}
}
//------------------------------------------
// Lookup pricing (active pricelist and pricelistitems only)
//------------------------------------------
$api_url = '/v2/pricelists/status=1&item_status=1&list=price';
$pricelist = ioApi($api_url,'',$clientsecret);
$pricelist = json_decode($pricelist,true);
foreach ($pricelist as $price) {
// Add price to product level
if (isset($catalog[$price['product_id']])) {
$catalog[$price['product_id']]['price'] = $price['price'];
$catalog[$price['product_id']]['rrp'] = $price['rrp'];
$catalog[$price['product_id']]['price_modifier'] = $price['price_modifier'];
}
//Check for configuration (can also include products as above)
foreach ($catalog as &$items) {
if (!empty($items['versions'])) {
foreach ($items['versions'] as &$version) {
foreach ($version['configurations'] as &$config) {
//UPDATE PRODUCT PRICES IN CONFIGURATION
if ($config['type'] == 'product' && $config['assignment'] == $price['product_id']) {
$config['price'] = $price['price'];
$config['rrp'] = $price['rrp'];
$config['price_modifier'] = $price['price_modifier'];
}
//UPDATE PRICES OF ATTRIBUTES IN GROUPS
if ($config['type'] == 'group') {
//check all attributes
foreach($config['attributes'] as &$attribute) {
if ($attribute['attribute_id'] == $price['product_id']) {
$attribute['price'] = $price['price'];
$attribute['rrp'] = $price['rrp'];
$attribute['price_modifier'] = $price['price_modifier'];
}
}
}
}
}
}
}
}
//------------------------------------------
//REMOVE KEYS FROM OUTPUT
//------------------------------------------
$keys_to_remove = ['status','item_status','group_status','version','config','sn','build','softwareversion','healthindex','salesflag','configurable','updatedby','createdby','updated','created'];
removeKeysRecursive($catalog,$keys_to_remove);
//------------------------------------------
//Catalog processor to split versions as new product
//------------------------------------------
$messages = processProductCollection($catalog);
//------------------------------------------
//check for METAfeed request
//------------------------------------------
if (isset($criterias['meta'])){
//------------------------------------------
// Meta Feed Configuration
//------------------------------------------
$meta_config = [
'base_url' => 'https://www.morvalwatches.com', // Product page URL
'image_base_url' => 'https://cloud.soveliti.nl',
'brand' => 'Morval Watches',
'currency' => 'EUR',
'condition' => 'new',
'availability' => 'in stock',
'google_product_category' => 'Apparel & Accessories > Jewelry > Watches',
'output_format' => 'json' // Options: 'csv', 'xml', 'json'
];
//------------------------------------------
// Product Code Based Descriptions
// Keys can be: exact code (MWTH2NB) or pattern (MWTH1*, MWTH2*)
//------------------------------------------
$meta_descriptions = [
// Pattern based (will match any product starting with this)
'MWTH1' => 'The Thomas-I exudes elegance and sophistication. Classic dimensions combined with subtle details in the dial make it an special automatic watch that can be worn on all occasions.',
'MWTH2' => 'The Thomas-II provides a view of the beating heart of the Swiss timepiece. It marks the precision and perfection with which the time is displayed.',
'MWABR' => 'Handmade Italian calf leather bracelet',
];
//------------------------------------------
//Include meta functions
//------------------------------------------
include_once './assets/functions_meta.php';
$meta_feed = catalogToMetaFeed($messages, $meta_config);
//------------------------------------------
// Output based on format parameter
//------------------------------------------
if ($criterias['meta'] === true) {
$format = $meta_config['output_format'];
} else {
$format = $criterias['meta'];
}
switch ($format) {
case 'xml':
$messages = outputMetaFeedXML($meta_feed);
break;
case 'csv':
$messages = outputMetaFeedCSV($meta_feed);
break;
case 'json':
default:
$messages = outputMetaFeedJSON($meta_feed);
break;
}
exit();
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages;
?>

112
api/v2/get/categories.php Normal file
View File

@@ -0,0 +1,112 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// categories
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND name like :'.$v[0];
}
elseif ($v[0] == 'rowid_exclude') {
//build up search
$clause .= ' AND rowID != :'.$v[0];
}
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 categories '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM categories '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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];
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_categories, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_categories, PDO::PARAM_INT);
//Excute 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,18 +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':
$whereclause = 'WHERE u.view IN (4,5)';
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;

149
api/v2/get/dealers.php Normal file
View File

@@ -0,0 +1,149 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// dealers
//------------------------------------------
//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("dealers",$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND d.name like :'.$v[0];
}
elseif ($v[0] == 'id') {//create clause
$clause .= ' AND d.rowID = :'.$v[0];
}
elseif ($v[0] == 'rating_overall') {//create clause
$clause .= ' AND d.rating_overall >= :'.$v[0];
}
else {//create clause
$clause .= ' AND d.'.$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 dealers d '.$whereclause;
}
elseif (isset($criterias['list']) && $criterias['list'] ==''){
$sql = 'SELECT d.* FROM dealers d '.$whereclause;
}
else {
//SQL for Paging
$sql = 'SELECT d.*, m.full_path FROM dealers d LEFT JOIN media m ON d.dealer_media = m.rowID '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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 == 'rowid' || $key == 'id' ){
//decode UUID to ID
$decoded_value = decodeUuid($value);
$stmt->bindValue($key, $decoded_value, PDO::PARAM_STR);
}
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];
//No further data transformation need
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
//exit
exit();
}
elseif (isset($criterias['list']) && $criterias['list']==''){
//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_dealers, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_dealers, PDO::PARAM_INT);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//CHANGE ROWID INTO UUID
//------------------------------------------
function updateRowID($row) {
$row['rowID'] = encodeUuid($row['rowID']);
return $row;
}
$updatedData = array_map('updateRowID', $messages);
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($updatedData, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

View File

@@ -0,0 +1,125 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// dealers
//------------------------------------------
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//ENSURE PRODUCTROWID IS SEND
if (isset($criterias['dealer_id']) && $criterias['dealer_id'] != ''){
//CHECK IF ALLOWED TO CRUD VERSIONS
$sql = "SELECT * FROM dealers WHERE rowID = ? '.$whereclause.'";
$stmt = $pdo->prepare($sql);
$stmt->execute([decodeUuid($criterias['dealer_id'])]);
$dealer_data = $stmt->fetch();
$dealer_owner = ($dealer_data['rowID'])? 1 : 0;
//IF PRODUCT IS OWNED THEN CRUD is ALLOWED
if ($dealer_owner === 1 ){
//Define Query
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM dealers_media '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for Paging
$sql = 'SELECT * FROM dealers_media '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT p_m.*, m.full_path FROM dealers_media p_m LEFT JOIN media m ON p_m.media_id = m.rowID '.$whereclause.'';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']==''){
//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_dealers, PDO::PARAM_INT);
//$stmt->bindValue('num_dealers', $page_rows_dealers, PDO::PARAM_INT);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
}
}
?>

122
api/v2/get/discounts.php Normal file
View File

@@ -0,0 +1,122 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// discounts
//------------------------------------------
//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("discounts",$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND name like :'.$v[0];
}
elseif ($v[0] == 'discount_category_id'){
$clause .= ' AND d.id = :'.$v[0];
}
elseif ($v[0] == 'discount_products_id'){
$clause .= ' AND d.id = :'.$v[0];
}
else {//create clause
$clause .= ' AND d.'.$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 discounts '.$whereclause.'';
}
elseif(isset($criterias['discount_category_id']) && $criterias['discount_category_id'] !=''){
$sql ='SELECT c.name, c.rowID FROM discounts d JOIN categories c ON FIND_IN_SET(c.rowID, d.category_ids) '.$whereclause;
}
elseif(isset($criterias['discount_products_id']) && $criterias['discount_products_id'] !=''){
$sql ='SELECT p.productname, p.rowID FROM discounts d JOIN products p ON FIND_IN_SET(p.rowID, d.product_ids) '.$whereclause;
}
else {
//SQL for Paging
$sql = 'SELECT d.*, GROUP_CONCAT(DISTINCT p.productname) product_names, GROUP_CONCAT(DISTINCT c.name) category_names FROM discounts d LEFT JOIN products p ON FIND_IN_SET(p.rowID, d.product_ids) LEFT JOIN categories c ON FIND_IN_SET(c.rowID, d.category_ids) '.$whereclause.' GROUP BY d.id, d.category_ids, d.product_ids, d.discount_code, d.discount_type, d.discount_type, d.discount_value, d.start_date, d.end_date LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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];
} else if ((isset($criterias['discount_category_id']) && $criterias['discount_category_id'] !='') || (isset($criterias['discount_products_id']) && $criterias['discount_products_id'] !='')){
//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_discounts, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_discounts, PDO::PARAM_INT);
//Excute 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

@@ -15,24 +15,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//------------------------------------------
//NEW ARRAY
//------------------------------------------

View File

@@ -15,24 +15,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//------------------------------------------
//NEW ARRAY
//------------------------------------------

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

@@ -4,7 +4,6 @@ defined($security_key) or exit;
//------------------------------------------
// Equipments
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
@@ -15,24 +14,8 @@ $partner = json_decode($partnerhierarchy);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE e.accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//------------------------------------------
//NEW ARRAY
//------------------------------------------
@@ -66,6 +49,9 @@ if(isset($get_content) && $get_content!=''){
elseif ($v[0] == 'equipmentid') {
//build up search
$clause .= ' AND e.rowID = :'.$v[0];
//UPDATE VERSION STATUS
$sw_version_latest_update = 1;
}
elseif ($v[0] == 'servicedate') {
//build up service coverage
@@ -86,6 +72,7 @@ if(isset($get_content) && $get_content!=''){
elseif ($v[0] == 'h_equipmentid') {
//build up search
$clause .= ' AND h.equipmentid = :'.$v[0];
}
elseif ($v[0] == 'status') {
//Update status based on status
@@ -97,8 +84,38 @@ if(isset($get_content) && $get_content!=''){
$clause .= ' AND (serialnumber like :'.$v[0].' OR e.rowID like :'.$v[0].')';
}
elseif ($v[0] == 'partnerid') {
//build up accounthierarchy
$clause .= ' AND e.accounthierarchy like :'.$v[0];
//PARTNER INFORMATION
$api_url = '/v2/partners/partnerID='.$v[1] ;
$partner_return = ioApi($api_url,'',$clientsecret);
$partner_return = json_decode($partner_return ,true);
$partner_return = $partner_return[0];
if ($partner_return){
//PARTNER FOUND
switch ($partner_return['partnertype']) {
case 'SalesID':
$clause .= ' AND e.accounthierarchy like "%_salesid_:_'.$v[1].'-%"';
break;
case 'SoldTo':
$clause .= ' AND e.accounthierarchy like "%_soldto_:_'.$v[1].'-%"';
break;
case 'ShipTo':
$clause .= ' AND e.accounthierarchy like "%_shipto_:_'.$v[1].'-%"';
break;
case 'Location':
$clause .= ' AND e.accounthierarchy like "%_location_:_'.$v[1].'-%"';
break;
}
} else {
//Partner not found
//Partner not found return empty
$clause .= ' AND e.accounthierarchy =""';
}
//remove original key/value from array
unset($criterias[$v[0]]);
}
elseif ($v[0] == 'serialnumber') {
//build up serialnumber
@@ -126,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';
@@ -144,29 +165,12 @@ if(isset($get_content) && $get_content!=''){
}
}
if ($sw_version_latest_update == 1){
if ($sw_version_latest_update == 1 || $clause == ''){
//------------------------------------------
//UPDATE SW_STATUS
//------------------------------------------
//UPDATE ASSETS-> SW_LATEST_VERSION WITH NO PRODUCT_SOFTWARE TO 2
$sql = 'UPDATE equipment e LEFT JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 2 WHERE ps.rowID IS NULL';
$stmt = $pdo->prepare($sql);
$stmt->execute();
//UPDATE ASSETS-> SW_LATEST_VERSION WITH PRODUCT_SOFTWARE FROM 2 TO 0
$sql = 'UPDATE equipment e LEFT JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 0 WHERE ps.rowID IS NOT NULL AND sw_version_latest = 2';
$stmt = $pdo->prepare($sql);
$stmt->execute();
//UPDATE LATEST TO NO IN CASE HW_VERSION ARE EQUAL AND SW_VERSIONS NOT AND NOT LATEST
$sql = 'UPDATE equipment e JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 0 WHERE ps.latest = 1 AND lower(e.sw_version) <> lower(ps.version) AND lower(e.hw_version) = lower(ps.hw_version) AND e.sw_version_latest = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute();
//UPDATE LATEST TO YES IN CASE HW_VERSION ARE EQUAL AND SW_VERSIONS ARE EQUAL
$sql = 'UPDATE equipment e JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 1 WHERE ps.latest = 1 AND lower(e.sw_version) = lower(ps.version) AND lower(e.hw_version) = lower(ps.hw_version) AND e.sw_version_latest = 0';
$stmt = $pdo->prepare($sql);
$stmt->execute();
// Use the reusable function to update software version status for all equipment
updateSoftwareVersionStatus($pdo);
//------------------------------------------
//------------------------------------------
}
@@ -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 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

@@ -0,0 +1,44 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Generate Download Token Helper
// Allows authenticated users to generate download URL tokens server-side
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//NEW ARRAY
$criterias = [];
//Parse GET parameters
if(isset($get_content) && $get_content != ''){
$requests = explode("&", $get_content);
foreach ($requests as $y){
$v = explode("=", $y);
$criterias[$v[0]] = $v[1];
}
}
// Validate required parameters
if (!isset($criterias['sn']) || !isset($criterias['version_id'])) {
http_response_code(400);
echo json_encode(["error" => "MISSING_PARAMETERS", "message" => "sn and version_id required"]);
exit;
}
// Generate token
$token = create_download_url_token($criterias['sn'], $criterias['version_id']);
$download_url = "https://" . $_SERVER['SERVER_NAME'] . "/api.php/v2/get/software_download?token=" . $token;
// Return token and download URL
echo json_encode([
"success" => true,
"token" => $token,
"download_url" => $download_url,
"expires_in_seconds" => 900,
"serial_number" => $criterias['sn'],
"version_id" => $criterias['version_id']
]);
?>

View File

@@ -13,26 +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':
$whereclause = '';
case '1':
$condition = '__salesid___'.$partner->salesid.'___soldto___%';
$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!=''){
@@ -63,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 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 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
@@ -88,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';
@@ -124,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);
@@ -135,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;

115
api/v2/get/identity.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Consumer identity
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//Get user_rights from users.php
$partner = json_decode($partnerhierarchy);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//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] == 'search') {
//build up search
$clause .= ' AND email like :'.$v[0];
}
elseif ($v[0] == 'partnerid') {
//check accounthierarchy related users
$clause .= ' AND accounthierarchy like :'.$v[0];
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//ASSIGN DEALER ID TO IDENTITY
if(isset($criterias['userkey'])){
checkAndInsertIdentityDealer($pdo, $criterias['userkey']);
}
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count from identity '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT id,email,profile,first_name,last_name,address_street,address_city,address_state,address_zip,address_country,address_phone,lastlogin,userkey,language,login_count,created,createdby,updated,updatedby,accounthierarchy FROM identity '.$whereclause.' ORDER BY lastlogin DESC LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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 == 'partnerid'){
$search_value = '%"_"'.$value.'-%';
$stmt->bindValue($key, $search_value, PDO::PARAM_STR);
}
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];
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_users, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_users, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,59 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//------------------------------------------
// dealers
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//NEW ARRAY
$criterias = [];
$messages = '';
//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];
}
}
//IDENTITY REQUEST - override SQL
if(isset($criterias['identity_id'])){
$sql = 'SELECT d.*, m.full_path FROM identity_dealers id JOIN dealers d ON id.dealer_ID = d.rowID LEFT JOIN media m ON d.dealer_media = m.rowID WHERE identity_id='.$criterias['identity_id'].'';
$stmt = $pdo->prepare($sql);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
//------------------------------------------
//CHANGE ROWID INTO UUID
//------------------------------------------
function updateRowID($row) {
$row['rowID'] = encodeUuid($row['rowID']);
return $row;
}
$updatedData = array_map('updateRowID', $messages);
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($updatedData, JSON_UNESCAPED_UNICODE);
}
//Send results
echo $messages;
?>

116
api/v2/get/invoice.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// invoice
//------------------------------------------
//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("invoice",$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
else {//create clause
$clause .= ' AND inv.'.$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 invoice inv '.$whereclause.'';
}
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.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;
}
else {
//SQL for Paging
$sql = 'SELECT * FROM invoice inv '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']=='invoice'){
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
$messages = transformOrderData($messages);
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_invoice, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_invoice, PDO::PARAM_INT);
//Excute 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

@@ -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);

115
api/v2/get/media.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products attributes
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclauselvl2('',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND title like :'.$v[0];
}
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 media '.$whereclause.'';
}
elseif ($criterias['list'] && $criterias['list'] =='product_image') {
//SQL for Paging
$sql = 'SELECT * FROM media '.$whereclause;
}
else {
//SQL for Paging
$sql = 'SELECT * FROM media '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']=='product_image'){
$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_media, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_media, PDO::PARAM_INT);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

115
api/v2/get/partners.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products
//------------------------------------------
//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('partners',$permission,$partner,'get');
//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'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND partnername like :'.$v[0];
}
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 partner '.$whereclause.'';
}
elseif(isset($criterias['list']) && $criterias['list'] ==''){
//Request for total rows
$sql = 'SELECT * FROM partner '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM partner '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']==''){
//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_partners, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_partners, PDO::PARAM_INT);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

88
api/v2/get/payment.php Normal file
View File

@@ -0,0 +1,88 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Payment Status Retrieval
//------------------------------------------
// This endpoint retrieves payment details for verification
//Connect to DB
$pdo = dbConnect($dbname);
//NEW ARRAY
$criterias = [];
//Check for $_GET variables
if(isset($get_content) && $get_content!=''){
$requests = explode("&", $get_content);
foreach ($requests as $y){
$v = explode("=", $y);
$criterias[$v[0]] = $v[1];
}
}
// Validate payment_id
if (empty($criterias['payment_id'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing required parameter: payment_id'], JSON_UNESCAPED_UNICODE);
exit;
}
$payment_id = $criterias['payment_id'];
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 1: Fetch transaction
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
$sql = 'SELECT * FROM transactions WHERE txn_id = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$payment_id]);
$transaction = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$transaction) {
http_response_code(404);
echo json_encode(['error' => 'Payment not found'], JSON_UNESCAPED_UNICODE);
exit;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 2: Fetch transaction item
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
$sql = 'SELECT * FROM transactions_items WHERE txn_id = ? LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$transaction['id']]);
$item = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$item) {
http_response_code(404);
echo json_encode(['error' => 'Payment item not found'], JSON_UNESCAPED_UNICODE);
exit;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 3: Parse item_options JSON
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
$item_options = [];
if (!empty($item['item_options'])) {
$item_options = json_decode($item['item_options'], true);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// STEP 4: Return payment details
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
$messages = json_encode([
'payment_id' => $transaction['txn_id'],
'payment_status' => $transaction['payment_status'],
'payment_amount' => $transaction['payment_amount'],
'currency' => 'EUR', // Default currency
'serial_number' => $item_options['serial_number'] ?? null,
'equipment_id' => $item_options['equipment_id'] ?? null,
'hw_version' => $item_options['hw_version'] ?? null,
'version_id' => $item['item_id'],
'payer_email' => $transaction['payer_email'],
'customer_name' => trim(($transaction['first_name'] ?? '') . ' ' . ($transaction['last_name'] ?? '')),
'created' => $transaction['created']
], JSON_UNESCAPED_UNICODE);
echo $messages;
?>

119
api/v2/get/pricelists.php Normal file
View File

@@ -0,0 +1,119 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Pricelists
//------------------------------------------
//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) = getWhereclause('pricelists',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'name') {
//build up search
$clause .= ' AND pls.name like :'.$v[0];
}
elseif ($v[0] == 'item_status') {
//build up search
$clause .= ' AND pli.status = :'.$v[0];
}
else {//create clause
$clause .= ' AND pls.'.$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 pricelists pls '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='price'){
$sql = 'SELECT pls.*,pli.* FROM pricelists pls JOIN pricelists_items pli ON pls.rowID = pli.pricelist_ID '.$whereclause;
}
else {
//SQL for Paging
$sql = 'SELECT * FROM pricelists pls '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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'])){
//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_pricelists, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_pricelists, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,107 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Pricelists items
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND product_ID like :'.$v[0];
}
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 pricelists_items '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM pricelists_items '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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];
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_pricelists, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_pricelists, PDO::PARAM_INT);
//Excute 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

@@ -13,19 +13,10 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
$whereclause_alt = '';
$whereclause_alt2 = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclause('products',$permission,$partner,'get');
//NEW ARRAY
$criterias = [];
@@ -46,10 +37,36 @@ if(isset($get_content) && $get_content!=''){
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND productcode like :'.$v[0];
$clause .= ' AND p.productcode like :'.$v[0];
}
elseif ($v[0] == 'product_id') {
//build up product_id = rowID
//check if multiple product_ids 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 p.rowID IN ('.$new_querystring.')';
//remove original key/value from array
unset($criterias[$v[0]]);
}
else {
$clause .= ' AND (p.rowID IN (:'.$v[0].') or p.url_slug =:'.$v[0].')';
}
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];
$clause .= ' AND p.'.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
@@ -61,15 +78,48 @@ if(isset($get_content) && $get_content!=''){
//Define Query
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM products '.$whereclause.'';
$sql = 'SELECT count(*) as count FROM products p '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for Paging
$sql = 'SELECT * FROM products '.$whereclause.'';
$sql = 'SELECT * FROM products p '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='price'){
//SET SPECIFIC WHERECLAUSE
if ($whereclause == ''){
$whereclause_1 = 'WHERE p.salesflag = 1';
$whereclause_2 = 'WHERE pat.item_status = 1';
} else {
$whereclause_1 = $whereclause .' AND p.salesflag = 1 AND p.status = 1 ';
list($whereclause_alt,$condition_alt) = getWhereclause('products_attributes_items',$permission,$partner,'get');
$whereclause_2 = $whereclause_alt .' AND pat.item_status = 1';
}
//GET ALL PRODUCTS AND PRODUCT ATTRIBUTES FOR PRICING
$sql = '(SELECT p.rowID as product_id, p.productname as product_name FROM products p '.$whereclause_1.' ) UNION (SELECT pat.attribute_id as product_id, pat.item_name as product_name FROM products_attributes_items pat '.$whereclause_2.' )';
}
elseif (isset($criterias['list']) && $criterias['list'] =='config'){
//SET SPECIFIC WHERECLAUSE
if ($whereclause == ''){
$whereclause_1 = 'WHERE p.salesflag = 1 AND p.status = 1 AND p.configurable = 0 ';
$whereclause_2 = 'WHERE pag.group_status = 1';
} else {
$whereclause_1 = $whereclause .' AND p.salesflag = 1 AND p.status = 1 AND p.configurable = 0 ';
list($whereclause_alt2,$condition_alt2) = getWhereclause('products_attributes_groups',$permission,$partner,'get');
$whereclause_2 = $whereclause_alt2 .' AND pag.group_status = 1';
}
//GET ALL PRODUCTS AND PRODUCT ATTRIBUTES FOR PRICING
$sql = '(SELECT p.rowID as product_id, p.productname as product_name FROM products p '.$whereclause_1.' ) UNION (SELECT pag.group_id as product_id, CONCAT(pag.group_name, " (", pag.group_name_internal,")") as product_name FROM products_attributes_groups pag '.$whereclause_2.' )';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM products '.$whereclause.' LIMIT :page,:num_products';
$sql = 'SELECT p.*, m.full_path FROM products p LEFT JOIN media m ON p.product_media = m.rowID '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
@@ -78,6 +128,12 @@ $stmt = $pdo->prepare($sql);
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
if (str_contains($whereclause_alt, ':condition')){
$stmt->bindValue('condition', $condition_alt, PDO::PARAM_STR);
}
if (str_contains($whereclause_alt2, ':condition')){
$stmt->bindValue('condition', $condition_alt2, PDO::PARAM_STR);
}
if (!empty($criterias)){
foreach ($criterias as $key => $value){
@@ -100,7 +156,7 @@ if(isset($criterias['totals']) && $criterias['totals']==''){
$messages = $stmt->fetch();
$messages = $messages[0];
}
elseif(isset($criterias['list']) && $criterias['list']==''){
elseif(isset($criterias['list'])){
//Excute Query
$stmt->execute();
//Get results

View File

@@ -0,0 +1,107 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products attributes
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND variable like :'.$v[0];
}
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 products_attributes_groups '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM products_attributes_groups '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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];
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_products_attributes, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_products_attributes, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,126 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products attributes items
//------------------------------------------
//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("attributes",$permission,$partner,'get');
//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] =='media'|| $v[0] =='success_msg'){
//do nothing
}
else {//create clause
$clause .= ' AND pat.'.$v[0].' = :'.$v[0];
}
}
//WHEN LIST = CATALOG change select based on GROUPS instead of ITEMS
if ($criterias['list'] && $criterias['list'] == 'catalog'){
$clause = str_replace('pat.group_id','pag.group_id',$clause);
}
//CREATE WHERE CLAUSE
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 products_attributes_items pat '.$whereclause.'';
} elseif ($criterias['media'] && $criterias['media'] =='all'){
//GET ALL MEDIA ITEMS RELATED TO ATTRIBUTES
$sql = 'SELECT pat.*, m.full_path, ma.full_path as alternative_media_full_path FROM products_attributes_items pat LEFT JOIN media m ON pat.item_media = m.rowID LEFT JOIN media ma ON pat.alternative_media = ma.rowID '.$whereclause;
} elseif ($criterias['list'] && $criterias['list'] =='catalog'){
//GET ALL ATTRIBUTE DATA FOR CATALOG GROUPS,ITEMS,MEDIA
$sql = 'SELECT pag.*, pat.*, m.title, m.full_path, ma.title as alternative_media_title, ma.full_path as alternative_media_full_path FROM products_attributes_groups pag JOIN products_attributes_items pat ON pag.rowID = pat.group_id LEFT JOIN media m ON pat.item_media = m.rowID LEFT JOIN media ma ON pat.alternative_media = ma.rowID '.$whereclause;
} else {
//SQL for Paging
$sql = 'SELECT * FROM products_attributes_items pat '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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($criterias['media'] && $criterias['media'] =='all'){
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
elseif($criterias['list'] && $criterias['list'] =='catalog'){
//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_products_attributes, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_products_attributes, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,178 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products catagories
//------------------------------------------
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'product_id') {
//check if multiple product_ids 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 pc.product_id IN ('.$new_querystring.')';
//remove original key/value from array
unset($criterias[$v[0]]);
}
else {
$clause .= ' AND pc.product_id IN (:'.$v[0].')';
}
}
elseif ($v[0] == 'category_id') {
//check if multiple category_ids 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);
$categoryCount = count($inputs);
//add new_querystring to clause
$clause .= ' AND pc.category_id IN ('.$new_querystring.')';
//remove original key/value from array
unset($criterias[$v[0]]);
}
else {
$clause .= ' AND pc.category_id IN (:'.$v[0].')';
$categoryCount = 1;
}
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND c.name like :'.$v[0];
}
elseif ($v[0] == 'filter') {
//build up filter
$clause .= ' AND c.filter = :'.$v[0];
}
elseif ($v[0] == 'status') {
//build up filter
$clause .= ' AND c.status = :'.$v[0];
}
else {//create clause
$clause .= ' AND pc.'.$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 products_categories '.$whereclause.'';
}
elseif(isset($criterias['list']) && $criterias['list'] =='filter'){
$sql = 'SELECT pc.product_id
FROM products_categories pc
'.$whereclause.'
GROUP BY pc.product_id
HAVING COUNT(DISTINCT pc.category_id) = '.$categoryCount;
}
else {
//SQL for Paging
$sql = 'SELECT c.* , pc.product_id FROM products_categories pc JOIN categories c ON c.rowID = pc.category_id '.$whereclause.'';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']=='filter'){
//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_products, PDO::PARAM_INT);
//$stmt->bindValue('num_products', $page_rows_products, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,133 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products_configurations
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//NEW ARRAY
$criterias = [];
$whereclause = '';
$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] =='history'|| $v[0] =='success_msg'){
//do nothing
} elseif($v[0] == 'version_status'){
$clause .= ' AND pv.status = :'.$v[0];
}
else {//create clause
$clause .= ' AND pc.'.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//ENSURE PRODUCTROWID IS SEND
if (isset($criterias['productrowid']) && $criterias['productrowid'] != ''){
//CHECK IF ALLOWED TO CRUD VERSIONS
list($whereclause_alt,$condition_alt) = getWhereclause('',$permission,$partner,'get');
$sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause_alt.'";
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['productrowid']]);
$product_data = $stmt->fetch();
$product_owner = ($product_data['rowID'])? 1 : 0;
//IF PRODUCT IS OWNED THEN CRUD is ALLOWED
if ($product_owner === 1 ){
//Define Query
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM products_configurations pc '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for Paging
$sql = 'SELECT * FROM products_configurations pc '.$whereclause.'';
}
else {
//SQL for Paging include name from different tables
$sql = 'SELECT pc.*, pv.config,pv.measurement,pag.group_mandatory, pag.group_type,
CASE WHEN p.rowID IS NOT NULL THEN p.productname
WHEN pag.group_id IS NOT NULL THEN pag.group_name
END AS assignment_name,
CASE WHEN p.rowID IS NOT NULL THEN "product"
WHEN pag.group_id IS NOT NULL THEN "group"
END AS type
FROM products_configurations pc
LEFT JOIN products p ON p.rowID = pc.assignment
LEFT JOIN products_attributes_groups pag ON pag.group_id = pc.assignment
LEFT JOIN products_versions pv ON pv.rowID = pc.version '.$whereclause;
}
$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);
}
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']==''){
//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_products, PDO::PARAM_INT);
//$stmt->bindValue('num_products', $page_rows_products, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,125 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products
//------------------------------------------
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
else {//create clause
$clause .= ' AND '.$v[0].' = :'.$v[0];
}
}
if ($whereclause == '' && $clause !=''){
$whereclause = 'WHERE '.substr($clause, 4);
} else {
$whereclause .= $clause;
}
}
//ENSURE PRODUCTROWID IS SEND
if (isset($criterias['product_id']) && $criterias['product_id'] != ''){
//CHECK IF ALLOWED TO CRUD VERSIONS
$sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'";
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['product_id']]);
$product_data = $stmt->fetch();
$product_owner = ($product_data['rowID'])? 1 : 0;
//IF PRODUCT IS OWNED THEN CRUD is ALLOWED
if ($product_owner === 1 ){
//Define Query
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
$sql = 'SELECT count(*) as count FROM products_media '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for Paging
$sql = 'SELECT * FROM products_media '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT p_m.*, m.full_path FROM products_media p_m LEFT JOIN media m ON p_m.media_id = m.rowID '.$whereclause.'';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']==''){
//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_products, PDO::PARAM_INT);
//$stmt->bindValue('num_products', $page_rows_products, PDO::PARAM_INT);
//Excute 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

@@ -12,20 +12,7 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE p.accounthierarchy like "'.$condition.'"';
break;
}
list($whereclause,$condition) = getWhereclauselvl2("software",$permission,$partner,'get');
//NEW ARRAY
$criterias = [];
@@ -61,7 +48,8 @@ if(isset($get_content) && $get_content!=''){
$clause .= ' AND ps.status = :'.$v[0];
}
elseif ($v[0] == 'hw_version') {
//build up search
//build up search - translate hardware version for comparison
$criterias[$v[0]] = translateDeviceHardwareVersion($criterias[$v[0]]);
$clause .= ' AND ps.hw_version = :'.$v[0];
}
else {//create clause
@@ -162,9 +150,11 @@ if (!isset($criterias['productrowid']) && isset($criterias['sn']) && $criterias[
//check if current version is send and update the equipment record
if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
// Translate hardware version to standardized format
$translated_hw_version = translateDeviceHardwareVersion($criterias['hw_version']);
$sql = 'UPDATE equipment SET hw_version = ?, updatedby = ? WHERE serialnumber = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['hw_version'],$username,$criterias['sn']]);
$stmt->execute([$translated_hw_version,$username,$criterias['sn']]);
}
//GET PRODUCTCODE, SW_VERSION_UPGRADE, HW_VERSION from equipment SN

View File

@@ -0,0 +1,122 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products Software Assignment
//------------------------------------------
//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,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND (product_id like :'.$v[0].' OR software_version_id like :'.$v[0].')';
}
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 products_software_assignment '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for list
$sql = 'SELECT * FROM products_software_assignment '.$whereclause.' ORDER BY created DESC';
}
else {
if (isset($criterias['product_id'])) {
// No paging for specific product
$sql = 'SELECT * FROM products_software_assignment '.$whereclause.' ORDER BY created DESC';
$stmt = $pdo->prepare($sql);
} else {
// Paged
$sql = 'SELECT * FROM products_software_assignment '.$whereclause.' ORDER BY created DESC LIMIT :page,:num_assignments';
$stmt = $pdo->prepare($sql);
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_software_assignment, PDO::PARAM_INT);
$stmt->bindValue('num_assignments', $page_rows_software_assignment, PDO::PARAM_INT);
}
}
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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 {
if (isset($criterias['product_id'])) {
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
//Send results
echo json_encode($messages);
?>

View File

@@ -0,0 +1,121 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//------------------------------------------
// Products Software Licenses
//------------------------------------------
//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("products_software_licenses",$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND (license_key like :'.$v[0].')';
}
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 products_software_licenses l '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for list
$sql = 'SELECT l.*, v.name as version_name, v.version, e.serialnumber as assigned_serial
FROM products_software_licenses l
LEFT JOIN products_software_versions v ON l.version_id = v.rowID
LEFT JOIN equipment e ON l.license_key = e.sw_version_license
'.$whereclause.' ORDER BY l.created DESC';
}
else {
//SQL for paged
$sql = 'SELECT l.*, v.name as version_name, v.version, e.serialnumber as assigned_serial
FROM products_software_licenses l
LEFT JOIN products_software_versions v ON l.version_id = v.rowID
LEFT JOIN equipment e ON l.license_key = e.sw_version_license
'.$whereclause.' ORDER BY l.created DESC LIMIT :page,:num_licenses';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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) * 50, PDO::PARAM_INT);
$stmt->bindValue('num_licenses', 50, PDO::PARAM_INT);
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//Send results
echo json_encode($messages);
?>

View File

@@ -0,0 +1,111 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products Software Upgrade Paths
//------------------------------------------
//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,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND (description like :'.$v[0].')';
}
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 products_software_upgrade_paths '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for list
$sql = 'SELECT * FROM products_software_upgrade_paths '.$whereclause.' ORDER BY created DESC';
}
else {
//SQL for paged
$sql = 'SELECT * FROM products_software_upgrade_paths '.$whereclause.' ORDER BY created DESC LIMIT :page,:num_paths';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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) * 50, PDO::PARAM_INT); // Assuming 50 per page
$stmt->bindValue('num_paths', 50, PDO::PARAM_INT);
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//Send results
echo json_encode($messages);
?>

View File

@@ -0,0 +1,112 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Products Software Versions
//------------------------------------------
//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,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND (name like :'.$v[0].' OR version like :'.$v[0].' OR description like :'.$v[0].')';
}
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 products_software_versions '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for list
$sql = 'SELECT * FROM products_software_versions '.$whereclause.' ORDER BY created DESC';
}
else {
//SQL for paged
$sql = 'SELECT * FROM products_software_versions '.$whereclause.' ORDER BY created DESC LIMIT :page,:num_versions';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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_software_versions, PDO::PARAM_INT);
$stmt->bindValue('num_versions', $page_rows_software_versions, PDO::PARAM_INT);
//Execute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//Send results
echo json_encode($messages);
?>

View File

@@ -14,19 +14,6 @@ if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} el
//default whereclause
$whereclause = '';
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
default:
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like "'.$condition.'"';
break;
}
//NEW ARRAY
$criterias = [];
$clause = '';
@@ -63,7 +50,10 @@ if(isset($get_content) && $get_content!=''){
if (isset($criterias['productrowid']) && $criterias['productrowid'] != ''){
//CHECK IF ALLOWED TO CRUD VERSIONS
$sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'";
list($whereclause2,$condition) = getWhereclause('',$permission,$partner,'get');
$sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause2.'";
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['productrowid']]);
$product_data = $stmt->fetch();

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

@@ -11,24 +11,8 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//NEW ARRAY
$criterias = [];

View File

@@ -11,24 +11,8 @@ $pdo = dbConnect($dbname);
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
switch ($permission) {
case '4':
$whereclause = '';
break;
case '3':
$whereclause = '';
break;
case '2':
$condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
$whereclause = 'WHERE accounthierarchy like :condition ';
break;
default:
$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 ';
break;
}
//NEW ARRAY
$criterias = [];

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);
}
?>

144
api/v2/get/shipping.php Normal file
View File

@@ -0,0 +1,144 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// shipping
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND name like :'.$v[0];
}
elseif ($v[0] == 'weight_total') {
//build up search
$clause .= ' AND weight_from <= :'.$v[0].' AND (weight_to >= :'.$v[0].' OR weight_to = 0)';
}
elseif ($v[0] == 'price_total') {
//build up search
$clause .= ' AND price_from <= :'.$v[0].' AND (price_to >= :'.$v[0].' OR price_to = 0)';
}
elseif ($v[0] == 'country') {
if ($v[1] != ''){
//CHECK IF SPECIFIC COUNTRY RECORD IS FOUND OTHERWISE CHECK FOR GLOBAL SHIPPING RECORDS
$sql = "SELECT COUNT(*) as count FROM shipping WHERE FIND_IN_SET(?, countries)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$v[1]]);
$result = $stmt->fetch();
$result = $result[0];
if ($result > 0) {
$clause .= ' AND FIND_IN_SET(:'.$v[0].', countries) > 0';
} else {
//GET ALL COUNTRIES
$clause .= ' AND countries = ""';
}
}
else {
//GET ALL COUNTRIES
$clause .= ' AND countries = :'.$v[0];
}
}
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 shipping '.$whereclause.'';
}
elseif(isset($criterias['list']) && $criterias['list'] =='methods'){
$sql = 'SELECT * FROM shipping '.$whereclause;
}
else {
//SQL for Paging
$sql = 'SELECT * FROM shipping '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']=='methods'){
$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_shipping, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_shipping, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,452 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//------------------------------------------
// Software Available Check API
// Returns boolean indicating if software updates are available
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//NEW ARRAY
$criterias = [];
$clause = '';
$debug = [];
//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 (debug) {
$debug['request_parameters'] = $criterias;
$debug['timestamp'] = date('Y-m-d H:i:s');
}
// IF SN IS PROVIDED, CHECK FOR AVAILABLE UPGRADES
if (isset($criterias['sn']) && $criterias['sn'] != ''){
//default response
$software_available = "no";
//check if current version is send and update the equipment record
if(isset($criterias['version']) && $criterias['version'] !=''){
$sql = 'UPDATE equipment SET sw_version = ?, updatedby = ? WHERE serialnumber = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['version'],$username,$criterias['sn']]);
}
//check if current hw_version is send and update the equipment record
if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
// Translate hardware version to standardized format
$translated_hw_version = translateDeviceHardwareVersion($criterias['hw_version']);
$sql = 'UPDATE equipment SET hw_version = ?, updatedby = ? WHERE serialnumber = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$translated_hw_version,$username,$criterias['sn']]);
}
//GET EQUIPMENT AND PRODUCT DATA BASED ON SERIAL NUMBER
$sql = 'SELECT
p.rowID as product_rowid,
p.productcode,
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
WHERE e.serialnumber = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['sn']]);
$equipment_data = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$equipment_data) {
$messages = ["error" => "No equipment found for serialnumber"];
} else {
$product_rowid = $equipment_data['product_rowid'];
$productcode = $equipment_data['productcode'];
$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) {
$debug['equipment_data'] = [
'product_rowid' => $product_rowid,
'productcode' => $productcode,
'current_sw_version_raw' => $current_sw_version,
'hw_version' => $hw_version,
'sw_version_upgrade' => $sw_version_upgrade
];
}
// Normalize software version for comparison (lowercase, trim leading zeros)
$current_sw_version = strtolower(ltrim($current_sw_version, '0'));
// Translate incoming hw_version parameter for comparison if provided
$comparison_hw_version = $hw_version;
$hw_version_from_request = null;
if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
$hw_version_from_request = $criterias['hw_version'];
$comparison_hw_version = translateDeviceHardwareVersion($criterias['hw_version']);
}
if (debug) {
$debug['normalized_data'] = [
'current_sw_version' => $current_sw_version,
'hw_version_from_request' => $hw_version_from_request,
'comparison_hw_version' => $comparison_hw_version,
'hw_version_valid' => ($comparison_hw_version !== '')
];
}
// Check if hardware version is invalid (all zeros)
if ($hw_version_from_request && $comparison_hw_version === '') {
$messages = ["software_available" => "error", "error" => "Invalid hardware version (000000) - device may not be properly initialized"];
if (debug) {
$messages['debug'] = $debug;
}
echo json_encode($messages, JSON_UNESCAPED_UNICODE);
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,
psv.version,
psv.name,
psv.description,
psv.mandatory,
psv.latest,
psv.hw_version,
psv.file_path
FROM products_software_assignment psa
JOIN products_software_versions psv ON psa.software_version_id = psv.rowID
WHERE psa.product_id = ?
AND psa.status = 1
AND (psv.hw_version = ? OR psv.hw_version IS NULL OR psv.hw_version = "")';
$stmt = $pdo->prepare($sql);
$stmt->execute([$product_rowid, $comparison_hw_version]);
$versions = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (debug) {
$debug['active_assignments'] = [
'count' => count($versions),
'versions' => array_map(function($v) {
return [
'version_id' => $v['version_id'],
'version' => $v['version'],
'name' => $v['name'],
'hw_version' => $v['hw_version'],
'latest' => $v['latest']
];
}, $versions)
];
}
if (empty($versions)) {
// No versions available
$software_available = "no";
if (debug) {
$debug['decision'] = 'No active software assignments found';
}
} else {
$available_upgrades = 0;
$has_priced_options = false;
$has_latest_version_different = false;
$version_details = []; // Track version details for downgrade prevention
if (debug) {
$debug['version_checks'] = [];
}
foreach ($versions as $version) {
//Normalize version for comparison (lowercase, trim leading zeros)
$normalized_version = strtolower(ltrim($version['version'], '0'));
//Skip if this is the current version
if ($current_sw_version && $normalized_version == $current_sw_version) {
continue;
}
//Check if this version should be shown (same logic as software_update)
$show_version = false;
$final_price = '0.00';
$decision_reason = '';
if (debug) {
$version_check = [
'version' => $version['version'],
'name' => $version['name'],
'normalized' => $normalized_version,
'is_current' => ($current_sw_version && $normalized_version == $current_sw_version)
];
}
if (!$current_sw_version || $current_sw_version == '') {
//No current version - show all
$show_version = true;
$decision_reason = 'No current version - showing all';
} else {
//Check if this version is part of ANY upgrade path system (either FROM or TO)
$sql = 'SELECT COUNT(*) as path_count
FROM products_software_upgrade_paths
WHERE (to_version_id = ? OR from_version_id = ?) AND is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$version['version_id'], $version['version_id']]);
$path_check = $stmt->fetch(PDO::FETCH_ASSOC);
if (debug) {
$version_check['path_count'] = $path_check['path_count'];
}
if ($path_check['path_count'] == 0) {
//Not part of any upgrade path system - show as free upgrade
$show_version = true;
$decision_reason = 'No upgrade paths defined - showing as free';
} else {
//Part of an upgrade path system
//Only show if there's an explicit path FROM current version TO this version
$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)) = ?
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
$show_version = true;
$final_price = $upgrade_path['price'] ?? '0.00';
$decision_reason = 'Found upgrade path from current with price: ' . $final_price;
} else {
$decision_reason = 'Has upgrade paths but none from current version';
}
}
}
if (debug) {
$version_check['show_version'] = $show_version;
$version_check['reason'] = $decision_reason;
}
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
$sql = 'SELECT status, starts_at, expires_at
FROM products_software_licenses
WHERE license_key = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sw_version_license]);
$license = $stmt->fetch(PDO::FETCH_ASSOC);
if ($license && $license['status'] == 1) {
$now = date('Y-m-d H:i:s');
$start_at = $license['starts_at'];
$expires_at = $license['expires_at'];
//Check if license is within valid date range
if ((!$start_at || $start_at <= $now) && (!$expires_at || $expires_at >= $now)) {
$final_price = '0.00';
}
}
}
// Store version details for downgrade prevention check (after license application)
$version_details[] = [
'show_version' => true,
'final_price' => $final_price
];
// Check for priced options
if ($final_price > 0) {
$has_priced_options = true;
}
// Check if there's a "latest" flagged version that's different from current
if ($version['latest'] == 1 && $normalized_version != $current_sw_version) {
$has_latest_version_different = true;
}
if (debug) {
$version_check['final_price'] = $final_price;
$version_check['has_priced_option'] = ($final_price > 0);
$version_check['is_latest_different'] = ($version['latest'] == 1 && $normalized_version != $current_sw_version);
}
}
if (debug) {
$debug['version_checks'][] = $version_check;
}
}
//PREVENT DOWNGRADE FROM PAID VERSION TO FREE VERSION (if config enabled)
if (defined('PREVENT_PAID_VERSION_DOWNGRADE') && PREVENT_PAID_VERSION_DOWNGRADE && $current_sw_version) {
// Check if user is currently on a paid version (check if there was a paid upgrade path TO current version)
$sql = 'SELECT COUNT(*) as paid_to_current
FROM products_software_upgrade_paths pup
JOIN products_software_versions to_ver ON pup.to_version_id = to_ver.rowID
WHERE LOWER(TRIM(LEADING "0" FROM to_ver.version)) = ?
AND pup.price > 0
AND pup.is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$current_sw_version]);
$paid_check = $stmt->fetch(PDO::FETCH_ASSOC);
$is_current_paid_version = ($paid_check['paid_to_current'] > 0);
if (debug) {
$debug['downgrade_prevention'] = [
'enabled' => true,
'current_version' => $current_sw_version,
'is_current_paid_version' => $is_current_paid_version
];
}
// If current version is paid, recalculate available_upgrades excluding free versions
if ($is_current_paid_version) {
$available_upgrades_before = $available_upgrades;
$available_upgrades = 0;
// Recount only paid upgrades (exclude free versions)
foreach ($version_details as $detail) {
if ($detail['show_version'] && floatval($detail['final_price']) > 0) {
$available_upgrades++;
}
}
if (debug) {
$debug['downgrade_prevention']['available_upgrades_before'] = $available_upgrades_before;
$debug['downgrade_prevention']['available_upgrades_after'] = $available_upgrades;
$debug['downgrade_prevention']['message'] = 'Excluded free versions to prevent downgrade from paid version';
}
}
}
// Simple logic: if any upgrades are available to show, return "yes"
if ($available_upgrades > 0) {
$software_available = "yes";
$availability_reason = "Software upgrades available";
} else {
$software_available = "no";
$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,
'reason' => $availability_reason
];
}
}
$messages = ["software_available" => $software_available];
if (debug) {
debuglog(json_encode($debug));
}
}
} else {
$messages = ["error" => "No serialnumber found"];
}
//Encrypt results
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

View File

@@ -0,0 +1,284 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Secure Software Download API
// Validates time-based URL token and streams firmware files
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
// STEP 1: Validate token parameter exists
if (!isset($_GET['token']) || $_GET['token'] == '') {
http_response_code(400);
echo json_encode(["error" => "MISSING_TOKEN", "message" => "Download token required"]);
exit;
}
$download_start = microtime(true);
// URL decode the token in case it was encoded during transmission
$url_token = urldecode($_GET['token']);
// STEP 2: Validate and decode URL token using standalone secure function
$token_data = validate_secure_download_token($url_token);
if (isset($token_data['error'])) {
http_response_code(403);
echo json_encode([
"error" => $token_data['error'],
"message" => $token_data['message']
]);
exit;
}
$serial_number = $token_data['sn'];
$version_id = $token_data['version_id'];
// STEP 3: Get equipment data (reuse software_update.php logic)
$sql = 'SELECT
e.rowID as equipment_rowid,
e.productrowid,
e.sw_version as current_sw_version,
e.hw_version,
e.sw_version_license,
e.accounthierarchy,
p.productcode
FROM equipment e
JOIN products p ON e.productrowid = p.rowID
WHERE e.serialnumber = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$serial_number]);
$equipment = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$equipment) {
http_response_code(404);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'Equipment not found',
'createdby' => $username
]);
echo json_encode(["error" => "EQUIPMENT_NOT_FOUND", "message" => "Equipment not found"]);
exit;
}
// STEP 4: Get version data
$sql = 'SELECT
psv.rowID,
psv.version,
psv.name,
psv.file_path,
psv.hw_version,
psv.status
FROM products_software_versions psv
WHERE psv.rowID = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$version_id]);
$version = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$version) {
http_response_code(404);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'Version not found',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "VERSION_NOT_FOUND", "message" => "Version not found"]);
exit;
}
if ($version['status'] != 1) {
http_response_code(403);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'Version inactive',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "VERSION_INACTIVE", "message" => "Version is not active"]);
exit;
}
// STEP 5: Check version is assigned to product
$sql = 'SELECT COUNT(*) as assigned
FROM products_software_assignment
WHERE product_id = ? AND software_version_id = ? AND status = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$equipment['productrowid'], $version_id]);
$assignment = $stmt->fetch(PDO::FETCH_ASSOC);
if ($assignment['assigned'] == 0) {
http_response_code(403);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'Version not assigned to product',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "VERSION_NOT_ASSIGNED", "message" => "Version not assigned to product"]);
exit;
}
// STEP 6: Hardware version compatibility
// Only check if version has hw_version requirement (not NULL or empty)
// Match logic from software_update.php line 103
if ($version['hw_version'] && $version['hw_version'] != '') {
if ($equipment['hw_version'] && $version['hw_version'] != $equipment['hw_version']) {
http_response_code(403);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'Hardware version mismatch',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "HW_VERSION_MISMATCH", "message" => "Hardware version incompatible"]);
exit;
}
}
// STEP 7: License validation (reuse software_update.php logic)
$current_sw_version = $equipment['current_sw_version'];
// Get upgrade pricing
$sql = 'SELECT price, 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 from_ver.version = ? AND pup.is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$version_id, $current_sw_version]);
$upgrade_pricing = $stmt->fetch(PDO::FETCH_ASSOC);
$final_price = $upgrade_pricing['price'] ?? '0.00';
if ($final_price > 0) {
// Paid upgrade - check license
$sw_version_license = $equipment['sw_version_license'];
if (!$sw_version_license) {
http_response_code(402);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'License required',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode([
"error" => "LICENSE_REQUIRED",
"message" => "Valid license required",
"price" => $final_price,
"currency" => $upgrade_pricing['currency']
]);
exit;
}
// Validate license
$sql = 'SELECT status, starts_at, expires_at
FROM products_software_licenses
WHERE license_key = ? AND equipment_id = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sw_version_license, $equipment['equipment_rowid']]);
$license = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$license || $license['status'] != 1) {
http_response_code(402);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'Invalid license',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "INVALID_LICENSE", "message" => "License is invalid"]);
exit;
}
// Check license date validity
$now = date('Y-m-d H:i:s');
if (($license['starts_at'] && $license['starts_at'] > $now) ||
($license['expires_at'] && $license['expires_at'] < $now)) {
http_response_code(402);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'License expired',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "LICENSE_EXPIRED", "message" => "License is expired"]);
exit;
}
}
// STEP 8: Build file path and verify exists
$firmware_path = dirname(__FILE__, 4) . '/firmware/' . $version['file_path'];
if (!file_exists($firmware_path)) {
http_response_code(404);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'status' => 'failed',
'error_message' => 'File not found on server',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
echo json_encode(["error" => "FILE_NOT_FOUND", "message" => "Firmware file not available"]);
exit;
}
// STEP 9: Stream file and log
$file_size = filesize($firmware_path);
try {
// Log successful download before streaming
$download_time = round(microtime(true) - $download_start);
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'file_size' => $file_size,
'download_time_seconds' => $download_time,
'status' => 'success',
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
// Stream file (function handles path traversal check and exits after streaming)
stream_file_download($firmware_path, $version['file_path']);
} catch (Exception $e) {
log_download([
'user_id' => $user_data['id'],
'version_id' => $version_id,
'file_size' => $file_size,
'status' => 'failed',
'error_message' => $e->getMessage(),
'accounthierarchy' => $equipment['accounthierarchy'],
'createdby' => $username
]);
http_response_code(500);
echo json_encode(["error" => "DOWNLOAD_FAILED", "message" => "Download failed"]);
}
?>

View File

@@ -0,0 +1,544 @@
<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
//------------------------------------------
// Products Software Upgrades API
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//NEW ARRAY
$criterias = [];
$clause = '';
$debug = [];
//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 (debug) {
$debug['request_parameters'] = $criterias;
$debug['timestamp'] = date('Y-m-d H:i:s');
}
// IF SN IS PROVIDED, HANDLE UPGRADE OPTIONS
if (isset($criterias['sn']) && $criterias['sn'] != ''){
//default output (array of options)
$output = [];
//check if current version is send and update the equipment record
if(isset($criterias['version']) && $criterias['version'] !=''){
$sql = 'UPDATE equipment SET sw_version = ?, updatedby = ? WHERE serialnumber = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$criterias['version'],$username,$criterias['sn']]);
}
//check if current hw_version is send and update the equipment record
if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
// Translate hardware version to standardized format
$translated_hw_version = translateDeviceHardwareVersion($criterias['hw_version']);
$sql = 'UPDATE equipment SET hw_version = ?, updatedby = ? WHERE serialnumber = ? ';
$stmt = $pdo->prepare($sql);
$stmt->execute([$translated_hw_version,$username,$criterias['sn']]);
}
//GET EQUIPMENT AND PRODUCT DATA BASED ON SERIAL NUMBER
$sql = "SELECT
p.rowID as product_rowid,
p.productcode,
e.sw_version as current_sw_version,
e.hw_version,
e.sw_version_license,
e.sw_version_upgrade,
e.rowID as equipment_rowid,
partner.*
FROM equipment e
JOIN products p ON e.productrowid = p.rowID
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);
if (!$equipment_data) {
$messages = ["error" => "No equipment found for serialnumber"];
} else {
$product_rowid = $equipment_data['product_rowid'];
$productcode = $equipment_data['productcode'];
$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_upgrade' => $sw_version_upgrade
];
}
// Normalize software version for comparison (lowercase, trim leading zeros)
$current_sw_version = strtolower(ltrim($current_sw_version, '0'));
// Translate incoming hw_version parameter for comparison if provided
$comparison_hw_version = $hw_version;
$hw_version_from_request = null;
if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
$hw_version_from_request = $criterias['hw_version'];
$comparison_hw_version = translateDeviceHardwareVersion($criterias['hw_version']);
}
if (debug) {
$debug['normalized_data'] = [
'current_sw_version' => $current_sw_version,
'hw_version_from_request' => $hw_version_from_request,
'comparison_hw_version' => $comparison_hw_version,
'hw_version_valid' => ($comparison_hw_version !== '')
];
}
// Check if hardware version is invalid (all zeros)
if ($hw_version_from_request && $comparison_hw_version === '') {
$messages = ["error" => "Invalid hardware version (000000) - device may not be properly initialized"];
if (debug) {
$messages['debug'] = $debug;
}
echo json_encode($messages, JSON_UNESCAPED_UNICODE);
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,
psv.version,
psv.name,
psv.description,
psv.mandatory,
psv.latest,
psv.hw_version,
psv.file_path
FROM products_software_assignment psa
JOIN products_software_versions psv ON psa.software_version_id = psv.rowID
WHERE psa.product_id = ?
AND psa.status = 1
AND (psv.hw_version = ? OR psv.hw_version IS NULL OR psv.hw_version = "")';
$stmt = $pdo->prepare($sql);
$stmt->execute([$product_rowid, $comparison_hw_version]);
$versions = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (debug) {
$debug['active_assignments'] = [
'count' => count($versions),
'versions' => array_map(function($v) {
return [
'version_id' => $v['version_id'],
'version' => $v['version'],
'name' => $v['name'],
'hw_version' => $v['hw_version'],
'latest' => $v['latest']
];
}, $versions)
];
}
if (empty($versions)) {
$messages = ["error" => "No active software assignments found for product"];
if (debug) {
$messages['debug'] = $debug;
}
} else {
// First check if current version has paid upgrade paths FROM it
$has_paid_upgrade_from_current = false;
if ($current_sw_version) {
$sql = 'SELECT COUNT(*) as paid_count
FROM products_software_upgrade_paths pup
JOIN products_software_versions from_ver ON pup.from_version_id = from_ver.rowID
WHERE LOWER(TRIM(LEADING "0" FROM from_ver.version)) = ?
AND pup.price > 0
AND pup.is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$current_sw_version]);
$paid_check = $stmt->fetch(PDO::FETCH_ASSOC);
$has_paid_upgrade_from_current = ($paid_check['paid_count'] > 0);
}
if (debug) {
$debug['has_paid_upgrade_from_current'] = $has_paid_upgrade_from_current;
$debug['version_decisions'] = [];
}
foreach ($versions as $version) {
//Normalize version for comparison (lowercase, trim leading zeros)
$normalized_version = strtolower(ltrim($version['version'], '0'));
$is_current_version = ($current_sw_version && $normalized_version == $current_sw_version);
//All versions with matching HW are potential upgrades
$show_version = false;
$final_price = '0.00';
$final_currency = '';
$is_current = false;
$decision_reason = '';
if (debug) {
$version_debug = [
'version' => $version['version'],
'name' => $version['name'],
'normalized_version' => $normalized_version,
'is_current_version' => $is_current_version,
'latest' => $version['latest']
];
}
if (!$current_sw_version || $current_sw_version == '') {
//No current version - show all as free upgrades
if (!$is_current_version) {
$show_version = true;
$decision_reason = 'No current version stored - showing as free upgrade';
} else {
$decision_reason = 'Skipped - is current version but no upgrades scenario';
}
} else {
//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 - 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
FROM products_software_upgrade_paths
WHERE (to_version_id = ? OR from_version_id = ?) AND is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$version['version_id'], $version['version_id']]);
$path_check = $stmt->fetch(PDO::FETCH_ASSOC);
if (debug) {
$version_debug['upgrade_path_count'] = $path_check['path_count'];
}
if ($path_check['path_count'] == 0) {
//Not part of any upgrade path system - show as free upgrade
$show_version = true;
$decision_reason = 'Showing as FREE - no upgrade paths defined for this version';
} 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)) = ?
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 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 . ') or wildcard with price: ' . $final_price . ' ' . $final_currency;
} else {
$decision_reason = 'Skipped - has upgrade paths but none FROM current version (' . $current_sw_version . ') or wildcard';
}
//If no path from current version or wildcard exists, don't show (show_version stays false)
}
}
}
if (debug) {
$version_debug['decision'] = [
'show_version' => $show_version,
'is_current' => $is_current,
'final_price' => $final_price,
'final_currency' => $final_currency,
'reason' => $decision_reason
];
}
if ($show_version) {
//Check if there's a valid license for this upgrade
$license_applied = false;
if ($final_price > 0 && $sw_version_license) {
//Check if the license is valid
$sql = 'SELECT status, starts_at, expires_at
FROM products_software_licenses
WHERE license_key = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$sw_version_license]);
$license = $stmt->fetch(PDO::FETCH_ASSOC);
if ($license && $license['status'] == 1) {
$now = date('Y-m-d H:i:s');
$start_at = $license['starts_at'];
$expires_at = $license['expires_at'];
//Check if license is within valid date range
if ((!$start_at || $start_at <= $now) && (!$expires_at || $expires_at >= $now)) {
$original_price = $final_price;
$final_price = '0.00';
$license_applied = true;
if (debug) {
$version_debug['license_applied'] = [
'license_key' => $sw_version_license,
'original_price' => $original_price,
'new_price' => $final_price
];
}
}
}
}
$entry = [
"productcode" => $productcode,
"name" => $version['name'] ?? '',
"version" => $version['version'],
"version_id" => $version['version_id'],
"description" => $version['description'] ?? '',
"hw_version" => $version['hw_version'] ?? '',
"mandatory" => $version['mandatory'] ?? '',
"latest" => $version['latest'] ?? '',
"software" => $version['file_path'] ?? '',
"source" => '',
"source_type" => '',
"price" => $final_price,
"currency" => $final_currency,
"is_current" => $is_current,
"dealer_info" => $dealer_info
];
$output[] = $entry;
}
if (debug) {
$debug['version_decisions'][] = $version_debug;
}
}
//PREVENT DOWNGRADE FROM PAID VERSION TO FREE VERSION (if config enabled)
if (defined('PREVENT_PAID_VERSION_DOWNGRADE') && PREVENT_PAID_VERSION_DOWNGRADE && $current_sw_version) {
// Check if user is currently on a paid version (check if there was a paid upgrade path TO current version)
$sql = 'SELECT COUNT(*) as paid_to_current
FROM products_software_upgrade_paths pup
JOIN products_software_versions to_ver ON pup.to_version_id = to_ver.rowID
WHERE LOWER(TRIM(LEADING "0" FROM to_ver.version)) = ?
AND pup.price > 0
AND pup.is_active = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute([$current_sw_version]);
$paid_check = $stmt->fetch(PDO::FETCH_ASSOC);
$is_current_paid_version = ($paid_check['paid_to_current'] > 0);
if (debug) {
$debug['downgrade_prevention'] = [
'enabled' => true,
'current_version' => $current_sw_version,
'is_current_paid_version' => $is_current_paid_version
];
}
// If current version is paid, remove all free versions from the output (except current)
if ($is_current_paid_version) {
$output = array_filter($output, function($option) {
$price = floatval($option['price']);
$is_current = $option['is_current'];
// Keep if it's the current version OR if it's a paid version
return $is_current || $price > 0;
});
// Re-index array after filtering
$output = array_values($output);
if (debug) {
$debug['downgrade_prevention']['filtered_count'] = count($output);
$debug['downgrade_prevention']['message'] = 'Removed free versions to prevent downgrade from paid version';
}
}
}
//GENERATE DOWNLOAD TOKENS FOR EACH OPTION
foreach ($output as &$option) {
// Generate time-based download token
$download_token = create_download_url_token($criterias['sn'], $option['version_id']);
// Create secure download URL
$download_url = 'https://'.$_SERVER['SERVER_NAME'].'/api.php/v2/software_download?token='.$download_token;
// Set source as download URL
$option['source'] = $download_url;
$option['source_type'] = 'token_url';
}
if (debug) {
$debug['final_output'] = [
'total_versions_shown' => count($output),
'versions' => array_map(function($o) {
return [
'name' => $o['name'],
'version' => $o['version'],
'price' => $o['price'],
'is_current' => $o['is_current']
];
}, $output)
];
}
// 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)) {
// Add debug as separate field in response
foreach ($messages as &$msg) {
$msg['_debug'] = $debug;
break; // Only add to first item
}
} elseif (debug && empty($output)) {
$messages = ['message' => 'No upgrades available', 'debug' => $debug];
}
}
}
}
else {
$messages = ["error" => "No serialnumber found"];
}
//Encrypt results
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

102
api/v2/get/taxes.php Normal file
View File

@@ -0,0 +1,102 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Taxes
//------------------------------------------
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND name like :'.$v[0];
}
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 taxes '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM taxes '.$whereclause;
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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];
}
else {
//Excute 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

@@ -0,0 +1,93 @@
<?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];
}
}
$token_refresh = $criterias['refreshkey'] ?? null;
if (!$token_refresh) {
http_response_code(400);
exit(json_encode(['error_code' => 'API_INPUT_1','error' => 'refreshkey is required']));
}
//GET USER_DATA
$stmt = $pdo->prepare('SELECT * FROM users WHERE refreshkey = ?');
$stmt->execute([$token_refresh]);
if ($stmt->rowCount() == 1) {
//Get results
$user_data = $stmt->fetch();
//Check valid userkey
$valid_key = strtotime('+30 minutes',strtotime($user_data['lastlogin']));
$valid = ($valid_key <= time())?0:1;
//REFRESH USERKEY
if ($user_data['userkey'] != '' && $valid == 0){
$user_data['userkey'] = bin2hex(random_bytes(25));
$sql_userkey = 'UPDATE users SET userkey = ? WHERE id = ?';
$stmt_userkey = $pdo->prepare($sql_userkey);
$stmt_userkey->execute([$user_data['userkey'], $user_data['id']]);
}
//REFRESH USERKEY
if ($user_data['service'] != '' && $valid == 0){
$user_data['service'] = bin2hex(random_bytes(25));
$sql_service = 'UPDATE users SET service = ? WHERE id = ?';
$stmt_service = $pdo->prepare($sql_service);
$stmt_service->execute([$user_data['service'], $user_data['id']]);
}
//Refresh REFRESHKEY
$user_data['refreshkey'] = bin2hex(random_bytes(25));
$sql_refreshkey = 'UPDATE users SET refreshkey = ? WHERE id = ?';
$stmt_refreshkey = $pdo->prepare($sql_refreshkey);
$stmt_refreshkey->execute([$user_data['refreshkey'], $user_data['id']]);
$token = createCommunicationToken($user_data['userkey']);
//RETURN JWT AND CLIENTSECRET
$user = array(
'clientID' => $user_data['username'],
'token' => $token,
'token_valid' => date('Y-m-d H:i:s',time() + 1800),
'userkey' => $user_data['userkey'],
'refreshkey' => $user_data['refreshkey'],
'language' => $user_data['language']
);
//+++++++++++++++++++++++++++++++++++++++++++
//Return as JSON
//+++++++++++++++++++++++++++++++++++++++++++
echo json_encode($user, JSON_UNESCAPED_UNICODE);
}
else {
http_response_code(404);
exit(json_encode(['error_code' => 'API_NOT_FOUND','error' => 'Refresh not succesfull']));
}
?>

120
api/v2/get/transactions.php Normal file
View File

@@ -0,0 +1,120 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// transactions
//------------------------------------------
//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("transactions",$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND tx.name like :'.$v[0];
}
else {//create clause
$clause .= ' AND tx.'.$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 transactions tx '.$whereclause.'';
}
elseif (isset($criterias['list']) && $criterias['list'] =='order'){
//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
FROM transactions tx
left join invoice inv ON tx.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 '.$whereclause;
}
else {
//SQL for Paging
$sql = 'SELECT * FROM transactions tx '.$whereclause.' ORDER BY tx.created DESC LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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']=='order'){
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
$messages = transformOrderData($messages);
}
else {
$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
$stmt->bindValue('page', ($current_page - 1) * $page_rows_transactions, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_transactions, PDO::PARAM_INT);
//Excute 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

@@ -0,0 +1,112 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// transactions_items
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclauselvl2('transactions',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND name like :'.$v[0];
}
elseif (($v[0] == 'account_id')){//create clause
$clause .= ' AND tx.'.$v[0].' = :'.$v[0];
}
else {//create clause
$clause .= ' AND tai.'.$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 transactions_items tai '.$whereclause.'';
}
else {
//SQL for Paging
//$sql = 'SELECT ta.*, tai.* FROM transactions ta left join transactions_items tai ON ta.id = tai.txn_id '.$whereclause;
$sql ='SELECT tx.*, tai.*, p.productname as item_name, m.full_path FROM transactions tx left join transactions_items tai ON tx.id = tai.txn_id LEFT JOIN media m ON tai.item_id = m.rowID LEFT JOIN products p ON tai.item_id = p.rowID '.$whereclause;
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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];
}
else {
//$current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
//$stmt->bindValue('page', ($current_page - 1) * $page_rows_transactions, PDO::PARAM_INT);
//$stmt->bindValue('num_products', $page_rows_transactions, PDO::PARAM_INT);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
$messages = transformOrders($messages);
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

117
api/v2/get/translations.php Normal file
View File

@@ -0,0 +1,117 @@
<?php
defined($security_key) or exit;
//------------------------------------------
// Translations
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}
//default whereclause
$whereclause = '';
list($whereclause,$condition) = getWhereclause('text_variables',$permission,$partner,'get');
//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] =='history'|| $v[0] =='success_msg'){
//do nothing
}
elseif ($v[0] == 'generatefile') {
$clause .= ' AND language_key = :'.$v[0];
}
elseif ($v[0] == 'search') {
//build up search
$clause .= ' AND variable like :'.$v[0];
}
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 text_variables tv '.$whereclause.'';
} elseif (isset($criterias['generatefile']) && $criterias['generatefile'] !=''){
$sql = 'SELECT tv.variable,tvt.translation FROM text_variables tv JOIN text_variables_translations tvt ON tv.rowID = tvt.variable_ID '.$whereclause.'';
}
else {
//SQL for Paging
$sql = 'SELECT * FROM text_variables tv '.$whereclause.' LIMIT :page,:num_products';
}
$stmt = $pdo->prepare($sql);
//Bind to query
if (str_contains($whereclause, ':condition')){
$stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
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);
}
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['generatefile']) && $criterias['generatefile'] !=''){
//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_translations, PDO::PARAM_INT);
$stmt->bindValue('num_products', $page_rows_translations, PDO::PARAM_INT);
//Excute Query
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//Send results
echo $messages;
?>

Some files were not shown because too many files have changed in this diff Show More